babylon.no-module.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  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 if (otherMesh.subMeshes) {
  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. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * 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)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * 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)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * 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)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * 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)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * 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)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * 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)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * 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)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * 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)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * 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)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * 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)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * 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)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * 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)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. var KeyboardEventTypes = /** @class */ (function () {
  1242. function KeyboardEventTypes() {
  1243. }
  1244. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1245. get: function () {
  1246. return KeyboardEventTypes._KEYDOWN;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1252. get: function () {
  1253. return KeyboardEventTypes._KEYUP;
  1254. },
  1255. enumerable: true,
  1256. configurable: true
  1257. });
  1258. KeyboardEventTypes._KEYDOWN = 0x01;
  1259. KeyboardEventTypes._KEYUP = 0x02;
  1260. return KeyboardEventTypes;
  1261. }());
  1262. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1263. var KeyboardInfo = /** @class */ (function () {
  1264. function KeyboardInfo(type, event) {
  1265. this.type = type;
  1266. this.event = event;
  1267. }
  1268. return KeyboardInfo;
  1269. }());
  1270. BABYLON.KeyboardInfo = KeyboardInfo;
  1271. /**
  1272. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1273. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1274. */
  1275. var KeyboardInfoPre = /** @class */ (function (_super) {
  1276. __extends(KeyboardInfoPre, _super);
  1277. function KeyboardInfoPre(type, event) {
  1278. var _this = _super.call(this, type, event) || this;
  1279. _this.skipOnPointerObservable = false;
  1280. return _this;
  1281. }
  1282. return KeyboardInfoPre;
  1283. }(KeyboardInfo));
  1284. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1285. })(BABYLON || (BABYLON = {}));
  1286. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1287. var BABYLON;
  1288. (function (BABYLON) {
  1289. var PointerEventTypes = /** @class */ (function () {
  1290. function PointerEventTypes() {
  1291. }
  1292. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1293. get: function () {
  1294. return PointerEventTypes._POINTERDOWN;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1300. get: function () {
  1301. return PointerEventTypes._POINTERUP;
  1302. },
  1303. enumerable: true,
  1304. configurable: true
  1305. });
  1306. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1307. get: function () {
  1308. return PointerEventTypes._POINTERMOVE;
  1309. },
  1310. enumerable: true,
  1311. configurable: true
  1312. });
  1313. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1314. get: function () {
  1315. return PointerEventTypes._POINTERWHEEL;
  1316. },
  1317. enumerable: true,
  1318. configurable: true
  1319. });
  1320. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1321. get: function () {
  1322. return PointerEventTypes._POINTERPICK;
  1323. },
  1324. enumerable: true,
  1325. configurable: true
  1326. });
  1327. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1328. get: function () {
  1329. return PointerEventTypes._POINTERTAP;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1335. get: function () {
  1336. return PointerEventTypes._POINTERDOUBLETAP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. PointerEventTypes._POINTERDOWN = 0x01;
  1342. PointerEventTypes._POINTERUP = 0x02;
  1343. PointerEventTypes._POINTERMOVE = 0x04;
  1344. PointerEventTypes._POINTERWHEEL = 0x08;
  1345. PointerEventTypes._POINTERPICK = 0x10;
  1346. PointerEventTypes._POINTERTAP = 0x20;
  1347. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1348. return PointerEventTypes;
  1349. }());
  1350. BABYLON.PointerEventTypes = PointerEventTypes;
  1351. var PointerInfoBase = /** @class */ (function () {
  1352. function PointerInfoBase(type, event) {
  1353. this.type = type;
  1354. this.event = event;
  1355. }
  1356. return PointerInfoBase;
  1357. }());
  1358. BABYLON.PointerInfoBase = PointerInfoBase;
  1359. /**
  1360. * This class is used to store pointer related info for the onPrePointerObservable event.
  1361. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1362. */
  1363. var PointerInfoPre = /** @class */ (function (_super) {
  1364. __extends(PointerInfoPre, _super);
  1365. function PointerInfoPre(type, event, localX, localY) {
  1366. var _this = _super.call(this, type, event) || this;
  1367. /**
  1368. * Ray from a pointer if availible (eg. 6dof controller)
  1369. */
  1370. _this.ray = null;
  1371. _this.skipOnPointerObservable = false;
  1372. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1373. return _this;
  1374. }
  1375. return PointerInfoPre;
  1376. }(PointerInfoBase));
  1377. BABYLON.PointerInfoPre = PointerInfoPre;
  1378. /**
  1379. * This type contains all the data related to a pointer event in Babylon.js.
  1380. * 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.
  1381. */
  1382. var PointerInfo = /** @class */ (function (_super) {
  1383. __extends(PointerInfo, _super);
  1384. function PointerInfo(type, event, pickInfo) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.pickInfo = pickInfo;
  1387. return _this;
  1388. }
  1389. return PointerInfo;
  1390. }(PointerInfoBase));
  1391. BABYLON.PointerInfo = PointerInfo;
  1392. })(BABYLON || (BABYLON = {}));
  1393. //# sourceMappingURL=babylon.pointerEvents.js.map
  1394. var BABYLON;
  1395. (function (BABYLON) {
  1396. /**
  1397. * Constant used to convert a value to gamma space
  1398. * @ignorenaming
  1399. */
  1400. BABYLON.ToGammaSpace = 1 / 2.2;
  1401. /**
  1402. * Constant used to convert a value to linear space
  1403. * @ignorenaming
  1404. */
  1405. BABYLON.ToLinearSpace = 2.2;
  1406. /**
  1407. * Constant used to define the minimal number value in Babylon.js
  1408. * @ignorenaming
  1409. */
  1410. BABYLON.Epsilon = 0.001;
  1411. /**
  1412. * Class used to hold a RBG color
  1413. */
  1414. var Color3 = /** @class */ (function () {
  1415. /**
  1416. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1417. * @param r defines the red component (between 0 and 1, default is 0)
  1418. * @param g defines the green component (between 0 and 1, default is 0)
  1419. * @param b defines the blue component (between 0 and 1, default is 0)
  1420. */
  1421. function Color3(
  1422. /**
  1423. * Defines the red component (between 0 and 1, default is 0)
  1424. */
  1425. r,
  1426. /**
  1427. * Defines the green component (between 0 and 1, default is 0)
  1428. */
  1429. g,
  1430. /**
  1431. * Defines the blue component (between 0 and 1, default is 0)
  1432. */
  1433. b) {
  1434. if (r === void 0) { r = 0; }
  1435. if (g === void 0) { g = 0; }
  1436. if (b === void 0) { b = 0; }
  1437. this.r = r;
  1438. this.g = g;
  1439. this.b = b;
  1440. }
  1441. /**
  1442. * Creates a string with the Color3 current values
  1443. * @returns the string representation of the Color3 object
  1444. */
  1445. Color3.prototype.toString = function () {
  1446. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1447. };
  1448. /**
  1449. * Returns the string "Color3"
  1450. * @returns "Color3"
  1451. */
  1452. Color3.prototype.getClassName = function () {
  1453. return "Color3";
  1454. };
  1455. /**
  1456. * Compute the Color3 hash code
  1457. * @returns an unique number that can be used to hash Color3 objects
  1458. */
  1459. Color3.prototype.getHashCode = function () {
  1460. var hash = this.r || 0;
  1461. hash = (hash * 397) ^ (this.g || 0);
  1462. hash = (hash * 397) ^ (this.b || 0);
  1463. return hash;
  1464. };
  1465. // Operators
  1466. /**
  1467. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1468. * @param array defines the array where to store the r,g,b components
  1469. * @param index defines an optional index in the target array to define where to start storing values
  1470. * @returns the current Color3 object
  1471. */
  1472. Color3.prototype.toArray = function (array, index) {
  1473. if (index === undefined) {
  1474. index = 0;
  1475. }
  1476. array[index] = this.r;
  1477. array[index + 1] = this.g;
  1478. array[index + 2] = this.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1483. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1484. * @returns a new {BABYLON.Color4} object
  1485. */
  1486. Color3.prototype.toColor4 = function (alpha) {
  1487. if (alpha === void 0) { alpha = 1; }
  1488. return new Color4(this.r, this.g, this.b, alpha);
  1489. };
  1490. /**
  1491. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1492. * @returns the new array
  1493. */
  1494. Color3.prototype.asArray = function () {
  1495. var result = new Array();
  1496. this.toArray(result, 0);
  1497. return result;
  1498. };
  1499. /**
  1500. * Returns the luminance value
  1501. * @returns a float value
  1502. */
  1503. Color3.prototype.toLuminance = function () {
  1504. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1505. };
  1506. /**
  1507. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1508. * @param otherColor defines the second operand
  1509. * @returns the new Color3 object
  1510. */
  1511. Color3.prototype.multiply = function (otherColor) {
  1512. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1513. };
  1514. /**
  1515. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1516. * @param otherColor defines the second operand
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the current Color3
  1519. */
  1520. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1521. result.r = this.r * otherColor.r;
  1522. result.g = this.g * otherColor.g;
  1523. result.b = this.b * otherColor.b;
  1524. return this;
  1525. };
  1526. /**
  1527. * Determines equality between Color3 objects
  1528. * @param otherColor defines the second operand
  1529. * @returns true if the rgb values are equal to the given ones
  1530. */
  1531. Color3.prototype.equals = function (otherColor) {
  1532. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1533. };
  1534. /**
  1535. * Determines equality between the current Color3 object and a set of r,b,g values
  1536. * @param r defines the red component to check
  1537. * @param g defines the green component to check
  1538. * @param b defines the blue component to check
  1539. * @returns true if the rgb values are equal to the given ones
  1540. */
  1541. Color3.prototype.equalsFloats = function (r, g, b) {
  1542. return this.r === r && this.g === g && this.b === b;
  1543. };
  1544. /**
  1545. * Multiplies in place each rgb value by scale
  1546. * @param scale defines the scaling factor
  1547. * @returns the updated Color3
  1548. */
  1549. Color3.prototype.scale = function (scale) {
  1550. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1551. };
  1552. /**
  1553. * Multiplies the rgb values by scale and stores the result into "result"
  1554. * @param scale defines the scaling factor
  1555. * @param result defines the Color3 object where to store the result
  1556. * @returns the unmodified current Color3
  1557. */
  1558. Color3.prototype.scaleToRef = function (scale, result) {
  1559. result.r = this.r * scale;
  1560. result.g = this.g * scale;
  1561. result.b = this.b * scale;
  1562. return this;
  1563. };
  1564. /**
  1565. * Scale the current Color3 values by a factor and add the result to a given Color3
  1566. * @param scale defines the scale factor
  1567. * @param result defines color to store the result into
  1568. * @returns the unmodified current Color3
  1569. */
  1570. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1571. result.r += this.r * scale;
  1572. result.g += this.g * scale;
  1573. result.b += this.b * scale;
  1574. return this;
  1575. };
  1576. /**
  1577. * Clamps the rgb values by the min and max values and stores the result into "result"
  1578. * @param min defines minimum clamping value (default is 0)
  1579. * @param max defines maximum clamping value (default is 1)
  1580. * @param result defines color to store the result into
  1581. * @returns the original Color3
  1582. */
  1583. Color3.prototype.clampToRef = function (min, max, result) {
  1584. if (min === void 0) { min = 0; }
  1585. if (max === void 0) { max = 1; }
  1586. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1587. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1588. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1589. return this;
  1590. };
  1591. /**
  1592. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1593. * @param otherColor defines the second operand
  1594. * @returns the new Color3
  1595. */
  1596. Color3.prototype.add = function (otherColor) {
  1597. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1598. };
  1599. /**
  1600. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1601. * @param otherColor defines the second operand
  1602. * @param result defines Color3 object to store the result into
  1603. * @returns the unmodified current Color3
  1604. */
  1605. Color3.prototype.addToRef = function (otherColor, result) {
  1606. result.r = this.r + otherColor.r;
  1607. result.g = this.g + otherColor.g;
  1608. result.b = this.b + otherColor.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1613. * @param otherColor defines the second operand
  1614. * @returns the new Color3
  1615. */
  1616. Color3.prototype.subtract = function (otherColor) {
  1617. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1618. };
  1619. /**
  1620. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1621. * @param otherColor defines the second operand
  1622. * @param result defines Color3 object to store the result into
  1623. * @returns the unmodified current Color3
  1624. */
  1625. Color3.prototype.subtractToRef = function (otherColor, result) {
  1626. result.r = this.r - otherColor.r;
  1627. result.g = this.g - otherColor.g;
  1628. result.b = this.b - otherColor.b;
  1629. return this;
  1630. };
  1631. /**
  1632. * Copy the current object
  1633. * @returns a new Color3 copied the current one
  1634. */
  1635. Color3.prototype.clone = function () {
  1636. return new Color3(this.r, this.g, this.b);
  1637. };
  1638. /**
  1639. * Copies the rgb values from the source in the current Color3
  1640. * @param source defines the source Color3 object
  1641. * @returns the updated Color3 object
  1642. */
  1643. Color3.prototype.copyFrom = function (source) {
  1644. this.r = source.r;
  1645. this.g = source.g;
  1646. this.b = source.b;
  1647. return this;
  1648. };
  1649. /**
  1650. * Updates the Color3 rgb values from the given floats
  1651. * @param r defines the red component to read from
  1652. * @param g defines the green component to read from
  1653. * @param b defines the blue component to read from
  1654. * @returns the current Color3 object
  1655. */
  1656. Color3.prototype.copyFromFloats = function (r, g, b) {
  1657. this.r = r;
  1658. this.g = g;
  1659. this.b = b;
  1660. return this;
  1661. };
  1662. /**
  1663. * Updates the Color3 rgb values from the given floats
  1664. * @param r defines the red component to read from
  1665. * @param g defines the green component to read from
  1666. * @param b defines the blue component to read from
  1667. * @returns the current Color3 object
  1668. */
  1669. Color3.prototype.set = function (r, g, b) {
  1670. return this.copyFromFloats(r, g, b);
  1671. };
  1672. /**
  1673. * Compute the Color3 hexadecimal code as a string
  1674. * @returns a string containing the hexadecimal representation of the Color3 object
  1675. */
  1676. Color3.prototype.toHexString = function () {
  1677. var intR = (this.r * 255) | 0;
  1678. var intG = (this.g * 255) | 0;
  1679. var intB = (this.b * 255) | 0;
  1680. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1681. };
  1682. /**
  1683. * Computes a new Color3 converted from the current one to linear space
  1684. * @returns a new Color3 object
  1685. */
  1686. Color3.prototype.toLinearSpace = function () {
  1687. var convertedColor = new Color3();
  1688. this.toLinearSpaceToRef(convertedColor);
  1689. return convertedColor;
  1690. };
  1691. /**
  1692. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1693. * @param convertedColor defines the Color3 object where to store the linear space version
  1694. * @returns the unmodified Color3
  1695. */
  1696. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1697. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1698. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1699. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1700. return this;
  1701. };
  1702. /**
  1703. * Computes a new Color3 converted from the current one to gamma space
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.prototype.toGammaSpace = function () {
  1707. var convertedColor = new Color3();
  1708. this.toGammaSpaceToRef(convertedColor);
  1709. return convertedColor;
  1710. };
  1711. /**
  1712. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1713. * @param convertedColor defines the Color3 object where to store the gamma space version
  1714. * @returns the unmodified Color3
  1715. */
  1716. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1717. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1718. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1719. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1720. return this;
  1721. };
  1722. // Statics
  1723. /**
  1724. * Creates a new Color3 from the string containing valid hexadecimal values
  1725. * @param hex defines a string containing valid hexadecimal values
  1726. * @returns a new Color3 object
  1727. */
  1728. Color3.FromHexString = function (hex) {
  1729. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1730. return new Color3(0, 0, 0);
  1731. }
  1732. var r = parseInt(hex.substring(1, 3), 16);
  1733. var g = parseInt(hex.substring(3, 5), 16);
  1734. var b = parseInt(hex.substring(5, 7), 16);
  1735. return Color3.FromInts(r, g, b);
  1736. };
  1737. /**
  1738. * Creates a new Vector3 from the starting index of the given array
  1739. * @param array defines the source array
  1740. * @param offset defines an offset in the source array
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromArray = function (array, offset) {
  1744. if (offset === void 0) { offset = 0; }
  1745. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1746. };
  1747. /**
  1748. * Creates a new Color3 from integer values (< 256)
  1749. * @param r defines the red component to read from (value between 0 and 255)
  1750. * @param g defines the green component to read from (value between 0 and 255)
  1751. * @param b defines the blue component to read from (value between 0 and 255)
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.FromInts = function (r, g, b) {
  1755. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1756. };
  1757. /**
  1758. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1759. * @param start defines the start Color3 value
  1760. * @param end defines the end Color3 value
  1761. * @param amount defines the gradient value between start and end
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Lerp = function (start, end, amount) {
  1765. var result = new Color3(0.0, 0.0, 0.0);
  1766. Color3.LerpToRef(start, end, amount, result);
  1767. return result;
  1768. };
  1769. /**
  1770. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1771. * @param left defines the start value
  1772. * @param right defines the end value
  1773. * @param amount defines the gradient factor
  1774. * @param result defines the Color3 object where to store the result
  1775. */
  1776. Color3.LerpToRef = function (left, right, amount, result) {
  1777. result.r = left.r + ((right.r - left.r) * amount);
  1778. result.g = left.g + ((right.g - left.g) * amount);
  1779. result.b = left.b + ((right.b - left.b) * amount);
  1780. };
  1781. /**
  1782. * Returns a Color3 value containing a red color
  1783. * @returns a new Color3 object
  1784. */
  1785. Color3.Red = function () { return new Color3(1, 0, 0); };
  1786. /**
  1787. * Returns a Color3 value containing a green color
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.Green = function () { return new Color3(0, 1, 0); };
  1791. /**
  1792. * Returns a Color3 value containing a blue color
  1793. * @returns a new Color3 object
  1794. */
  1795. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1796. /**
  1797. * Returns a Color3 value containing a black color
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Black = function () { return new Color3(0, 0, 0); };
  1801. /**
  1802. * Returns a Color3 value containing a white color
  1803. * @returns a new Color3 object
  1804. */
  1805. Color3.White = function () { return new Color3(1, 1, 1); };
  1806. /**
  1807. * Returns a Color3 value containing a purple color
  1808. * @returns a new Color3 object
  1809. */
  1810. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1811. /**
  1812. * Returns a Color3 value containing a magenta color
  1813. * @returns a new Color3 object
  1814. */
  1815. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1816. /**
  1817. * Returns a Color3 value containing a yellow color
  1818. * @returns a new Color3 object
  1819. */
  1820. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1821. /**
  1822. * Returns a Color3 value containing a gray color
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1826. /**
  1827. * Returns a Color3 value containing a teal color
  1828. * @returns a new Color3 object
  1829. */
  1830. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1831. /**
  1832. * Returns a Color3 value containing a random color
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1836. return Color3;
  1837. }());
  1838. BABYLON.Color3 = Color3;
  1839. /**
  1840. * Class used to hold a RBGA color
  1841. */
  1842. var Color4 = /** @class */ (function () {
  1843. /**
  1844. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1845. * @param r defines the red component (between 0 and 1, default is 0)
  1846. * @param g defines the green component (between 0 and 1, default is 0)
  1847. * @param b defines the blue component (between 0 and 1, default is 0)
  1848. * @param a defines the alpha component (between 0 and 1, default is 1)
  1849. */
  1850. function Color4(
  1851. /**
  1852. * Defines the red component (between 0 and 1, default is 0)
  1853. */
  1854. r,
  1855. /**
  1856. * Defines the green component (between 0 and 1, default is 0)
  1857. */
  1858. g,
  1859. /**
  1860. * Defines the blue component (between 0 and 1, default is 0)
  1861. */
  1862. b,
  1863. /**
  1864. * Defines the alpha component (between 0 and 1, default is 1)
  1865. */
  1866. a) {
  1867. if (r === void 0) { r = 0; }
  1868. if (g === void 0) { g = 0; }
  1869. if (b === void 0) { b = 0; }
  1870. if (a === void 0) { a = 1; }
  1871. this.r = r;
  1872. this.g = g;
  1873. this.b = b;
  1874. this.a = a;
  1875. }
  1876. // Operators
  1877. /**
  1878. * Adds in place the given Color4 values to the current Color4 object
  1879. * @param right defines the second operand
  1880. * @returns the current updated Color4 object
  1881. */
  1882. Color4.prototype.addInPlace = function (right) {
  1883. this.r += right.r;
  1884. this.g += right.g;
  1885. this.b += right.b;
  1886. this.a += right.a;
  1887. return this;
  1888. };
  1889. /**
  1890. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1891. * @returns the new array
  1892. */
  1893. Color4.prototype.asArray = function () {
  1894. var result = new Array();
  1895. this.toArray(result, 0);
  1896. return result;
  1897. };
  1898. /**
  1899. * Stores from the starting index in the given array the Color4 successive values
  1900. * @param array defines the array where to store the r,g,b components
  1901. * @param index defines an optional index in the target array to define where to start storing values
  1902. * @returns the current Color4 object
  1903. */
  1904. Color4.prototype.toArray = function (array, index) {
  1905. if (index === undefined) {
  1906. index = 0;
  1907. }
  1908. array[index] = this.r;
  1909. array[index + 1] = this.g;
  1910. array[index + 2] = this.b;
  1911. array[index + 3] = this.a;
  1912. return this;
  1913. };
  1914. /**
  1915. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1916. * @param right defines the second operand
  1917. * @returns a new Color4 object
  1918. */
  1919. Color4.prototype.add = function (right) {
  1920. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1921. };
  1922. /**
  1923. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1924. * @param right defines the second operand
  1925. * @returns a new Color4 object
  1926. */
  1927. Color4.prototype.subtract = function (right) {
  1928. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1929. };
  1930. /**
  1931. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1932. * @param right defines the second operand
  1933. * @param result defines the Color4 object where to store the result
  1934. * @returns the current Color4 object
  1935. */
  1936. Color4.prototype.subtractToRef = function (right, result) {
  1937. result.r = this.r - right.r;
  1938. result.g = this.g - right.g;
  1939. result.b = this.b - right.b;
  1940. result.a = this.a - right.a;
  1941. return this;
  1942. };
  1943. /**
  1944. * Creates a new Color4 with the current Color4 values multiplied by scale
  1945. * @param scale defines the scaling factor to apply
  1946. * @returns a new Color4 object
  1947. */
  1948. Color4.prototype.scale = function (scale) {
  1949. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1950. };
  1951. /**
  1952. * Multiplies the current Color4 values by scale and stores the result in "result"
  1953. * @param scale defines the scaling factor to apply
  1954. * @param result defines the Color4 object where to store the result
  1955. * @returns the current unmodified Color4
  1956. */
  1957. Color4.prototype.scaleToRef = function (scale, result) {
  1958. result.r = this.r * scale;
  1959. result.g = this.g * scale;
  1960. result.b = this.b * scale;
  1961. result.a = this.a * scale;
  1962. return this;
  1963. };
  1964. /**
  1965. * Scale the current Color4 values by a factor and add the result to a given Color4
  1966. * @param scale defines the scale factor
  1967. * @param result defines the Color4 object where to store the result
  1968. * @returns the unmodified current Color4
  1969. */
  1970. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1971. result.r += this.r * scale;
  1972. result.g += this.g * scale;
  1973. result.b += this.b * scale;
  1974. result.a += this.a * scale;
  1975. return this;
  1976. };
  1977. /**
  1978. * Clamps the rgb values by the min and max values and stores the result into "result"
  1979. * @param min defines minimum clamping value (default is 0)
  1980. * @param max defines maximum clamping value (default is 1)
  1981. * @param result defines color to store the result into.
  1982. * @returns the cuurent Color4
  1983. */
  1984. Color4.prototype.clampToRef = function (min, max, result) {
  1985. if (min === void 0) { min = 0; }
  1986. if (max === void 0) { max = 1; }
  1987. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1988. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1989. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1990. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1991. return this;
  1992. };
  1993. /**
  1994. * Multipy an Color4 value by another and return a new Color4 object
  1995. * @param color defines the Color4 value to multiply by
  1996. * @returns a new Color4 object
  1997. */
  1998. Color4.prototype.multiply = function (color) {
  1999. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2000. };
  2001. /**
  2002. * Multipy a Color4 value by another and push the result in a reference value
  2003. * @param color defines the Color4 value to multiply by
  2004. * @param result defines the Color4 to fill the result in
  2005. * @returns the result Color4
  2006. */
  2007. Color4.prototype.multiplyToRef = function (color, result) {
  2008. result.r = this.r * color.r;
  2009. result.g = this.g * color.g;
  2010. result.b = this.b * color.b;
  2011. result.a = this.a * color.a;
  2012. return result;
  2013. };
  2014. /**
  2015. * Creates a string with the Color4 current values
  2016. * @returns the string representation of the Color4 object
  2017. */
  2018. Color4.prototype.toString = function () {
  2019. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2020. };
  2021. /**
  2022. * Returns the string "Color4"
  2023. * @returns "Color4"
  2024. */
  2025. Color4.prototype.getClassName = function () {
  2026. return "Color4";
  2027. };
  2028. /**
  2029. * Compute the Color4 hash code
  2030. * @returns an unique number that can be used to hash Color4 objects
  2031. */
  2032. Color4.prototype.getHashCode = function () {
  2033. var hash = this.r || 0;
  2034. hash = (hash * 397) ^ (this.g || 0);
  2035. hash = (hash * 397) ^ (this.b || 0);
  2036. hash = (hash * 397) ^ (this.a || 0);
  2037. return hash;
  2038. };
  2039. /**
  2040. * Creates a new Color4 copied from the current one
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.clone = function () {
  2044. return new Color4(this.r, this.g, this.b, this.a);
  2045. };
  2046. /**
  2047. * Copies the given Color4 values into the current one
  2048. * @param source defines the source Color4 object
  2049. * @returns the current updated Color4 object
  2050. */
  2051. Color4.prototype.copyFrom = function (source) {
  2052. this.r = source.r;
  2053. this.g = source.g;
  2054. this.b = source.b;
  2055. this.a = source.a;
  2056. return this;
  2057. };
  2058. /**
  2059. * Copies the given float values into the current one
  2060. * @param r defines the red component to read from
  2061. * @param g defines the green component to read from
  2062. * @param b defines the blue component to read from
  2063. * @param a defines the alpha component to read from
  2064. * @returns the current updated Color4 object
  2065. */
  2066. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2067. this.r = r;
  2068. this.g = g;
  2069. this.b = b;
  2070. this.a = a;
  2071. return this;
  2072. };
  2073. /**
  2074. * Copies the given float values into the current one
  2075. * @param r defines the red component to read from
  2076. * @param g defines the green component to read from
  2077. * @param b defines the blue component to read from
  2078. * @param a defines the alpha component to read from
  2079. * @returns the current updated Color4 object
  2080. */
  2081. Color4.prototype.set = function (r, g, b, a) {
  2082. return this.copyFromFloats(r, g, b, a);
  2083. };
  2084. /**
  2085. * Compute the Color4 hexadecimal code as a string
  2086. * @returns a string containing the hexadecimal representation of the Color4 object
  2087. */
  2088. Color4.prototype.toHexString = function () {
  2089. var intR = (this.r * 255) | 0;
  2090. var intG = (this.g * 255) | 0;
  2091. var intB = (this.b * 255) | 0;
  2092. var intA = (this.a * 255) | 0;
  2093. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2094. };
  2095. /**
  2096. * Computes a new Color4 converted from the current one to linear space
  2097. * @returns a new Color4 object
  2098. */
  2099. Color4.prototype.toLinearSpace = function () {
  2100. var convertedColor = new Color4();
  2101. this.toLinearSpaceToRef(convertedColor);
  2102. return convertedColor;
  2103. };
  2104. /**
  2105. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2106. * @param convertedColor defines the Color4 object where to store the linear space version
  2107. * @returns the unmodified Color4
  2108. */
  2109. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2110. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2111. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2112. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2113. convertedColor.a = this.a;
  2114. return this;
  2115. };
  2116. /**
  2117. * Computes a new Color4 converted from the current one to gamma space
  2118. * @returns a new Color4 object
  2119. */
  2120. Color4.prototype.toGammaSpace = function () {
  2121. var convertedColor = new Color4();
  2122. this.toGammaSpaceToRef(convertedColor);
  2123. return convertedColor;
  2124. };
  2125. /**
  2126. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2127. * @param convertedColor defines the Color4 object where to store the gamma space version
  2128. * @returns the unmodified Color4
  2129. */
  2130. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2131. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2132. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2133. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2134. convertedColor.a = this.a;
  2135. return this;
  2136. };
  2137. // Statics
  2138. /**
  2139. * Creates a new Color4 from the string containing valid hexadecimal values
  2140. * @param hex defines a string containing valid hexadecimal values
  2141. * @returns a new Color4 object
  2142. */
  2143. Color4.FromHexString = function (hex) {
  2144. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2145. return new Color4(0.0, 0.0, 0.0, 0.0);
  2146. }
  2147. var r = parseInt(hex.substring(1, 3), 16);
  2148. var g = parseInt(hex.substring(3, 5), 16);
  2149. var b = parseInt(hex.substring(5, 7), 16);
  2150. var a = parseInt(hex.substring(7, 9), 16);
  2151. return Color4.FromInts(r, g, b, a);
  2152. };
  2153. /**
  2154. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2155. * @param left defines the start value
  2156. * @param right defines the end value
  2157. * @param amount defines the gradient factor
  2158. * @returns a new Color4 object
  2159. */
  2160. Color4.Lerp = function (left, right, amount) {
  2161. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2162. Color4.LerpToRef(left, right, amount, result);
  2163. return result;
  2164. };
  2165. /**
  2166. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2167. * @param left defines the start value
  2168. * @param right defines the end value
  2169. * @param amount defines the gradient factor
  2170. * @param result defines the Color4 object where to store data
  2171. */
  2172. Color4.LerpToRef = function (left, right, amount, result) {
  2173. result.r = left.r + (right.r - left.r) * amount;
  2174. result.g = left.g + (right.g - left.g) * amount;
  2175. result.b = left.b + (right.b - left.b) * amount;
  2176. result.a = left.a + (right.a - left.a) * amount;
  2177. };
  2178. /**
  2179. * Creates a new Color4 from a Color3 and an alpha value
  2180. * @param color3 defines the source Color3 to read from
  2181. * @param alpha defines the alpha component (1.0 by default)
  2182. * @returns a new Color4 object
  2183. */
  2184. Color4.FromColor3 = function (color3, alpha) {
  2185. if (alpha === void 0) { alpha = 1.0; }
  2186. return new Color4(color3.r, color3.g, color3.b, alpha);
  2187. };
  2188. /**
  2189. * Creates a new Color4 from the starting index element of the given array
  2190. * @param array defines the source array to read from
  2191. * @param offset defines the offset in the source array
  2192. * @returns a new Color4 object
  2193. */
  2194. Color4.FromArray = function (array, offset) {
  2195. if (offset === void 0) { offset = 0; }
  2196. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2197. };
  2198. /**
  2199. * Creates a new Color3 from integer values (< 256)
  2200. * @param r defines the red component to read from (value between 0 and 255)
  2201. * @param g defines the green component to read from (value between 0 and 255)
  2202. * @param b defines the blue component to read from (value between 0 and 255)
  2203. * @param a defines the alpha component to read from (value between 0 and 255)
  2204. * @returns a new Color3 object
  2205. */
  2206. Color4.FromInts = function (r, g, b, a) {
  2207. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2208. };
  2209. /**
  2210. * Check the content of a given array and convert it to an array containing RGBA data
  2211. * If the original array was already containing count * 4 values then it is returned directly
  2212. * @param colors defines the array to check
  2213. * @param count defines the number of RGBA data to expect
  2214. * @returns an array containing count * 4 values (RGBA)
  2215. */
  2216. Color4.CheckColors4 = function (colors, count) {
  2217. // Check if color3 was used
  2218. if (colors.length === count * 3) {
  2219. var colors4 = [];
  2220. for (var index = 0; index < colors.length; index += 3) {
  2221. var newIndex = (index / 3) * 4;
  2222. colors4[newIndex] = colors[index];
  2223. colors4[newIndex + 1] = colors[index + 1];
  2224. colors4[newIndex + 2] = colors[index + 2];
  2225. colors4[newIndex + 3] = 1.0;
  2226. }
  2227. return colors4;
  2228. }
  2229. return colors;
  2230. };
  2231. return Color4;
  2232. }());
  2233. BABYLON.Color4 = Color4;
  2234. /**
  2235. * Class representing a vector containing 2 coordinates
  2236. */
  2237. var Vector2 = /** @class */ (function () {
  2238. /**
  2239. * Creates a new Vector2 from the given x and y coordinates
  2240. * @param x defines the first coordinate
  2241. * @param y defines the second coordinate
  2242. */
  2243. function Vector2(
  2244. /** defines the first coordinate */
  2245. x,
  2246. /** defines the second coordinate */
  2247. y) {
  2248. if (x === void 0) { x = 0; }
  2249. if (y === void 0) { y = 0; }
  2250. this.x = x;
  2251. this.y = y;
  2252. }
  2253. /**
  2254. * Gets a string with the Vector2 coordinates
  2255. * @returns a string with the Vector2 coordinates
  2256. */
  2257. Vector2.prototype.toString = function () {
  2258. return "{X: " + this.x + " Y:" + this.y + "}";
  2259. };
  2260. /**
  2261. * Gets class name
  2262. * @returns the string "Vector2"
  2263. */
  2264. Vector2.prototype.getClassName = function () {
  2265. return "Vector2";
  2266. };
  2267. /**
  2268. * Gets current vector hash code
  2269. * @returns the Vector2 hash code as a number
  2270. */
  2271. Vector2.prototype.getHashCode = function () {
  2272. var hash = this.x || 0;
  2273. hash = (hash * 397) ^ (this.y || 0);
  2274. return hash;
  2275. };
  2276. // Operators
  2277. /**
  2278. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2279. * @param array defines the source array
  2280. * @param index defines the offset in source array
  2281. * @returns the current Vector2
  2282. */
  2283. Vector2.prototype.toArray = function (array, index) {
  2284. if (index === void 0) { index = 0; }
  2285. array[index] = this.x;
  2286. array[index + 1] = this.y;
  2287. return this;
  2288. };
  2289. /**
  2290. * Copy the current vector to an array
  2291. * @returns a new array with 2 elements: the Vector2 coordinates.
  2292. */
  2293. Vector2.prototype.asArray = function () {
  2294. var result = new Array();
  2295. this.toArray(result, 0);
  2296. return result;
  2297. };
  2298. /**
  2299. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2300. * @param source defines the source Vector2
  2301. * @returns the current updated Vector2
  2302. */
  2303. Vector2.prototype.copyFrom = function (source) {
  2304. this.x = source.x;
  2305. this.y = source.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Sets the Vector2 coordinates with the given floats
  2310. * @param x defines the first coordinate
  2311. * @param y defines the second coordinate
  2312. * @returns the current updated Vector2
  2313. */
  2314. Vector2.prototype.copyFromFloats = function (x, y) {
  2315. this.x = x;
  2316. this.y = y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Sets the Vector2 coordinates with the given floats
  2321. * @param x defines the first coordinate
  2322. * @param y defines the second coordinate
  2323. * @returns the current updated Vector2
  2324. */
  2325. Vector2.prototype.set = function (x, y) {
  2326. return this.copyFromFloats(x, y);
  2327. };
  2328. /**
  2329. * Add another vector with the current one
  2330. * @param otherVector defines the other vector
  2331. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2332. */
  2333. Vector2.prototype.add = function (otherVector) {
  2334. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2335. };
  2336. /**
  2337. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2338. * @param otherVector defines the other vector
  2339. * @param result defines the target vector
  2340. * @returns the unmodified current Vector2
  2341. */
  2342. Vector2.prototype.addToRef = function (otherVector, result) {
  2343. result.x = this.x + otherVector.x;
  2344. result.y = this.y + otherVector.y;
  2345. return this;
  2346. };
  2347. /**
  2348. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2349. * @param otherVector defines the other vector
  2350. * @returns the current updated Vector2
  2351. */
  2352. Vector2.prototype.addInPlace = function (otherVector) {
  2353. this.x += otherVector.x;
  2354. this.y += otherVector.y;
  2355. return this;
  2356. };
  2357. /**
  2358. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2359. * @param otherVector defines the other vector
  2360. * @returns a new Vector2
  2361. */
  2362. Vector2.prototype.addVector3 = function (otherVector) {
  2363. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2364. };
  2365. /**
  2366. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2367. * @param otherVector defines the other vector
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.subtract = function (otherVector) {
  2371. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2372. };
  2373. /**
  2374. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2375. * @param otherVector defines the other vector
  2376. * @param result defines the target vector
  2377. * @returns the unmodified current Vector2
  2378. */
  2379. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2380. result.x = this.x - otherVector.x;
  2381. result.y = this.y - otherVector.y;
  2382. return this;
  2383. };
  2384. /**
  2385. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2386. * @param otherVector defines the other vector
  2387. * @returns the current updated Vector2
  2388. */
  2389. Vector2.prototype.subtractInPlace = function (otherVector) {
  2390. this.x -= otherVector.x;
  2391. this.y -= otherVector.y;
  2392. return this;
  2393. };
  2394. /**
  2395. * Multiplies in place the current Vector2 coordinates by the given ones
  2396. * @param otherVector defines the other vector
  2397. * @returns the current updated Vector2
  2398. */
  2399. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2400. this.x *= otherVector.x;
  2401. this.y *= otherVector.y;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2406. * @param otherVector defines the other vector
  2407. * @returns a new Vector2
  2408. */
  2409. Vector2.prototype.multiply = function (otherVector) {
  2410. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2411. };
  2412. /**
  2413. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2414. * @param otherVector defines the other vector
  2415. * @param result defines the target vector
  2416. * @returns the unmodified current Vector2
  2417. */
  2418. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2419. result.x = this.x * otherVector.x;
  2420. result.y = this.y * otherVector.y;
  2421. return this;
  2422. };
  2423. /**
  2424. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2425. * @param x defines the first coordinate
  2426. * @param y defines the second coordinate
  2427. * @returns a new Vector2
  2428. */
  2429. Vector2.prototype.multiplyByFloats = function (x, y) {
  2430. return new Vector2(this.x * x, this.y * y);
  2431. };
  2432. /**
  2433. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2434. * @param otherVector defines the other vector
  2435. * @returns a new Vector2
  2436. */
  2437. Vector2.prototype.divide = function (otherVector) {
  2438. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2439. };
  2440. /**
  2441. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @param result defines the target vector
  2444. * @returns the unmodified current Vector2
  2445. */
  2446. Vector2.prototype.divideToRef = function (otherVector, result) {
  2447. result.x = this.x / otherVector.x;
  2448. result.y = this.y / otherVector.y;
  2449. return this;
  2450. };
  2451. /**
  2452. * Divides the current Vector2 coordinates by the given ones
  2453. * @param otherVector defines the other vector
  2454. * @returns the current updated Vector2
  2455. */
  2456. Vector2.prototype.divideInPlace = function (otherVector) {
  2457. return this.divideToRef(otherVector, this);
  2458. };
  2459. /**
  2460. * Gets a new Vector2 with current Vector2 negated coordinates
  2461. * @returns a new Vector2
  2462. */
  2463. Vector2.prototype.negate = function () {
  2464. return new Vector2(-this.x, -this.y);
  2465. };
  2466. /**
  2467. * Multiply the Vector2 coordinates by scale
  2468. * @param scale defines the scaling factor
  2469. * @returns the current updated Vector2
  2470. */
  2471. Vector2.prototype.scaleInPlace = function (scale) {
  2472. this.x *= scale;
  2473. this.y *= scale;
  2474. return this;
  2475. };
  2476. /**
  2477. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2478. * @param scale defines the scaling factor
  2479. * @returns a new Vector2
  2480. */
  2481. Vector2.prototype.scale = function (scale) {
  2482. var result = new Vector2(0, 0);
  2483. this.scaleToRef(scale, result);
  2484. return result;
  2485. };
  2486. /**
  2487. * Scale the current Vector2 values by a factor to a given Vector2
  2488. * @param scale defines the scale factor
  2489. * @param result defines the Vector2 object where to store the result
  2490. * @returns the unmodified current Vector2
  2491. */
  2492. Vector2.prototype.scaleToRef = function (scale, result) {
  2493. result.x = this.x * scale;
  2494. result.y = this.y * scale;
  2495. return this;
  2496. };
  2497. /**
  2498. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2499. * @param scale defines the scale factor
  2500. * @param result defines the Vector2 object where to store the result
  2501. * @returns the unmodified current Vector2
  2502. */
  2503. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2504. result.x += this.x * scale;
  2505. result.y += this.y * scale;
  2506. return this;
  2507. };
  2508. /**
  2509. * Gets a boolean if two vectors are equals
  2510. * @param otherVector defines the other vector
  2511. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2512. */
  2513. Vector2.prototype.equals = function (otherVector) {
  2514. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2515. };
  2516. /**
  2517. * Gets a boolean if two vectors are equals (using an epsilon value)
  2518. * @param otherVector defines the other vector
  2519. * @param epsilon defines the minimal distance to consider equality
  2520. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2521. */
  2522. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2523. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2524. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2525. };
  2526. /**
  2527. * Gets a new Vector2 from current Vector2 floored values
  2528. * @returns a new Vector2
  2529. */
  2530. Vector2.prototype.floor = function () {
  2531. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2532. };
  2533. /**
  2534. * Gets a new Vector2 from current Vector2 floored values
  2535. * @returns a new Vector2
  2536. */
  2537. Vector2.prototype.fract = function () {
  2538. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2539. };
  2540. // Properties
  2541. /**
  2542. * Gets the length of the vector
  2543. * @returns the vector length (float)
  2544. */
  2545. Vector2.prototype.length = function () {
  2546. return Math.sqrt(this.x * this.x + this.y * this.y);
  2547. };
  2548. /**
  2549. * Gets the vector squared length
  2550. * @returns the vector squared length (float)
  2551. */
  2552. Vector2.prototype.lengthSquared = function () {
  2553. return (this.x * this.x + this.y * this.y);
  2554. };
  2555. // Methods
  2556. /**
  2557. * Normalize the vector
  2558. * @returns the current updated Vector2
  2559. */
  2560. Vector2.prototype.normalize = function () {
  2561. var len = this.length();
  2562. if (len === 0)
  2563. return this;
  2564. var num = 1.0 / len;
  2565. this.x *= num;
  2566. this.y *= num;
  2567. return this;
  2568. };
  2569. /**
  2570. * Gets a new Vector2 copied from the Vector2
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.clone = function () {
  2574. return new Vector2(this.x, this.y);
  2575. };
  2576. // Statics
  2577. /**
  2578. * Gets a new Vector2(0, 0)
  2579. * @returns a new Vector2
  2580. */
  2581. Vector2.Zero = function () {
  2582. return new Vector2(0, 0);
  2583. };
  2584. /**
  2585. * Gets a new Vector2(1, 1)
  2586. * @returns a new Vector2
  2587. */
  2588. Vector2.One = function () {
  2589. return new Vector2(1, 1);
  2590. };
  2591. /**
  2592. * Gets a new Vector2 set from the given index element of the given array
  2593. * @param array defines the data source
  2594. * @param offset defines the offset in the data source
  2595. * @returns a new Vector2
  2596. */
  2597. Vector2.FromArray = function (array, offset) {
  2598. if (offset === void 0) { offset = 0; }
  2599. return new Vector2(array[offset], array[offset + 1]);
  2600. };
  2601. /**
  2602. * Sets "result" from the given index element of the given array
  2603. * @param array defines the data source
  2604. * @param offset defines the offset in the data source
  2605. * @param result defines the target vector
  2606. */
  2607. Vector2.FromArrayToRef = function (array, offset, result) {
  2608. result.x = array[offset];
  2609. result.y = array[offset + 1];
  2610. };
  2611. /**
  2612. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2613. * @param value1 defines 1st point of control
  2614. * @param value2 defines 2nd point of control
  2615. * @param value3 defines 3rd point of control
  2616. * @param value4 defines 4th point of control
  2617. * @param amount defines the interpolation factor
  2618. * @returns a new Vector2
  2619. */
  2620. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2621. var squared = amount * amount;
  2622. var cubed = amount * squared;
  2623. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2624. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2625. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2626. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2627. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2628. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2629. return new Vector2(x, y);
  2630. };
  2631. /**
  2632. * 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".
  2633. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2634. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2635. * @param value defines the value to clamp
  2636. * @param min defines the lower limit
  2637. * @param max defines the upper limit
  2638. * @returns a new Vector2
  2639. */
  2640. Vector2.Clamp = function (value, min, max) {
  2641. var x = value.x;
  2642. x = (x > max.x) ? max.x : x;
  2643. x = (x < min.x) ? min.x : x;
  2644. var y = value.y;
  2645. y = (y > max.y) ? max.y : y;
  2646. y = (y < min.y) ? min.y : y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2651. * @param value1 defines the 1st control point
  2652. * @param tangent1 defines the outgoing tangent
  2653. * @param value2 defines the 2nd control point
  2654. * @param tangent2 defines the incoming tangent
  2655. * @param amount defines the interpolation factor
  2656. * @returns a new Vector2
  2657. */
  2658. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2659. var squared = amount * amount;
  2660. var cubed = amount * squared;
  2661. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2662. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2663. var part3 = (cubed - (2.0 * squared)) + amount;
  2664. var part4 = cubed - squared;
  2665. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2666. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2667. return new Vector2(x, y);
  2668. };
  2669. /**
  2670. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2671. * @param start defines the start vector
  2672. * @param end defines the end vector
  2673. * @param amount defines the interpolation factor
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Lerp = function (start, end, amount) {
  2677. var x = start.x + ((end.x - start.x) * amount);
  2678. var y = start.y + ((end.y - start.y) * amount);
  2679. return new Vector2(x, y);
  2680. };
  2681. /**
  2682. * Gets the dot product of the vector "left" and the vector "right"
  2683. * @param left defines first vector
  2684. * @param right defines second vector
  2685. * @returns the dot product (float)
  2686. */
  2687. Vector2.Dot = function (left, right) {
  2688. return left.x * right.x + left.y * right.y;
  2689. };
  2690. /**
  2691. * Returns a new Vector2 equal to the normalized given vector
  2692. * @param vector defines the vector to normalize
  2693. * @returns a new Vector2
  2694. */
  2695. Vector2.Normalize = function (vector) {
  2696. var newVector = vector.clone();
  2697. newVector.normalize();
  2698. return newVector;
  2699. };
  2700. /**
  2701. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2702. * @param left defines 1st vector
  2703. * @param right defines 2nd vector
  2704. * @returns a new Vector2
  2705. */
  2706. Vector2.Minimize = function (left, right) {
  2707. var x = (left.x < right.x) ? left.x : right.x;
  2708. var y = (left.y < right.y) ? left.y : right.y;
  2709. return new Vector2(x, y);
  2710. };
  2711. /**
  2712. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2713. * @param left defines 1st vector
  2714. * @param right defines 2nd vector
  2715. * @returns a new Vector2
  2716. */
  2717. Vector2.Maximize = function (left, right) {
  2718. var x = (left.x > right.x) ? left.x : right.x;
  2719. var y = (left.y > right.y) ? left.y : right.y;
  2720. return new Vector2(x, y);
  2721. };
  2722. /**
  2723. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2724. * @param vector defines the vector to transform
  2725. * @param transformation defines the matrix to apply
  2726. * @returns a new Vector2
  2727. */
  2728. Vector2.Transform = function (vector, transformation) {
  2729. var r = Vector2.Zero();
  2730. Vector2.TransformToRef(vector, transformation, r);
  2731. return r;
  2732. };
  2733. /**
  2734. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2735. * @param vector defines the vector to transform
  2736. * @param transformation defines the matrix to apply
  2737. * @param result defines the target vector
  2738. */
  2739. Vector2.TransformToRef = function (vector, transformation, result) {
  2740. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2741. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2742. result.x = x;
  2743. result.y = y;
  2744. };
  2745. /**
  2746. * Determines if a given vector is included in a triangle
  2747. * @param p defines the vector to test
  2748. * @param p0 defines 1st triangle point
  2749. * @param p1 defines 2nd triangle point
  2750. * @param p2 defines 3rd triangle point
  2751. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2752. */
  2753. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2754. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2755. var sign = a < 0 ? -1 : 1;
  2756. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2757. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2758. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2759. };
  2760. /**
  2761. * Gets the distance between the vectors "value1" and "value2"
  2762. * @param value1 defines first vector
  2763. * @param value2 defines second vector
  2764. * @returns the distance between vectors
  2765. */
  2766. Vector2.Distance = function (value1, value2) {
  2767. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2768. };
  2769. /**
  2770. * Returns the squared distance between the vectors "value1" and "value2"
  2771. * @param value1 defines first vector
  2772. * @param value2 defines second vector
  2773. * @returns the squared distance between vectors
  2774. */
  2775. Vector2.DistanceSquared = function (value1, value2) {
  2776. var x = value1.x - value2.x;
  2777. var y = value1.y - value2.y;
  2778. return (x * x) + (y * y);
  2779. };
  2780. /**
  2781. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2782. * @param value1 defines first vector
  2783. * @param value2 defines second vector
  2784. * @returns a new Vector2
  2785. */
  2786. Vector2.Center = function (value1, value2) {
  2787. var center = value1.add(value2);
  2788. center.scaleInPlace(0.5);
  2789. return center;
  2790. };
  2791. /**
  2792. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2793. * @param p defines the middle point
  2794. * @param segA defines one point of the segment
  2795. * @param segB defines the other point of the segment
  2796. * @returns the shortest distance
  2797. */
  2798. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2799. var l2 = Vector2.DistanceSquared(segA, segB);
  2800. if (l2 === 0.0) {
  2801. return Vector2.Distance(p, segA);
  2802. }
  2803. var v = segB.subtract(segA);
  2804. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2805. var proj = segA.add(v.multiplyByFloats(t, t));
  2806. return Vector2.Distance(p, proj);
  2807. };
  2808. return Vector2;
  2809. }());
  2810. BABYLON.Vector2 = Vector2;
  2811. /**
  2812. * Classed used to store (x,y,z) vector representation
  2813. * A Vector3 is the main object used in 3D geometry
  2814. * It can represent etiher the coordinates of a point the space, either a direction
  2815. * Reminder: Babylon.js uses a left handed forward facing system
  2816. */
  2817. var Vector3 = /** @class */ (function () {
  2818. /**
  2819. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2820. * @param x defines the first coordinates (on X axis)
  2821. * @param y defines the second coordinates (on Y axis)
  2822. * @param z defines the third coordinates (on Z axis)
  2823. */
  2824. function Vector3(
  2825. /**
  2826. * Defines the first coordinates (on X axis)
  2827. */
  2828. x,
  2829. /**
  2830. * Defines the second coordinates (on Y axis)
  2831. */
  2832. y,
  2833. /**
  2834. * Defines the third coordinates (on Z axis)
  2835. */
  2836. z) {
  2837. if (x === void 0) { x = 0; }
  2838. if (y === void 0) { y = 0; }
  2839. if (z === void 0) { z = 0; }
  2840. this.x = x;
  2841. this.y = y;
  2842. this.z = z;
  2843. }
  2844. /**
  2845. * Creates a string representation of the Vector3
  2846. * @returns a string with the Vector3 coordinates.
  2847. */
  2848. Vector3.prototype.toString = function () {
  2849. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2850. };
  2851. /**
  2852. * Gets the class name
  2853. * @returns the string "Vector3"
  2854. */
  2855. Vector3.prototype.getClassName = function () {
  2856. return "Vector3";
  2857. };
  2858. /**
  2859. * Creates the Vector3 hash code
  2860. * @returns a number which tends to be unique between Vector3 instances
  2861. */
  2862. Vector3.prototype.getHashCode = function () {
  2863. var hash = this.x || 0;
  2864. hash = (hash * 397) ^ (this.y || 0);
  2865. hash = (hash * 397) ^ (this.z || 0);
  2866. return hash;
  2867. };
  2868. // Operators
  2869. /**
  2870. * Creates an array containing three elements : the coordinates of the Vector3
  2871. * @returns a new array of numbers
  2872. */
  2873. Vector3.prototype.asArray = function () {
  2874. var result = [];
  2875. this.toArray(result, 0);
  2876. return result;
  2877. };
  2878. /**
  2879. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2880. * @param array defines the destination array
  2881. * @param index defines the offset in the destination array
  2882. * @returns the current Vector3
  2883. */
  2884. Vector3.prototype.toArray = function (array, index) {
  2885. if (index === void 0) { index = 0; }
  2886. array[index] = this.x;
  2887. array[index + 1] = this.y;
  2888. array[index + 2] = this.z;
  2889. return this;
  2890. };
  2891. /**
  2892. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2893. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2894. */
  2895. Vector3.prototype.toQuaternion = function () {
  2896. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2897. };
  2898. /**
  2899. * Adds the given vector to the current Vector3
  2900. * @param otherVector defines the second operand
  2901. * @returns the current updated Vector3
  2902. */
  2903. Vector3.prototype.addInPlace = function (otherVector) {
  2904. this.x += otherVector.x;
  2905. this.y += otherVector.y;
  2906. this.z += otherVector.z;
  2907. return this;
  2908. };
  2909. /**
  2910. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2911. * @param otherVector defines the second operand
  2912. * @returns the resulting Vector3
  2913. */
  2914. Vector3.prototype.add = function (otherVector) {
  2915. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2916. };
  2917. /**
  2918. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2919. * @param otherVector defines the second operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.addToRef = function (otherVector, result) {
  2924. result.x = this.x + otherVector.x;
  2925. result.y = this.y + otherVector.y;
  2926. result.z = this.z + otherVector.z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Subtract the given vector from the current Vector3
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.subtractInPlace = function (otherVector) {
  2935. this.x -= otherVector.x;
  2936. this.y -= otherVector.y;
  2937. this.z -= otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2942. * @param otherVector defines the second operand
  2943. * @returns the resulting Vector3
  2944. */
  2945. Vector3.prototype.subtract = function (otherVector) {
  2946. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2947. };
  2948. /**
  2949. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2950. * @param otherVector defines the second operand
  2951. * @param result defines the Vector3 object where to store the result
  2952. * @returns the current Vector3
  2953. */
  2954. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2955. result.x = this.x - otherVector.x;
  2956. result.y = this.y - otherVector.y;
  2957. result.z = this.z - otherVector.z;
  2958. return this;
  2959. };
  2960. /**
  2961. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2962. * @param x defines the x coordinate of the operand
  2963. * @param y defines the y coordinate of the operand
  2964. * @param z defines the z coordinate of the operand
  2965. * @returns the resulting Vector3
  2966. */
  2967. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2968. return new Vector3(this.x - x, this.y - y, this.z - z);
  2969. };
  2970. /**
  2971. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @param result defines the Vector3 object where to store the result
  2976. * @returns the current Vector3
  2977. */
  2978. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2979. result.x = this.x - x;
  2980. result.y = this.y - y;
  2981. result.z = this.z - z;
  2982. return this;
  2983. };
  2984. /**
  2985. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2986. * @returns a new Vector3
  2987. */
  2988. Vector3.prototype.negate = function () {
  2989. return new Vector3(-this.x, -this.y, -this.z);
  2990. };
  2991. /**
  2992. * Multiplies the Vector3 coordinates by the float "scale"
  2993. * @param scale defines the multiplier factor
  2994. * @returns the current updated Vector3
  2995. */
  2996. Vector3.prototype.scaleInPlace = function (scale) {
  2997. this.x *= scale;
  2998. this.y *= scale;
  2999. this.z *= scale;
  3000. return this;
  3001. };
  3002. /**
  3003. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3004. * @param scale defines the multiplier factor
  3005. * @returns a new Vector3
  3006. */
  3007. Vector3.prototype.scale = function (scale) {
  3008. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3009. };
  3010. /**
  3011. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3012. * @param scale defines the multiplier factor
  3013. * @param result defines the Vector3 object where to store the result
  3014. * @returns the current Vector3
  3015. */
  3016. Vector3.prototype.scaleToRef = function (scale, result) {
  3017. result.x = this.x * scale;
  3018. result.y = this.y * scale;
  3019. result.z = this.z * scale;
  3020. return this;
  3021. };
  3022. /**
  3023. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3024. * @param scale defines the scale factor
  3025. * @param result defines the Vector3 object where to store the result
  3026. * @returns the unmodified current Vector3
  3027. */
  3028. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3029. result.x += this.x * scale;
  3030. result.y += this.y * scale;
  3031. result.z += this.z * scale;
  3032. return this;
  3033. };
  3034. /**
  3035. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3036. * @param otherVector defines the second operand
  3037. * @returns true if both vectors are equals
  3038. */
  3039. Vector3.prototype.equals = function (otherVector) {
  3040. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3041. };
  3042. /**
  3043. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3044. * @param otherVector defines the second operand
  3045. * @param epsilon defines the minimal distance to define values as equals
  3046. * @returns true if both vectors are distant less than epsilon
  3047. */
  3048. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3049. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3050. 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);
  3051. };
  3052. /**
  3053. * Returns true if the current Vector3 coordinates equals the given floats
  3054. * @param x defines the x coordinate of the operand
  3055. * @param y defines the y coordinate of the operand
  3056. * @param z defines the z coordinate of the operand
  3057. * @returns true if both vectors are equals
  3058. */
  3059. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3060. return this.x === x && this.y === y && this.z === z;
  3061. };
  3062. /**
  3063. * Multiplies the current Vector3 coordinates by the given ones
  3064. * @param otherVector defines the second operand
  3065. * @returns the current updated Vector3
  3066. */
  3067. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3068. this.x *= otherVector.x;
  3069. this.y *= otherVector.y;
  3070. this.z *= otherVector.z;
  3071. return this;
  3072. };
  3073. /**
  3074. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3075. * @param otherVector defines the second operand
  3076. * @returns the new Vector3
  3077. */
  3078. Vector3.prototype.multiply = function (otherVector) {
  3079. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3080. };
  3081. /**
  3082. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3083. * @param otherVector defines the second operand
  3084. * @param result defines the Vector3 object where to store the result
  3085. * @returns the current Vector3
  3086. */
  3087. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3088. result.x = this.x * otherVector.x;
  3089. result.y = this.y * otherVector.y;
  3090. result.z = this.z * otherVector.z;
  3091. return this;
  3092. };
  3093. /**
  3094. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3095. * @param x defines the x coordinate of the operand
  3096. * @param y defines the y coordinate of the operand
  3097. * @param z defines the z coordinate of the operand
  3098. * @returns the new Vector3
  3099. */
  3100. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3101. return new Vector3(this.x * x, this.y * y, this.z * z);
  3102. };
  3103. /**
  3104. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3105. * @param otherVector defines the second operand
  3106. * @returns the new Vector3
  3107. */
  3108. Vector3.prototype.divide = function (otherVector) {
  3109. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3110. };
  3111. /**
  3112. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3113. * @param otherVector defines the second operand
  3114. * @param result defines the Vector3 object where to store the result
  3115. * @returns the current Vector3
  3116. */
  3117. Vector3.prototype.divideToRef = function (otherVector, result) {
  3118. result.x = this.x / otherVector.x;
  3119. result.y = this.y / otherVector.y;
  3120. result.z = this.z / otherVector.z;
  3121. return this;
  3122. };
  3123. /**
  3124. * Divides the current Vector3 coordinates by the given ones.
  3125. * @param otherVector defines the second operand
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.divideInPlace = function (otherVector) {
  3129. return this.divideToRef(otherVector, this);
  3130. };
  3131. /**
  3132. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3133. * @param other defines the second operand
  3134. * @returns the current updated Vector3
  3135. */
  3136. Vector3.prototype.minimizeInPlace = function (other) {
  3137. if (other.x < this.x)
  3138. this.x = other.x;
  3139. if (other.y < this.y)
  3140. this.y = other.y;
  3141. if (other.z < this.z)
  3142. this.z = other.z;
  3143. return this;
  3144. };
  3145. /**
  3146. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3147. * @param other defines the second operand
  3148. * @returns the current updated Vector3
  3149. */
  3150. Vector3.prototype.maximizeInPlace = function (other) {
  3151. if (other.x > this.x)
  3152. this.x = other.x;
  3153. if (other.y > this.y)
  3154. this.y = other.y;
  3155. if (other.z > this.z)
  3156. this.z = other.z;
  3157. return this;
  3158. };
  3159. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3160. /**
  3161. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3162. */
  3163. get: function () {
  3164. var absX = Math.abs(this.x);
  3165. var absY = Math.abs(this.y);
  3166. if (absX !== absY) {
  3167. return true;
  3168. }
  3169. var absZ = Math.abs(this.z);
  3170. if (absX !== absZ) {
  3171. return true;
  3172. }
  3173. if (absY !== absZ) {
  3174. return true;
  3175. }
  3176. return false;
  3177. },
  3178. enumerable: true,
  3179. configurable: true
  3180. });
  3181. /**
  3182. * Gets a new Vector3 from current Vector3 floored values
  3183. * @returns a new Vector3
  3184. */
  3185. Vector3.prototype.floor = function () {
  3186. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3187. };
  3188. /**
  3189. * Gets a new Vector3 from current Vector3 floored values
  3190. * @returns a new Vector3
  3191. */
  3192. Vector3.prototype.fract = function () {
  3193. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3194. };
  3195. // Properties
  3196. /**
  3197. * Gets the length of the Vector3
  3198. * @returns the length of the Vecto3
  3199. */
  3200. Vector3.prototype.length = function () {
  3201. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3202. };
  3203. /**
  3204. * Gets the squared length of the Vector3
  3205. * @returns squared length of the Vector3
  3206. */
  3207. Vector3.prototype.lengthSquared = function () {
  3208. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3209. };
  3210. /**
  3211. * Normalize the current Vector3.
  3212. * Please note that this is an in place operation.
  3213. * @returns the current updated Vector3
  3214. */
  3215. Vector3.prototype.normalize = function () {
  3216. var len = this.length();
  3217. if (len === 0 || len === 1.0)
  3218. return this;
  3219. var num = 1.0 / len;
  3220. this.x *= num;
  3221. this.y *= num;
  3222. this.z *= num;
  3223. return this;
  3224. };
  3225. /**
  3226. * Normalize the current Vector3 to a new vector
  3227. * @returns the new Vector3
  3228. */
  3229. Vector3.prototype.normalizeToNew = function () {
  3230. var normalized = new Vector3(0, 0, 0);
  3231. this.normalizeToRef(normalized);
  3232. return normalized;
  3233. };
  3234. /**
  3235. * Normalize the current Vector3 to the reference
  3236. * @param reference define the Vector3 to update
  3237. * @returns the updated Vector3
  3238. */
  3239. Vector3.prototype.normalizeToRef = function (reference) {
  3240. var len = this.length();
  3241. if (len === 0 || len === 1.0) {
  3242. reference.set(this.x, this.y, this.z);
  3243. return reference;
  3244. }
  3245. var scale = 1.0 / len;
  3246. this.scaleToRef(scale, reference);
  3247. return reference;
  3248. };
  3249. /**
  3250. * Creates a new Vector3 copied from the current Vector3
  3251. * @returns the new Vector3
  3252. */
  3253. Vector3.prototype.clone = function () {
  3254. return new Vector3(this.x, this.y, this.z);
  3255. };
  3256. /**
  3257. * Copies the given vector coordinates to the current Vector3 ones
  3258. * @param source defines the source Vector3
  3259. * @returns the current updated Vector3
  3260. */
  3261. Vector3.prototype.copyFrom = function (source) {
  3262. this.x = source.x;
  3263. this.y = source.y;
  3264. this.z = source.z;
  3265. return this;
  3266. };
  3267. /**
  3268. * Copies the given floats to the current Vector3 coordinates
  3269. * @param x defines the x coordinate of the operand
  3270. * @param y defines the y coordinate of the operand
  3271. * @param z defines the z coordinate of the operand
  3272. * @returns the current updated Vector3
  3273. */
  3274. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3275. this.x = x;
  3276. this.y = y;
  3277. this.z = z;
  3278. return this;
  3279. };
  3280. /**
  3281. * Copies the given floats to the current Vector3 coordinates
  3282. * @param x defines the x coordinate of the operand
  3283. * @param y defines the y coordinate of the operand
  3284. * @param z defines the z coordinate of the operand
  3285. * @returns the current updated Vector3
  3286. */
  3287. Vector3.prototype.set = function (x, y, z) {
  3288. return this.copyFromFloats(x, y, z);
  3289. };
  3290. // Statics
  3291. /**
  3292. * Get the clip factor between two vectors
  3293. * @param vector0 defines the first operand
  3294. * @param vector1 defines the second operand
  3295. * @param axis defines the axis to use
  3296. * @param size defines the size along the axis
  3297. * @returns the clip factor
  3298. */
  3299. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3300. var d0 = Vector3.Dot(vector0, axis) - size;
  3301. var d1 = Vector3.Dot(vector1, axis) - size;
  3302. var s = d0 / (d0 - d1);
  3303. return s;
  3304. };
  3305. /**
  3306. * Get angle between two vectors
  3307. * @param vector0 angle between vector0 and vector1
  3308. * @param vector1 angle between vector0 and vector1
  3309. * @param normal direction of the normal
  3310. * @return the angle between vector0 and vector1
  3311. */
  3312. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3313. var v0 = vector0.clone().normalize();
  3314. var v1 = vector1.clone().normalize();
  3315. var dot = Vector3.Dot(v0, v1);
  3316. var n = Vector3.Cross(v0, v1);
  3317. if (Vector3.Dot(n, normal) > 0) {
  3318. return Math.acos(dot);
  3319. }
  3320. return -Math.acos(dot);
  3321. };
  3322. /**
  3323. * Returns a new Vector3 set from the index "offset" of the given array
  3324. * @param array defines the source array
  3325. * @param offset defines the offset in the source array
  3326. * @returns the new Vector3
  3327. */
  3328. Vector3.FromArray = function (array, offset) {
  3329. if (!offset) {
  3330. offset = 0;
  3331. }
  3332. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3333. };
  3334. /**
  3335. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3336. * This function is deprecated. Use FromArray instead
  3337. * @param array defines the source array
  3338. * @param offset defines the offset in the source array
  3339. * @returns the new Vector3
  3340. */
  3341. Vector3.FromFloatArray = function (array, offset) {
  3342. return Vector3.FromArray(array, offset);
  3343. };
  3344. /**
  3345. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.FromArrayToRef = function (array, offset, result) {
  3351. result.x = array[offset];
  3352. result.y = array[offset + 1];
  3353. result.z = array[offset + 2];
  3354. };
  3355. /**
  3356. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3357. * This function is deprecated. Use FromArrayToRef instead.
  3358. * @param array defines the source array
  3359. * @param offset defines the offset in the source array
  3360. * @param result defines the Vector3 where to store the result
  3361. */
  3362. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3363. return Vector3.FromArrayToRef(array, offset, result);
  3364. };
  3365. /**
  3366. * Sets the given vector "result" with the given floats.
  3367. * @param x defines the x coordinate of the source
  3368. * @param y defines the y coordinate of the source
  3369. * @param z defines the z coordinate of the source
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3373. result.x = x;
  3374. result.y = y;
  3375. result.z = z;
  3376. };
  3377. /**
  3378. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3379. * @returns a new empty Vector3
  3380. */
  3381. Vector3.Zero = function () {
  3382. return new Vector3(0.0, 0.0, 0.0);
  3383. };
  3384. /**
  3385. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3386. * @returns a new unit Vector3
  3387. */
  3388. Vector3.One = function () {
  3389. return new Vector3(1.0, 1.0, 1.0);
  3390. };
  3391. /**
  3392. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3393. * @returns a new up Vector3
  3394. */
  3395. Vector3.Up = function () {
  3396. return new Vector3(0.0, 1.0, 0.0);
  3397. };
  3398. /**
  3399. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3400. * @returns a new down Vector3
  3401. */
  3402. Vector3.Down = function () {
  3403. return new Vector3(0.0, -1.0, 0.0);
  3404. };
  3405. /**
  3406. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3407. * @returns a new forward Vector3
  3408. */
  3409. Vector3.Forward = function () {
  3410. return new Vector3(0.0, 0.0, 1.0);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3414. * @returns a new forward Vector3
  3415. */
  3416. Vector3.Backward = function () {
  3417. return new Vector3(0.0, 0.0, -1.0);
  3418. };
  3419. /**
  3420. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3421. * @returns a new right Vector3
  3422. */
  3423. Vector3.Right = function () {
  3424. return new Vector3(1.0, 0.0, 0.0);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3428. * @returns a new left Vector3
  3429. */
  3430. Vector3.Left = function () {
  3431. return new Vector3(-1.0, 0.0, 0.0);
  3432. };
  3433. /**
  3434. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3435. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3436. * @param vector defines the Vector3 to transform
  3437. * @param transformation defines the transformation matrix
  3438. * @returns the transformed Vector3
  3439. */
  3440. Vector3.TransformCoordinates = function (vector, transformation) {
  3441. var result = Vector3.Zero();
  3442. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3443. return result;
  3444. };
  3445. /**
  3446. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3447. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3448. * @param vector defines the Vector3 to transform
  3449. * @param transformation defines the transformation matrix
  3450. * @param result defines the Vector3 where to store the result
  3451. */
  3452. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3456. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3457. result.x = x / w;
  3458. result.y = y / w;
  3459. result.z = z / w;
  3460. };
  3461. /**
  3462. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3463. * This method computes tranformed coordinates only, not transformed direction vectors
  3464. * @param x define the x coordinate of the source vector
  3465. * @param y define the y coordinate of the source vector
  3466. * @param z define the z coordinate of the source vector
  3467. * @param transformation defines the transformation matrix
  3468. * @param result defines the Vector3 where to store the result
  3469. */
  3470. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3471. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3472. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3473. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3474. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3475. result.x = rx / rw;
  3476. result.y = ry / rw;
  3477. result.z = rz / rw;
  3478. };
  3479. /**
  3480. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3481. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3482. * @param vector defines the Vector3 to transform
  3483. * @param transformation defines the transformation matrix
  3484. * @returns the new Vector3
  3485. */
  3486. Vector3.TransformNormal = function (vector, transformation) {
  3487. var result = Vector3.Zero();
  3488. Vector3.TransformNormalToRef(vector, transformation, result);
  3489. return result;
  3490. };
  3491. /**
  3492. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3493. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3494. * @param vector defines the Vector3 to transform
  3495. * @param transformation defines the transformation matrix
  3496. * @param result defines the Vector3 where to store the result
  3497. */
  3498. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3499. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3500. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3501. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3502. result.x = x;
  3503. result.y = y;
  3504. result.z = z;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param x define the x coordinate of the source vector
  3510. * @param y define the y coordinate of the source vector
  3511. * @param z define the z coordinate of the source vector
  3512. * @param transformation defines the transformation matrix
  3513. * @param result defines the Vector3 where to store the result
  3514. */
  3515. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3516. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3517. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3518. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3519. };
  3520. /**
  3521. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3522. * @param value1 defines the first control point
  3523. * @param value2 defines the second control point
  3524. * @param value3 defines the third control point
  3525. * @param value4 defines the fourth control point
  3526. * @param amount defines the amount on the spline to use
  3527. * @returns the new Vector3
  3528. */
  3529. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3530. var squared = amount * amount;
  3531. var cubed = amount * squared;
  3532. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3533. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3534. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3535. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3536. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3537. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3538. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3539. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3540. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3541. return new Vector3(x, y, z);
  3542. };
  3543. /**
  3544. * 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"
  3545. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3546. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3547. * @param value defines the current value
  3548. * @param min defines the lower range value
  3549. * @param max defines the upper range value
  3550. * @returns the new Vector3
  3551. */
  3552. Vector3.Clamp = function (value, min, max) {
  3553. var x = value.x;
  3554. x = (x > max.x) ? max.x : x;
  3555. x = (x < min.x) ? min.x : x;
  3556. var y = value.y;
  3557. y = (y > max.y) ? max.y : y;
  3558. y = (y < min.y) ? min.y : y;
  3559. var z = value.z;
  3560. z = (z > max.z) ? max.z : z;
  3561. z = (z < min.z) ? min.z : z;
  3562. return new Vector3(x, y, z);
  3563. };
  3564. /**
  3565. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3566. * @param value1 defines the first control point
  3567. * @param tangent1 defines the first tangent vector
  3568. * @param value2 defines the second control point
  3569. * @param tangent2 defines the second tangent vector
  3570. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3571. * @returns the new Vector3
  3572. */
  3573. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3574. var squared = amount * amount;
  3575. var cubed = amount * squared;
  3576. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3577. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3578. var part3 = (cubed - (2.0 * squared)) + amount;
  3579. var part4 = cubed - squared;
  3580. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3581. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3582. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3583. return new Vector3(x, y, z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3587. * @param start defines the start value
  3588. * @param end defines the end value
  3589. * @param amount max defines amount between both (between 0 and 1)
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.Lerp = function (start, end, amount) {
  3593. var result = new Vector3(0, 0, 0);
  3594. Vector3.LerpToRef(start, end, amount, result);
  3595. return result;
  3596. };
  3597. /**
  3598. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3599. * @param start defines the start value
  3600. * @param end defines the end value
  3601. * @param amount max defines amount between both (between 0 and 1)
  3602. * @param result defines the Vector3 where to store the result
  3603. */
  3604. Vector3.LerpToRef = function (start, end, amount, result) {
  3605. result.x = start.x + ((end.x - start.x) * amount);
  3606. result.y = start.y + ((end.y - start.y) * amount);
  3607. result.z = start.z + ((end.z - start.z) * amount);
  3608. };
  3609. /**
  3610. * Returns the dot product (float) between the vectors "left" and "right"
  3611. * @param left defines the left operand
  3612. * @param right defines the right operand
  3613. * @returns the dot product
  3614. */
  3615. Vector3.Dot = function (left, right) {
  3616. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3617. };
  3618. /**
  3619. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3620. * The cross product is then orthogonal to both "left" and "right"
  3621. * @param left defines the left operand
  3622. * @param right defines the right operand
  3623. * @returns the cross product
  3624. */
  3625. Vector3.Cross = function (left, right) {
  3626. var result = Vector3.Zero();
  3627. Vector3.CrossToRef(left, right, result);
  3628. return result;
  3629. };
  3630. /**
  3631. * Sets the given vector "result" with the cross product of "left" and "right"
  3632. * The cross product is then orthogonal to both "left" and "right"
  3633. * @param left defines the left operand
  3634. * @param right defines the right operand
  3635. * @param result defines the Vector3 where to store the result
  3636. */
  3637. Vector3.CrossToRef = function (left, right, result) {
  3638. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3639. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3640. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3641. result.copyFrom(MathTmp.Vector3[0]);
  3642. };
  3643. /**
  3644. * Returns a new Vector3 as the normalization of the given vector
  3645. * @param vector defines the Vector3 to normalize
  3646. * @returns the new Vector3
  3647. */
  3648. Vector3.Normalize = function (vector) {
  3649. var result = Vector3.Zero();
  3650. Vector3.NormalizeToRef(vector, result);
  3651. return result;
  3652. };
  3653. /**
  3654. * Sets the given vector "result" with the normalization of the given first vector
  3655. * @param vector defines the Vector3 to normalize
  3656. * @param result defines the Vector3 where to store the result
  3657. */
  3658. Vector3.NormalizeToRef = function (vector, result) {
  3659. result.copyFrom(vector);
  3660. result.normalize();
  3661. };
  3662. /**
  3663. * Project a Vector3 onto screen space
  3664. * @param vector defines the Vector3 to project
  3665. * @param world defines the world matrix to use
  3666. * @param transform defines the transform (view x projection) matrix to use
  3667. * @param viewport defines the screen viewport to use
  3668. * @returns the new Vector3
  3669. */
  3670. Vector3.Project = function (vector, world, transform, viewport) {
  3671. var cw = viewport.width;
  3672. var ch = viewport.height;
  3673. var cx = viewport.x;
  3674. var cy = viewport.y;
  3675. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3676. 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);
  3677. var matrix = MathTmp.Matrix[0];
  3678. world.multiplyToRef(transform, matrix);
  3679. matrix.multiplyToRef(viewportMatrix, matrix);
  3680. return Vector3.TransformCoordinates(vector, matrix);
  3681. };
  3682. /**
  3683. * Unproject from screen space to object space
  3684. * @param source defines the screen space Vector3 to use
  3685. * @param viewportWidth defines the current width of the viewport
  3686. * @param viewportHeight defines the current height of the viewport
  3687. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3688. * @param transform defines the transform (view x projection) matrix to use
  3689. * @returns the new Vector3
  3690. */
  3691. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.invert();
  3695. source.x = source.x / viewportWidth * 2 - 1;
  3696. source.y = -(source.y / viewportHeight * 2 - 1);
  3697. var vector = Vector3.TransformCoordinates(source, matrix);
  3698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3699. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3700. vector = vector.scale(1.0 / num);
  3701. }
  3702. return vector;
  3703. };
  3704. /**
  3705. * Unproject from screen space to object space
  3706. * @param source defines the screen space Vector3 to use
  3707. * @param viewportWidth defines the current width of the viewport
  3708. * @param viewportHeight defines the current height of the viewport
  3709. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3710. * @param view defines the view matrix to use
  3711. * @param projection defines the projection matrix to use
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3715. var result = Vector3.Zero();
  3716. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3717. return result;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @param result defines the Vector3 where to store the result
  3728. */
  3729. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3730. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3731. };
  3732. /**
  3733. * Unproject from screen space to object space
  3734. * @param sourceX defines the screen space x coordinate to use
  3735. * @param sourceY defines the screen space y coordinate to use
  3736. * @param sourceZ defines the screen space z coordinate to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. var matrix = MathTmp.Matrix[0];
  3746. world.multiplyToRef(view, matrix);
  3747. matrix.multiplyToRef(projection, matrix);
  3748. matrix.invert();
  3749. var screenSource = MathTmp.Vector3[0];
  3750. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3751. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3752. screenSource.z = 2 * sourceZ - 1.0;
  3753. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3754. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3756. result.scaleInPlace(1.0 / num);
  3757. }
  3758. };
  3759. /**
  3760. * Gets the minimal coordinate values between two Vector3
  3761. * @param left defines the first operand
  3762. * @param right defines the second operand
  3763. * @returns the new Vector3
  3764. */
  3765. Vector3.Minimize = function (left, right) {
  3766. var min = left.clone();
  3767. min.minimizeInPlace(right);
  3768. return min;
  3769. };
  3770. /**
  3771. * Gets the maximal coordinate values between two Vector3
  3772. * @param left defines the first operand
  3773. * @param right defines the second operand
  3774. * @returns the new Vector3
  3775. */
  3776. Vector3.Maximize = function (left, right) {
  3777. var max = left.clone();
  3778. max.maximizeInPlace(right);
  3779. return max;
  3780. };
  3781. /**
  3782. * Returns the distance between the vectors "value1" and "value2"
  3783. * @param value1 defines the first operand
  3784. * @param value2 defines the second operand
  3785. * @returns the distance
  3786. */
  3787. Vector3.Distance = function (value1, value2) {
  3788. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3789. };
  3790. /**
  3791. * Returns the squared distance between the vectors "value1" and "value2"
  3792. * @param value1 defines the first operand
  3793. * @param value2 defines the second operand
  3794. * @returns the squared distance
  3795. */
  3796. Vector3.DistanceSquared = function (value1, value2) {
  3797. var x = value1.x - value2.x;
  3798. var y = value1.y - value2.y;
  3799. var z = value1.z - value2.z;
  3800. return (x * x) + (y * y) + (z * z);
  3801. };
  3802. /**
  3803. * Returns a new Vector3 located at the center between "value1" and "value2"
  3804. * @param value1 defines the first operand
  3805. * @param value2 defines the second operand
  3806. * @returns the new Vector3
  3807. */
  3808. Vector3.Center = function (value1, value2) {
  3809. var center = value1.add(value2);
  3810. center.scaleInPlace(0.5);
  3811. return center;
  3812. };
  3813. /**
  3814. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3815. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3816. * to something in order to rotate it from its local system to the given target system
  3817. * Note: axis1, axis2 and axis3 are normalized during this operation
  3818. * @param axis1 defines the first axis
  3819. * @param axis2 defines the second axis
  3820. * @param axis3 defines the third axis
  3821. * @returns a new Vector3
  3822. */
  3823. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3824. var rotation = Vector3.Zero();
  3825. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3826. return rotation;
  3827. };
  3828. /**
  3829. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3830. * @param axis1 defines the first axis
  3831. * @param axis2 defines the second axis
  3832. * @param axis3 defines the third axis
  3833. * @param ref defines the Vector3 where to store the result
  3834. */
  3835. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3836. var quat = MathTmp.Quaternion[0];
  3837. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3838. quat.toEulerAnglesToRef(ref);
  3839. };
  3840. return Vector3;
  3841. }());
  3842. BABYLON.Vector3 = Vector3;
  3843. //Vector4 class created for EulerAngle class conversion to Quaternion
  3844. var Vector4 = /** @class */ (function () {
  3845. /**
  3846. * Creates a Vector4 object from the given floats.
  3847. */
  3848. function Vector4(x, y, z, w) {
  3849. this.x = x;
  3850. this.y = y;
  3851. this.z = z;
  3852. this.w = w;
  3853. }
  3854. /**
  3855. * Returns the string with the Vector4 coordinates.
  3856. */
  3857. Vector4.prototype.toString = function () {
  3858. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3859. };
  3860. /**
  3861. * Returns the string "Vector4".
  3862. */
  3863. Vector4.prototype.getClassName = function () {
  3864. return "Vector4";
  3865. };
  3866. /**
  3867. * Returns the Vector4 hash code.
  3868. */
  3869. Vector4.prototype.getHashCode = function () {
  3870. var hash = this.x || 0;
  3871. hash = (hash * 397) ^ (this.y || 0);
  3872. hash = (hash * 397) ^ (this.z || 0);
  3873. hash = (hash * 397) ^ (this.w || 0);
  3874. return hash;
  3875. };
  3876. // Operators
  3877. /**
  3878. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3879. */
  3880. Vector4.prototype.asArray = function () {
  3881. var result = new Array();
  3882. this.toArray(result, 0);
  3883. return result;
  3884. };
  3885. /**
  3886. * Populates the given array from the given index with the Vector4 coordinates.
  3887. * Returns the Vector4.
  3888. */
  3889. Vector4.prototype.toArray = function (array, index) {
  3890. if (index === undefined) {
  3891. index = 0;
  3892. }
  3893. array[index] = this.x;
  3894. array[index + 1] = this.y;
  3895. array[index + 2] = this.z;
  3896. array[index + 3] = this.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Adds the given vector to the current Vector4.
  3901. * Returns the updated Vector4.
  3902. */
  3903. Vector4.prototype.addInPlace = function (otherVector) {
  3904. this.x += otherVector.x;
  3905. this.y += otherVector.y;
  3906. this.z += otherVector.z;
  3907. this.w += otherVector.w;
  3908. return this;
  3909. };
  3910. /**
  3911. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3912. */
  3913. Vector4.prototype.add = function (otherVector) {
  3914. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3915. };
  3916. /**
  3917. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3918. * Returns the current Vector4.
  3919. */
  3920. Vector4.prototype.addToRef = function (otherVector, result) {
  3921. result.x = this.x + otherVector.x;
  3922. result.y = this.y + otherVector.y;
  3923. result.z = this.z + otherVector.z;
  3924. result.w = this.w + otherVector.w;
  3925. return this;
  3926. };
  3927. /**
  3928. * Subtract in place the given vector from the current Vector4.
  3929. * Returns the updated Vector4.
  3930. */
  3931. Vector4.prototype.subtractInPlace = function (otherVector) {
  3932. this.x -= otherVector.x;
  3933. this.y -= otherVector.y;
  3934. this.z -= otherVector.z;
  3935. this.w -= otherVector.w;
  3936. return this;
  3937. };
  3938. /**
  3939. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3940. */
  3941. Vector4.prototype.subtract = function (otherVector) {
  3942. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3943. };
  3944. /**
  3945. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3946. * Returns the current Vector4.
  3947. */
  3948. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3949. result.x = this.x - otherVector.x;
  3950. result.y = this.y - otherVector.y;
  3951. result.z = this.z - otherVector.z;
  3952. result.w = this.w - otherVector.w;
  3953. return this;
  3954. };
  3955. /**
  3956. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3957. */
  3958. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3959. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3960. };
  3961. /**
  3962. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3963. * Returns the current Vector4.
  3964. */
  3965. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3966. result.x = this.x - x;
  3967. result.y = this.y - y;
  3968. result.z = this.z - z;
  3969. result.w = this.w - w;
  3970. return this;
  3971. };
  3972. /**
  3973. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3974. */
  3975. Vector4.prototype.negate = function () {
  3976. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3977. };
  3978. /**
  3979. * Multiplies the current Vector4 coordinates by scale (float).
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.scaleInPlace = function (scale) {
  3983. this.x *= scale;
  3984. this.y *= scale;
  3985. this.z *= scale;
  3986. this.w *= scale;
  3987. return this;
  3988. };
  3989. /**
  3990. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3991. */
  3992. Vector4.prototype.scale = function (scale) {
  3993. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3994. };
  3995. /**
  3996. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3997. * Returns the current Vector4.
  3998. */
  3999. Vector4.prototype.scaleToRef = function (scale, result) {
  4000. result.x = this.x * scale;
  4001. result.y = this.y * scale;
  4002. result.z = this.z * scale;
  4003. result.w = this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4008. * @param scale defines the scale factor
  4009. * @param result defines the Vector4 object where to store the result
  4010. * @returns the unmodified current Vector4
  4011. */
  4012. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4013. result.x += this.x * scale;
  4014. result.y += this.y * scale;
  4015. result.z += this.z * scale;
  4016. result.w += this.w * scale;
  4017. return this;
  4018. };
  4019. /**
  4020. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4021. */
  4022. Vector4.prototype.equals = function (otherVector) {
  4023. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4024. };
  4025. /**
  4026. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4027. */
  4028. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4029. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4030. return otherVector
  4031. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4032. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4033. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4034. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4035. };
  4036. /**
  4037. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4038. */
  4039. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4040. return this.x === x && this.y === y && this.z === z && this.w === w;
  4041. };
  4042. /**
  4043. * Multiplies in place the current Vector4 by the given one.
  4044. * Returns the updated Vector4.
  4045. */
  4046. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4047. this.x *= otherVector.x;
  4048. this.y *= otherVector.y;
  4049. this.z *= otherVector.z;
  4050. this.w *= otherVector.w;
  4051. return this;
  4052. };
  4053. /**
  4054. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4055. */
  4056. Vector4.prototype.multiply = function (otherVector) {
  4057. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4058. };
  4059. /**
  4060. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4061. * Returns the current Vector4.
  4062. */
  4063. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4064. result.x = this.x * otherVector.x;
  4065. result.y = this.y * otherVector.y;
  4066. result.z = this.z * otherVector.z;
  4067. result.w = this.w * otherVector.w;
  4068. return this;
  4069. };
  4070. /**
  4071. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4072. */
  4073. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4074. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4075. };
  4076. /**
  4077. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4078. */
  4079. Vector4.prototype.divide = function (otherVector) {
  4080. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4081. };
  4082. /**
  4083. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4084. * Returns the current Vector4.
  4085. */
  4086. Vector4.prototype.divideToRef = function (otherVector, result) {
  4087. result.x = this.x / otherVector.x;
  4088. result.y = this.y / otherVector.y;
  4089. result.z = this.z / otherVector.z;
  4090. result.w = this.w / otherVector.w;
  4091. return this;
  4092. };
  4093. /**
  4094. * Divides the current Vector3 coordinates by the given ones.
  4095. * @returns the updated Vector3.
  4096. */
  4097. Vector4.prototype.divideInPlace = function (otherVector) {
  4098. return this.divideToRef(otherVector, this);
  4099. };
  4100. /**
  4101. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4102. * @param other defines the second operand
  4103. * @returns the current updated Vector4
  4104. */
  4105. Vector4.prototype.minimizeInPlace = function (other) {
  4106. if (other.x < this.x)
  4107. this.x = other.x;
  4108. if (other.y < this.y)
  4109. this.y = other.y;
  4110. if (other.z < this.z)
  4111. this.z = other.z;
  4112. if (other.w < this.w)
  4113. this.w = other.w;
  4114. return this;
  4115. };
  4116. /**
  4117. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4118. * @param other defines the second operand
  4119. * @returns the current updated Vector4
  4120. */
  4121. Vector4.prototype.maximizeInPlace = function (other) {
  4122. if (other.x > this.x)
  4123. this.x = other.x;
  4124. if (other.y > this.y)
  4125. this.y = other.y;
  4126. if (other.z > this.z)
  4127. this.z = other.z;
  4128. if (other.w > this.w)
  4129. this.w = other.w;
  4130. return this;
  4131. };
  4132. /**
  4133. * Gets a new Vector4 from current Vector4 floored values
  4134. * @returns a new Vector4
  4135. */
  4136. Vector4.prototype.floor = function () {
  4137. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4138. };
  4139. /**
  4140. * Gets a new Vector4 from current Vector3 floored values
  4141. * @returns a new Vector4
  4142. */
  4143. Vector4.prototype.fract = function () {
  4144. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4145. };
  4146. // Properties
  4147. /**
  4148. * Returns the Vector4 length (float).
  4149. */
  4150. Vector4.prototype.length = function () {
  4151. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4152. };
  4153. /**
  4154. * Returns the Vector4 squared length (float).
  4155. */
  4156. Vector4.prototype.lengthSquared = function () {
  4157. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4158. };
  4159. // Methods
  4160. /**
  4161. * Normalizes in place the Vector4.
  4162. * Returns the updated Vector4.
  4163. */
  4164. Vector4.prototype.normalize = function () {
  4165. var len = this.length();
  4166. if (len === 0)
  4167. return this;
  4168. var num = 1.0 / len;
  4169. this.x *= num;
  4170. this.y *= num;
  4171. this.z *= num;
  4172. this.w *= num;
  4173. return this;
  4174. };
  4175. /**
  4176. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4177. */
  4178. Vector4.prototype.toVector3 = function () {
  4179. return new Vector3(this.x, this.y, this.z);
  4180. };
  4181. /**
  4182. * Returns a new Vector4 copied from the current one.
  4183. */
  4184. Vector4.prototype.clone = function () {
  4185. return new Vector4(this.x, this.y, this.z, this.w);
  4186. };
  4187. /**
  4188. * Updates the current Vector4 with the given one coordinates.
  4189. * Returns the updated Vector4.
  4190. */
  4191. Vector4.prototype.copyFrom = function (source) {
  4192. this.x = source.x;
  4193. this.y = source.y;
  4194. this.z = source.z;
  4195. this.w = source.w;
  4196. return this;
  4197. };
  4198. /**
  4199. * Updates the current Vector4 coordinates with the given floats.
  4200. * Returns the updated Vector4.
  4201. */
  4202. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4203. this.x = x;
  4204. this.y = y;
  4205. this.z = z;
  4206. this.w = w;
  4207. return this;
  4208. };
  4209. /**
  4210. * Updates the current Vector4 coordinates with the given floats.
  4211. * Returns the updated Vector4.
  4212. */
  4213. Vector4.prototype.set = function (x, y, z, w) {
  4214. return this.copyFromFloats(x, y, z, w);
  4215. };
  4216. // Statics
  4217. /**
  4218. * Returns a new Vector4 set from the starting index of the given array.
  4219. */
  4220. Vector4.FromArray = function (array, offset) {
  4221. if (!offset) {
  4222. offset = 0;
  4223. }
  4224. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4225. };
  4226. /**
  4227. * Updates the given vector "result" from the starting index of the given array.
  4228. */
  4229. Vector4.FromArrayToRef = function (array, offset, result) {
  4230. result.x = array[offset];
  4231. result.y = array[offset + 1];
  4232. result.z = array[offset + 2];
  4233. result.w = array[offset + 3];
  4234. };
  4235. /**
  4236. * Updates the given vector "result" from the starting index of the given Float32Array.
  4237. */
  4238. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4239. Vector4.FromArrayToRef(array, offset, result);
  4240. };
  4241. /**
  4242. * Updates the given vector "result" coordinates from the given floats.
  4243. */
  4244. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4245. result.x = x;
  4246. result.y = y;
  4247. result.z = z;
  4248. result.w = w;
  4249. };
  4250. /**
  4251. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4252. */
  4253. Vector4.Zero = function () {
  4254. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4255. };
  4256. /**
  4257. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4258. */
  4259. Vector4.One = function () {
  4260. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4261. };
  4262. /**
  4263. * Returns a new normalized Vector4 from the given one.
  4264. */
  4265. Vector4.Normalize = function (vector) {
  4266. var result = Vector4.Zero();
  4267. Vector4.NormalizeToRef(vector, result);
  4268. return result;
  4269. };
  4270. /**
  4271. * Updates the given vector "result" from the normalization of the given one.
  4272. */
  4273. Vector4.NormalizeToRef = function (vector, result) {
  4274. result.copyFrom(vector);
  4275. result.normalize();
  4276. };
  4277. Vector4.Minimize = function (left, right) {
  4278. var min = left.clone();
  4279. min.minimizeInPlace(right);
  4280. return min;
  4281. };
  4282. Vector4.Maximize = function (left, right) {
  4283. var max = left.clone();
  4284. max.maximizeInPlace(right);
  4285. return max;
  4286. };
  4287. /**
  4288. * Returns the distance (float) between the vectors "value1" and "value2".
  4289. */
  4290. Vector4.Distance = function (value1, value2) {
  4291. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4292. };
  4293. /**
  4294. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4295. */
  4296. Vector4.DistanceSquared = function (value1, value2) {
  4297. var x = value1.x - value2.x;
  4298. var y = value1.y - value2.y;
  4299. var z = value1.z - value2.z;
  4300. var w = value1.w - value2.w;
  4301. return (x * x) + (y * y) + (z * z) + (w * w);
  4302. };
  4303. /**
  4304. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4305. */
  4306. Vector4.Center = function (value1, value2) {
  4307. var center = value1.add(value2);
  4308. center.scaleInPlace(0.5);
  4309. return center;
  4310. };
  4311. /**
  4312. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4313. * This methods computes transformed normalized direction vectors only.
  4314. */
  4315. Vector4.TransformNormal = function (vector, transformation) {
  4316. var result = Vector4.Zero();
  4317. Vector4.TransformNormalToRef(vector, transformation, result);
  4318. return result;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4325. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4326. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4327. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4328. result.x = x;
  4329. result.y = y;
  4330. result.z = z;
  4331. result.w = vector.w;
  4332. };
  4333. /**
  4334. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4335. * This methods computes transformed normalized direction vectors only.
  4336. */
  4337. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4338. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4339. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4340. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4341. result.w = w;
  4342. };
  4343. return Vector4;
  4344. }());
  4345. BABYLON.Vector4 = Vector4;
  4346. var Size = /** @class */ (function () {
  4347. /**
  4348. * Creates a Size object from the given width and height (floats).
  4349. */
  4350. function Size(width, height) {
  4351. this.width = width;
  4352. this.height = height;
  4353. }
  4354. // Returns a string with the Size width and height.
  4355. Size.prototype.toString = function () {
  4356. return "{W: " + this.width + ", H: " + this.height + "}";
  4357. };
  4358. /**
  4359. * Returns the string "Size"
  4360. */
  4361. Size.prototype.getClassName = function () {
  4362. return "Size";
  4363. };
  4364. /**
  4365. * Returns the Size hash code.
  4366. */
  4367. Size.prototype.getHashCode = function () {
  4368. var hash = this.width || 0;
  4369. hash = (hash * 397) ^ (this.height || 0);
  4370. return hash;
  4371. };
  4372. /**
  4373. * Updates the current size from the given one.
  4374. * Returns the updated Size.
  4375. */
  4376. Size.prototype.copyFrom = function (src) {
  4377. this.width = src.width;
  4378. this.height = src.height;
  4379. };
  4380. /**
  4381. * Updates in place the current Size from the given floats.
  4382. * Returns the updated Size.
  4383. */
  4384. Size.prototype.copyFromFloats = function (width, height) {
  4385. this.width = width;
  4386. this.height = height;
  4387. return this;
  4388. };
  4389. /**
  4390. * Updates in place the current Size from the given floats.
  4391. * Returns the updated Size.
  4392. */
  4393. Size.prototype.set = function (width, height) {
  4394. return this.copyFromFloats(width, height);
  4395. };
  4396. /**
  4397. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4398. */
  4399. Size.prototype.multiplyByFloats = function (w, h) {
  4400. return new Size(this.width * w, this.height * h);
  4401. };
  4402. /**
  4403. * Returns a new Size copied from the given one.
  4404. */
  4405. Size.prototype.clone = function () {
  4406. return new Size(this.width, this.height);
  4407. };
  4408. /**
  4409. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4410. */
  4411. Size.prototype.equals = function (other) {
  4412. if (!other) {
  4413. return false;
  4414. }
  4415. return (this.width === other.width) && (this.height === other.height);
  4416. };
  4417. Object.defineProperty(Size.prototype, "surface", {
  4418. /**
  4419. * Returns the surface of the Size : width * height (float).
  4420. */
  4421. get: function () {
  4422. return this.width * this.height;
  4423. },
  4424. enumerable: true,
  4425. configurable: true
  4426. });
  4427. /**
  4428. * Returns a new Size set to (0.0, 0.0)
  4429. */
  4430. Size.Zero = function () {
  4431. return new Size(0.0, 0.0);
  4432. };
  4433. /**
  4434. * Returns a new Size set as the addition result of the current Size and the given one.
  4435. */
  4436. Size.prototype.add = function (otherSize) {
  4437. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4438. return r;
  4439. };
  4440. /**
  4441. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4442. */
  4443. Size.prototype.subtract = function (otherSize) {
  4444. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4445. return r;
  4446. };
  4447. /**
  4448. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4449. */
  4450. Size.Lerp = function (start, end, amount) {
  4451. var w = start.width + ((end.width - start.width) * amount);
  4452. var h = start.height + ((end.height - start.height) * amount);
  4453. return new Size(w, h);
  4454. };
  4455. return Size;
  4456. }());
  4457. BABYLON.Size = Size;
  4458. /**
  4459. * Class used to store quaternion data
  4460. * @see https://en.wikipedia.org/wiki/Quaternion
  4461. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4462. */
  4463. var Quaternion = /** @class */ (function () {
  4464. /**
  4465. * Creates a new Quaternion from the given floats
  4466. * @param x defines the first component (0 by default)
  4467. * @param y defines the second component (0 by default)
  4468. * @param z defines the third component (0 by default)
  4469. * @param w defines the fourth component (1.0 by default)
  4470. */
  4471. function Quaternion(
  4472. /** defines the first component (0 by default) */
  4473. x,
  4474. /** defines the second component (0 by default) */
  4475. y,
  4476. /** defines the third component (0 by default) */
  4477. z,
  4478. /** defines the fourth component (1.0 by default) */
  4479. w) {
  4480. if (x === void 0) { x = 0.0; }
  4481. if (y === void 0) { y = 0.0; }
  4482. if (z === void 0) { z = 0.0; }
  4483. if (w === void 0) { w = 1.0; }
  4484. this.x = x;
  4485. this.y = y;
  4486. this.z = z;
  4487. this.w = w;
  4488. }
  4489. /**
  4490. * Gets a string representation for the current quaternion
  4491. * @returns a string with the Quaternion coordinates
  4492. */
  4493. Quaternion.prototype.toString = function () {
  4494. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4495. };
  4496. /**
  4497. * Gets the class name of the quaternion
  4498. * @returns the string "Quaternion"
  4499. */
  4500. Quaternion.prototype.getClassName = function () {
  4501. return "Quaternion";
  4502. };
  4503. /**
  4504. * Gets a hash code for this quaternion
  4505. * @returns the quaternion hash code
  4506. */
  4507. Quaternion.prototype.getHashCode = function () {
  4508. var hash = this.x || 0;
  4509. hash = (hash * 397) ^ (this.y || 0);
  4510. hash = (hash * 397) ^ (this.z || 0);
  4511. hash = (hash * 397) ^ (this.w || 0);
  4512. return hash;
  4513. };
  4514. /**
  4515. * Copy the quaternion to an array
  4516. * @returns a new array populated with 4 elements from the quaternion coordinates
  4517. */
  4518. Quaternion.prototype.asArray = function () {
  4519. return [this.x, this.y, this.z, this.w];
  4520. };
  4521. /**
  4522. * Check if two quaternions are equals
  4523. * @param otherQuaternion defines the second operand
  4524. * @return true if the current quaternion and the given one coordinates are strictly equals
  4525. */
  4526. Quaternion.prototype.equals = function (otherQuaternion) {
  4527. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4528. };
  4529. /**
  4530. * Clone the current quaternion
  4531. * @returns a new quaternion copied from the current one
  4532. */
  4533. Quaternion.prototype.clone = function () {
  4534. return new Quaternion(this.x, this.y, this.z, this.w);
  4535. };
  4536. /**
  4537. * Copy a quaternion to the current one
  4538. * @param other defines the other quaternion
  4539. * @returns the updated current quaternion
  4540. */
  4541. Quaternion.prototype.copyFrom = function (other) {
  4542. this.x = other.x;
  4543. this.y = other.y;
  4544. this.z = other.z;
  4545. this.w = other.w;
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion with the given float coordinates
  4550. * @param x defines the x coordinate
  4551. * @param y defines the y coordinate
  4552. * @param z defines the z coordinate
  4553. * @param w defines the w coordinate
  4554. * @returns the updated current quaternion
  4555. */
  4556. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4557. this.x = x;
  4558. this.y = y;
  4559. this.z = z;
  4560. this.w = w;
  4561. return this;
  4562. };
  4563. /**
  4564. * Updates the current quaternion from the given float coordinates
  4565. * @param x defines the x coordinate
  4566. * @param y defines the y coordinate
  4567. * @param z defines the z coordinate
  4568. * @param w defines the w coordinate
  4569. * @returns the updated current quaternion
  4570. */
  4571. Quaternion.prototype.set = function (x, y, z, w) {
  4572. return this.copyFromFloats(x, y, z, w);
  4573. };
  4574. /**
  4575. * Adds two quaternions
  4576. * @param other defines the second operand
  4577. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4578. */
  4579. Quaternion.prototype.add = function (other) {
  4580. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4581. };
  4582. /**
  4583. * Add a quaternion to the current one
  4584. * @param other defines the quaternion to add
  4585. * @returns the current quaternion
  4586. */
  4587. Quaternion.prototype.addInPlace = function (other) {
  4588. this.x += other.x;
  4589. this.y += other.y;
  4590. this.z += other.z;
  4591. this.w += other.w;
  4592. return this;
  4593. };
  4594. /**
  4595. * Subtract two quaternions
  4596. * @param other defines the second operand
  4597. * @returns a new quaternion as the subtraction result of the given one from the current one
  4598. */
  4599. Quaternion.prototype.subtract = function (other) {
  4600. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4601. };
  4602. /**
  4603. * Multiplies the current quaternion by a scale factor
  4604. * @param value defines the scale factor
  4605. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4606. */
  4607. Quaternion.prototype.scale = function (value) {
  4608. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4609. };
  4610. /**
  4611. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4612. * @param scale defines the scale factor
  4613. * @param result defines the Quaternion object where to store the result
  4614. * @returns the unmodified current quaternion
  4615. */
  4616. Quaternion.prototype.scaleToRef = function (scale, result) {
  4617. result.x = this.x * scale;
  4618. result.y = this.y * scale;
  4619. result.z = this.z * scale;
  4620. result.w = this.w * scale;
  4621. return this;
  4622. };
  4623. /**
  4624. * Multiplies in place the current quaternion by a scale factor
  4625. * @param value defines the scale factor
  4626. * @returns the current modified quaternion
  4627. */
  4628. Quaternion.prototype.scaleInPlace = function (value) {
  4629. this.x *= value;
  4630. this.y *= value;
  4631. this.z *= value;
  4632. this.w *= value;
  4633. return this;
  4634. };
  4635. /**
  4636. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4637. * @param scale defines the scale factor
  4638. * @param result defines the Quaternion object where to store the result
  4639. * @returns the unmodified current quaternion
  4640. */
  4641. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4642. result.x += this.x * scale;
  4643. result.y += this.y * scale;
  4644. result.z += this.z * scale;
  4645. result.w += this.w * scale;
  4646. return this;
  4647. };
  4648. /**
  4649. * Multiplies two quaternions
  4650. * @param q1 defines the second operand
  4651. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4652. */
  4653. Quaternion.prototype.multiply = function (q1) {
  4654. var result = new Quaternion(0, 0, 0, 1.0);
  4655. this.multiplyToRef(q1, result);
  4656. return result;
  4657. };
  4658. /**
  4659. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4660. * @param q1 defines the second operand
  4661. * @param result defines the target quaternion
  4662. * @returns the current quaternion
  4663. */
  4664. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4665. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4666. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4667. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4668. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4669. result.copyFromFloats(x, y, z, w);
  4670. return this;
  4671. };
  4672. /**
  4673. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4674. * @param q1 defines the second operand
  4675. * @returns the currentupdated quaternion
  4676. */
  4677. Quaternion.prototype.multiplyInPlace = function (q1) {
  4678. this.multiplyToRef(q1, this);
  4679. return this;
  4680. };
  4681. /**
  4682. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4683. * @param ref defines the target quaternion
  4684. * @returns the current quaternion
  4685. */
  4686. Quaternion.prototype.conjugateToRef = function (ref) {
  4687. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4688. return this;
  4689. };
  4690. /**
  4691. * Conjugates in place (1-q) the current quaternion
  4692. * @returns the current updated quaternion
  4693. */
  4694. Quaternion.prototype.conjugateInPlace = function () {
  4695. this.x *= -1;
  4696. this.y *= -1;
  4697. this.z *= -1;
  4698. return this;
  4699. };
  4700. /**
  4701. * Conjugates in place (1-q) the current quaternion
  4702. * @returns a new quaternion
  4703. */
  4704. Quaternion.prototype.conjugate = function () {
  4705. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4706. return result;
  4707. };
  4708. /**
  4709. * Gets length of current quaternion
  4710. * @returns the quaternion length (float)
  4711. */
  4712. Quaternion.prototype.length = function () {
  4713. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4714. };
  4715. /**
  4716. * Normalize in place the current quaternion
  4717. * @returns the current updated quaternion
  4718. */
  4719. Quaternion.prototype.normalize = function () {
  4720. var length = 1.0 / this.length();
  4721. this.x *= length;
  4722. this.y *= length;
  4723. this.z *= length;
  4724. this.w *= length;
  4725. return this;
  4726. };
  4727. /**
  4728. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4729. * @param order is a reserved parameter and is ignore for now
  4730. * @returns a new Vector3 containing the Euler angles
  4731. */
  4732. Quaternion.prototype.toEulerAngles = function (order) {
  4733. if (order === void 0) { order = "YZX"; }
  4734. var result = Vector3.Zero();
  4735. this.toEulerAnglesToRef(result, order);
  4736. return result;
  4737. };
  4738. /**
  4739. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4740. * @param result defines the vector which will be filled with the Euler angles
  4741. * @param order is a reserved parameter and is ignore for now
  4742. * @returns the current unchanged quaternion
  4743. */
  4744. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4745. if (order === void 0) { order = "YZX"; }
  4746. var qz = this.z;
  4747. var qx = this.x;
  4748. var qy = this.y;
  4749. var qw = this.w;
  4750. var sqw = qw * qw;
  4751. var sqz = qz * qz;
  4752. var sqx = qx * qx;
  4753. var sqy = qy * qy;
  4754. var zAxisY = qy * qz - qx * qw;
  4755. var limit = .4999999;
  4756. if (zAxisY < -limit) {
  4757. result.y = 2 * Math.atan2(qy, qw);
  4758. result.x = Math.PI / 2;
  4759. result.z = 0;
  4760. }
  4761. else if (zAxisY > limit) {
  4762. result.y = 2 * Math.atan2(qy, qw);
  4763. result.x = -Math.PI / 2;
  4764. result.z = 0;
  4765. }
  4766. else {
  4767. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4768. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4769. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4770. }
  4771. return this;
  4772. };
  4773. /**
  4774. * Updates the given rotation matrix with the current quaternion values
  4775. * @param result defines the target matrix
  4776. * @returns the current unchanged quaternion
  4777. */
  4778. Quaternion.prototype.toRotationMatrix = function (result) {
  4779. var xx = this.x * this.x;
  4780. var yy = this.y * this.y;
  4781. var zz = this.z * this.z;
  4782. var xy = this.x * this.y;
  4783. var zw = this.z * this.w;
  4784. var zx = this.z * this.x;
  4785. var yw = this.y * this.w;
  4786. var yz = this.y * this.z;
  4787. var xw = this.x * this.w;
  4788. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4789. result.m[1] = 2.0 * (xy + zw);
  4790. result.m[2] = 2.0 * (zx - yw);
  4791. result.m[3] = 0;
  4792. result.m[4] = 2.0 * (xy - zw);
  4793. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4794. result.m[6] = 2.0 * (yz + xw);
  4795. result.m[7] = 0;
  4796. result.m[8] = 2.0 * (zx + yw);
  4797. result.m[9] = 2.0 * (yz - xw);
  4798. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4799. result.m[11] = 0;
  4800. result.m[12] = 0;
  4801. result.m[13] = 0;
  4802. result.m[14] = 0;
  4803. result.m[15] = 1.0;
  4804. result._markAsUpdated();
  4805. return this;
  4806. };
  4807. /**
  4808. * Updates the current quaternion from the given rotation matrix values
  4809. * @param matrix defines the source matrix
  4810. * @returns the current updated quaternion
  4811. */
  4812. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4813. Quaternion.FromRotationMatrixToRef(matrix, this);
  4814. return this;
  4815. };
  4816. // Statics
  4817. /**
  4818. * Creates a new quaternion from a rotation matrix
  4819. * @param matrix defines the source matrix
  4820. * @returns a new quaternion created from the given rotation matrix values
  4821. */
  4822. Quaternion.FromRotationMatrix = function (matrix) {
  4823. var result = new Quaternion();
  4824. Quaternion.FromRotationMatrixToRef(matrix, result);
  4825. return result;
  4826. };
  4827. /**
  4828. * Updates the given quaternion with the given rotation matrix values
  4829. * @param matrix defines the source matrix
  4830. * @param result defines the target quaternion
  4831. */
  4832. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4833. var data = matrix.m;
  4834. var m11 = data[0], m12 = data[4], m13 = data[8];
  4835. var m21 = data[1], m22 = data[5], m23 = data[9];
  4836. var m31 = data[2], m32 = data[6], m33 = data[10];
  4837. var trace = m11 + m22 + m33;
  4838. var s;
  4839. if (trace > 0) {
  4840. s = 0.5 / Math.sqrt(trace + 1.0);
  4841. result.w = 0.25 / s;
  4842. result.x = (m32 - m23) * s;
  4843. result.y = (m13 - m31) * s;
  4844. result.z = (m21 - m12) * s;
  4845. }
  4846. else if (m11 > m22 && m11 > m33) {
  4847. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4848. result.w = (m32 - m23) / s;
  4849. result.x = 0.25 * s;
  4850. result.y = (m12 + m21) / s;
  4851. result.z = (m13 + m31) / s;
  4852. }
  4853. else if (m22 > m33) {
  4854. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4855. result.w = (m13 - m31) / s;
  4856. result.x = (m12 + m21) / s;
  4857. result.y = 0.25 * s;
  4858. result.z = (m23 + m32) / s;
  4859. }
  4860. else {
  4861. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4862. result.w = (m21 - m12) / s;
  4863. result.x = (m13 + m31) / s;
  4864. result.y = (m23 + m32) / s;
  4865. result.z = 0.25 * s;
  4866. }
  4867. };
  4868. /**
  4869. * Returns the dot product (float) between the quaternions "left" and "right"
  4870. * @param left defines the left operand
  4871. * @param right defines the right operand
  4872. * @returns the dot product
  4873. */
  4874. Quaternion.Dot = function (left, right) {
  4875. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4876. };
  4877. /**
  4878. * Checks if the two quaternions are close to each other
  4879. * @param quat0 defines the first quaternion to check
  4880. * @param quat1 defines the second quaternion to check
  4881. * @returns true if the two quaternions are close to each other
  4882. */
  4883. Quaternion.AreClose = function (quat0, quat1) {
  4884. var dot = Quaternion.Dot(quat0, quat1);
  4885. return dot >= 0;
  4886. };
  4887. /**
  4888. * Creates an empty quaternion
  4889. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4890. */
  4891. Quaternion.Zero = function () {
  4892. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4893. };
  4894. /**
  4895. * Inverse a given quaternion
  4896. * @param q defines the source quaternion
  4897. * @returns a new quaternion as the inverted current quaternion
  4898. */
  4899. Quaternion.Inverse = function (q) {
  4900. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4901. };
  4902. /**
  4903. * Creates an identity quaternion
  4904. * @returns the identity quaternion
  4905. */
  4906. Quaternion.Identity = function () {
  4907. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4908. };
  4909. /**
  4910. * Gets a boolean indicating if the given quaternion is identity
  4911. * @param quaternion defines the quaternion to check
  4912. * @returns true if the quaternion is identity
  4913. */
  4914. Quaternion.IsIdentity = function (quaternion) {
  4915. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4916. };
  4917. /**
  4918. * Creates a quaternion from a rotation around an axis
  4919. * @param axis defines the axis to use
  4920. * @param angle defines the angle to use
  4921. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4922. */
  4923. Quaternion.RotationAxis = function (axis, angle) {
  4924. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4925. };
  4926. /**
  4927. * Creates a rotation around an axis and stores it into the given quaternion
  4928. * @param axis defines the axis to use
  4929. * @param angle defines the angle to use
  4930. * @param result defines the target quaternion
  4931. * @returns the target quaternion
  4932. */
  4933. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4934. var sin = Math.sin(angle / 2);
  4935. axis.normalize();
  4936. result.w = Math.cos(angle / 2);
  4937. result.x = axis.x * sin;
  4938. result.y = axis.y * sin;
  4939. result.z = axis.z * sin;
  4940. return result;
  4941. };
  4942. /**
  4943. * Creates a new quaternion from data stored into an array
  4944. * @param array defines the data source
  4945. * @param offset defines the offset in the source array where the data starts
  4946. * @returns a new quaternion
  4947. */
  4948. Quaternion.FromArray = function (array, offset) {
  4949. if (!offset) {
  4950. offset = 0;
  4951. }
  4952. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4953. };
  4954. /**
  4955. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4956. * @param yaw defines the rotation around Y axis
  4957. * @param pitch defines the rotation around X axis
  4958. * @param roll defines the rotation around Z axis
  4959. * @returns the new quaternion
  4960. */
  4961. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4962. var q = new Quaternion();
  4963. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4964. return q;
  4965. };
  4966. /**
  4967. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4968. * @param yaw defines the rotation around Y axis
  4969. * @param pitch defines the rotation around X axis
  4970. * @param roll defines the rotation around Z axis
  4971. * @param result defines the target quaternion
  4972. */
  4973. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4974. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4975. var halfRoll = roll * 0.5;
  4976. var halfPitch = pitch * 0.5;
  4977. var halfYaw = yaw * 0.5;
  4978. var sinRoll = Math.sin(halfRoll);
  4979. var cosRoll = Math.cos(halfRoll);
  4980. var sinPitch = Math.sin(halfPitch);
  4981. var cosPitch = Math.cos(halfPitch);
  4982. var sinYaw = Math.sin(halfYaw);
  4983. var cosYaw = Math.cos(halfYaw);
  4984. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4985. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4986. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4987. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4988. };
  4989. /**
  4990. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4991. * @param alpha defines the rotation around first axis
  4992. * @param beta defines the rotation around second axis
  4993. * @param gamma defines the rotation around third axis
  4994. * @returns the new quaternion
  4995. */
  4996. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4997. var result = new Quaternion();
  4998. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4999. return result;
  5000. };
  5001. /**
  5002. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5003. * @param alpha defines the rotation around first axis
  5004. * @param beta defines the rotation around second axis
  5005. * @param gamma defines the rotation around third axis
  5006. * @param result defines the target quaternion
  5007. */
  5008. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5009. // Produces a quaternion from Euler angles in the z-x-z orientation
  5010. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5011. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5012. var halfBeta = beta * 0.5;
  5013. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5014. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5015. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5016. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5017. };
  5018. /**
  5019. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5020. * @param axis1 defines the first axis
  5021. * @param axis2 defines the second axis
  5022. * @param axis3 defines the third axis
  5023. * @returns the new quaternion
  5024. */
  5025. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5026. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5027. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5028. return quat;
  5029. };
  5030. /**
  5031. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5032. * @param axis1 defines the first axis
  5033. * @param axis2 defines the second axis
  5034. * @param axis3 defines the third axis
  5035. * @param ref defines the target quaternion
  5036. */
  5037. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5038. var rotMat = MathTmp.Matrix[0];
  5039. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5040. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5041. };
  5042. /**
  5043. * Interpolates between two quaternions
  5044. * @param left defines first quaternion
  5045. * @param right defines second quaternion
  5046. * @param amount defines the gradient to use
  5047. * @returns the new interpolated quaternion
  5048. */
  5049. Quaternion.Slerp = function (left, right, amount) {
  5050. var result = Quaternion.Identity();
  5051. Quaternion.SlerpToRef(left, right, amount, result);
  5052. return result;
  5053. };
  5054. /**
  5055. * Interpolates between two quaternions and stores it into a target quaternion
  5056. * @param left defines first quaternion
  5057. * @param right defines second quaternion
  5058. * @param amount defines the gradient to use
  5059. * @param result defines the target quaternion
  5060. */
  5061. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5062. var num2;
  5063. var num3;
  5064. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5065. var flag = false;
  5066. if (num4 < 0) {
  5067. flag = true;
  5068. num4 = -num4;
  5069. }
  5070. if (num4 > 0.999999) {
  5071. num3 = 1 - amount;
  5072. num2 = flag ? -amount : amount;
  5073. }
  5074. else {
  5075. var num5 = Math.acos(num4);
  5076. var num6 = (1.0 / Math.sin(num5));
  5077. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5078. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5079. }
  5080. result.x = (num3 * left.x) + (num2 * right.x);
  5081. result.y = (num3 * left.y) + (num2 * right.y);
  5082. result.z = (num3 * left.z) + (num2 * right.z);
  5083. result.w = (num3 * left.w) + (num2 * right.w);
  5084. };
  5085. /**
  5086. * Interpolate between two quaternions using Hermite interpolation
  5087. * @param value1 defines first quaternion
  5088. * @param tangent1 defines the incoming tangent
  5089. * @param value2 defines second quaternion
  5090. * @param tangent2 defines the outgoing tangent
  5091. * @param amount defines the target quaternion
  5092. * @returns the new interpolated quaternion
  5093. */
  5094. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5095. var squared = amount * amount;
  5096. var cubed = amount * squared;
  5097. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5098. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5099. var part3 = (cubed - (2.0 * squared)) + amount;
  5100. var part4 = cubed - squared;
  5101. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5102. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5103. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5104. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5105. return new Quaternion(x, y, z, w);
  5106. };
  5107. return Quaternion;
  5108. }());
  5109. BABYLON.Quaternion = Quaternion;
  5110. /**
  5111. * Class used to store matrix data (4x4)
  5112. */
  5113. var Matrix = /** @class */ (function () {
  5114. /**
  5115. * Creates an empty matrix (filled with zeros)
  5116. */
  5117. function Matrix() {
  5118. this._isIdentity = false;
  5119. this._isIdentityDirty = true;
  5120. /**
  5121. * Gets or sets the internal data of the matrix
  5122. */
  5123. this.m = new Float32Array(16);
  5124. this._markAsUpdated();
  5125. }
  5126. /** @hidden */
  5127. Matrix.prototype._markAsUpdated = function () {
  5128. this.updateFlag = Matrix._updateFlagSeed++;
  5129. this._isIdentityDirty = true;
  5130. };
  5131. // Properties
  5132. /**
  5133. * Check if the current matrix is indentity
  5134. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5135. * @returns true is the matrix is the identity matrix
  5136. */
  5137. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5138. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5139. if (this._isIdentityDirty) {
  5140. this._isIdentityDirty = false;
  5141. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5142. this._isIdentity = false;
  5143. }
  5144. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5145. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5146. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5147. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5148. this._isIdentity = false;
  5149. }
  5150. else {
  5151. this._isIdentity = true;
  5152. }
  5153. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5154. this._isIdentity = false;
  5155. }
  5156. }
  5157. return this._isIdentity;
  5158. };
  5159. /**
  5160. * Gets the determinant of the matrix
  5161. * @returns the matrix determinant
  5162. */
  5163. Matrix.prototype.determinant = function () {
  5164. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5165. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5166. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5167. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5168. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5169. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5170. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5171. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5172. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5173. };
  5174. // Methods
  5175. /**
  5176. * Returns the matrix as a Float32Array
  5177. * @returns the matrix underlying array
  5178. */
  5179. Matrix.prototype.toArray = function () {
  5180. return this.m;
  5181. };
  5182. /**
  5183. * Returns the matrix as a Float32Array
  5184. * @returns the matrix underlying array.
  5185. */
  5186. Matrix.prototype.asArray = function () {
  5187. return this.toArray();
  5188. };
  5189. /**
  5190. * Inverts the current matrix in place
  5191. * @returns the current inverted matrix
  5192. */
  5193. Matrix.prototype.invert = function () {
  5194. this.invertToRef(this);
  5195. return this;
  5196. };
  5197. /**
  5198. * Sets all the matrix elements to zero
  5199. * @returns the current matrix
  5200. */
  5201. Matrix.prototype.reset = function () {
  5202. for (var index = 0; index < 16; index++) {
  5203. this.m[index] = 0.0;
  5204. }
  5205. this._markAsUpdated();
  5206. return this;
  5207. };
  5208. /**
  5209. * Adds the current matrix with a second one
  5210. * @param other defines the matrix to add
  5211. * @returns a new matrix as the addition of the current matrix and the given one
  5212. */
  5213. Matrix.prototype.add = function (other) {
  5214. var result = new Matrix();
  5215. this.addToRef(other, result);
  5216. return result;
  5217. };
  5218. /**
  5219. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5220. * @param other defines the matrix to add
  5221. * @param result defines the target matrix
  5222. * @returns the current matrix
  5223. */
  5224. Matrix.prototype.addToRef = function (other, result) {
  5225. for (var index = 0; index < 16; index++) {
  5226. result.m[index] = this.m[index] + other.m[index];
  5227. }
  5228. result._markAsUpdated();
  5229. return this;
  5230. };
  5231. /**
  5232. * Adds in place the given matrix to the current matrix
  5233. * @param other defines the second operand
  5234. * @returns the current updated matrix
  5235. */
  5236. Matrix.prototype.addToSelf = function (other) {
  5237. for (var index = 0; index < 16; index++) {
  5238. this.m[index] += other.m[index];
  5239. }
  5240. this._markAsUpdated();
  5241. return this;
  5242. };
  5243. /**
  5244. * Sets the given matrix to the current inverted Matrix
  5245. * @param other defines the target matrix
  5246. * @returns the unmodified current matrix
  5247. */
  5248. Matrix.prototype.invertToRef = function (other) {
  5249. var l1 = this.m[0];
  5250. var l2 = this.m[1];
  5251. var l3 = this.m[2];
  5252. var l4 = this.m[3];
  5253. var l5 = this.m[4];
  5254. var l6 = this.m[5];
  5255. var l7 = this.m[6];
  5256. var l8 = this.m[7];
  5257. var l9 = this.m[8];
  5258. var l10 = this.m[9];
  5259. var l11 = this.m[10];
  5260. var l12 = this.m[11];
  5261. var l13 = this.m[12];
  5262. var l14 = this.m[13];
  5263. var l15 = this.m[14];
  5264. var l16 = this.m[15];
  5265. var l17 = (l11 * l16) - (l12 * l15);
  5266. var l18 = (l10 * l16) - (l12 * l14);
  5267. var l19 = (l10 * l15) - (l11 * l14);
  5268. var l20 = (l9 * l16) - (l12 * l13);
  5269. var l21 = (l9 * l15) - (l11 * l13);
  5270. var l22 = (l9 * l14) - (l10 * l13);
  5271. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5272. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5273. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5274. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5275. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5276. var l28 = (l7 * l16) - (l8 * l15);
  5277. var l29 = (l6 * l16) - (l8 * l14);
  5278. var l30 = (l6 * l15) - (l7 * l14);
  5279. var l31 = (l5 * l16) - (l8 * l13);
  5280. var l32 = (l5 * l15) - (l7 * l13);
  5281. var l33 = (l5 * l14) - (l6 * l13);
  5282. var l34 = (l7 * l12) - (l8 * l11);
  5283. var l35 = (l6 * l12) - (l8 * l10);
  5284. var l36 = (l6 * l11) - (l7 * l10);
  5285. var l37 = (l5 * l12) - (l8 * l9);
  5286. var l38 = (l5 * l11) - (l7 * l9);
  5287. var l39 = (l5 * l10) - (l6 * l9);
  5288. other.m[0] = l23 * l27;
  5289. other.m[4] = l24 * l27;
  5290. other.m[8] = l25 * l27;
  5291. other.m[12] = l26 * l27;
  5292. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5293. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5294. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5295. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5296. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5297. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5298. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5299. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5300. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5301. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5302. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5303. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5304. other._markAsUpdated();
  5305. return this;
  5306. };
  5307. /**
  5308. * Inserts the translation vector (using 3 floats) in the current matrix
  5309. * @param x defines the 1st component of the translation
  5310. * @param y defines the 2nd component of the translation
  5311. * @param z defines the 3rd component of the translation
  5312. * @returns the current updated matrix
  5313. */
  5314. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5315. this.m[12] = x;
  5316. this.m[13] = y;
  5317. this.m[14] = z;
  5318. this._markAsUpdated();
  5319. return this;
  5320. };
  5321. /**
  5322. * Inserts the translation vector in the current matrix
  5323. * @param vector3 defines the translation to insert
  5324. * @returns the current updated matrix
  5325. */
  5326. Matrix.prototype.setTranslation = function (vector3) {
  5327. this.m[12] = vector3.x;
  5328. this.m[13] = vector3.y;
  5329. this.m[14] = vector3.z;
  5330. this._markAsUpdated();
  5331. return this;
  5332. };
  5333. /**
  5334. * Gets the translation value of the current matrix
  5335. * @returns a new Vector3 as the extracted translation from the matrix
  5336. */
  5337. Matrix.prototype.getTranslation = function () {
  5338. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5339. };
  5340. /**
  5341. * Fill a Vector3 with the extracted translation from the matrix
  5342. * @param result defines the Vector3 where to store the translation
  5343. * @returns the current matrix
  5344. */
  5345. Matrix.prototype.getTranslationToRef = function (result) {
  5346. result.x = this.m[12];
  5347. result.y = this.m[13];
  5348. result.z = this.m[14];
  5349. return this;
  5350. };
  5351. /**
  5352. * Remove rotation and scaling part from the matrix
  5353. * @returns the updated matrix
  5354. */
  5355. Matrix.prototype.removeRotationAndScaling = function () {
  5356. this.setRowFromFloats(0, 1, 0, 0, 0);
  5357. this.setRowFromFloats(1, 0, 1, 0, 0);
  5358. this.setRowFromFloats(2, 0, 0, 1, 0);
  5359. return this;
  5360. };
  5361. /**
  5362. * Multiply two matrices
  5363. * @param other defines the second operand
  5364. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5365. */
  5366. Matrix.prototype.multiply = function (other) {
  5367. var result = new Matrix();
  5368. this.multiplyToRef(other, result);
  5369. return result;
  5370. };
  5371. /**
  5372. * Copy the current matrix from the given one
  5373. * @param other defines the source matrix
  5374. * @returns the current updated matrix
  5375. */
  5376. Matrix.prototype.copyFrom = function (other) {
  5377. for (var index = 0; index < 16; index++) {
  5378. this.m[index] = other.m[index];
  5379. }
  5380. this._markAsUpdated();
  5381. return this;
  5382. };
  5383. /**
  5384. * Populates the given array from the starting index with the current matrix values
  5385. * @param array defines the target array
  5386. * @param offset defines the offset in the target array where to start storing values
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.copyToArray = function (array, offset) {
  5390. if (offset === void 0) { offset = 0; }
  5391. for (var index = 0; index < 16; index++) {
  5392. array[offset + index] = this.m[index];
  5393. }
  5394. return this;
  5395. };
  5396. /**
  5397. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5398. * @param other defines the second operand
  5399. * @param result defines the matrix where to store the multiplication
  5400. * @returns the current matrix
  5401. */
  5402. Matrix.prototype.multiplyToRef = function (other, result) {
  5403. this.multiplyToArray(other, result.m, 0);
  5404. result._markAsUpdated();
  5405. return this;
  5406. };
  5407. /**
  5408. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5409. * @param other defines the second operand
  5410. * @param result defines the array where to store the multiplication
  5411. * @param offset defines the offset in the target array where to start storing values
  5412. * @returns the current matrix
  5413. */
  5414. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5415. var tm0 = this.m[0];
  5416. var tm1 = this.m[1];
  5417. var tm2 = this.m[2];
  5418. var tm3 = this.m[3];
  5419. var tm4 = this.m[4];
  5420. var tm5 = this.m[5];
  5421. var tm6 = this.m[6];
  5422. var tm7 = this.m[7];
  5423. var tm8 = this.m[8];
  5424. var tm9 = this.m[9];
  5425. var tm10 = this.m[10];
  5426. var tm11 = this.m[11];
  5427. var tm12 = this.m[12];
  5428. var tm13 = this.m[13];
  5429. var tm14 = this.m[14];
  5430. var tm15 = this.m[15];
  5431. var om0 = other.m[0];
  5432. var om1 = other.m[1];
  5433. var om2 = other.m[2];
  5434. var om3 = other.m[3];
  5435. var om4 = other.m[4];
  5436. var om5 = other.m[5];
  5437. var om6 = other.m[6];
  5438. var om7 = other.m[7];
  5439. var om8 = other.m[8];
  5440. var om9 = other.m[9];
  5441. var om10 = other.m[10];
  5442. var om11 = other.m[11];
  5443. var om12 = other.m[12];
  5444. var om13 = other.m[13];
  5445. var om14 = other.m[14];
  5446. var om15 = other.m[15];
  5447. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5448. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5449. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5450. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5451. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5452. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5453. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5454. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5455. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5456. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5457. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5458. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5459. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5460. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5461. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5462. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5463. return this;
  5464. };
  5465. /**
  5466. * Check equality between this matrix and a second one
  5467. * @param value defines the second matrix to compare
  5468. * @returns true is the current matrix and the given one values are strictly equal
  5469. */
  5470. Matrix.prototype.equals = function (value) {
  5471. return value &&
  5472. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5473. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5474. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5475. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5476. };
  5477. /**
  5478. * Clone the current matrix
  5479. * @returns a new matrix from the current matrix
  5480. */
  5481. Matrix.prototype.clone = function () {
  5482. 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]);
  5483. };
  5484. /**
  5485. * Returns the name of the current matrix class
  5486. * @returns the string "Matrix"
  5487. */
  5488. Matrix.prototype.getClassName = function () {
  5489. return "Matrix";
  5490. };
  5491. /**
  5492. * Gets the hash code of the current matrix
  5493. * @returns the hash code
  5494. */
  5495. Matrix.prototype.getHashCode = function () {
  5496. var hash = this.m[0] || 0;
  5497. for (var i = 1; i < 16; i++) {
  5498. hash = (hash * 397) ^ (this.m[i] || 0);
  5499. }
  5500. return hash;
  5501. };
  5502. /**
  5503. * Decomposes the current Matrix into a translation, rotation and scaling components
  5504. * @param scale defines the scale vector3 given as a reference to update
  5505. * @param rotation defines the rotation quaternion given as a reference to update
  5506. * @param translation defines the translation vector3 given as a reference to update
  5507. * @returns true if operation was successful
  5508. */
  5509. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5510. if (translation) {
  5511. translation.x = this.m[12];
  5512. translation.y = this.m[13];
  5513. translation.z = this.m[14];
  5514. }
  5515. scale = scale || MathTmp.Vector3[0];
  5516. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5517. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5518. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5519. if (this.determinant() <= 0) {
  5520. scale.y *= -1;
  5521. }
  5522. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5523. if (rotation) {
  5524. rotation.x = 0;
  5525. rotation.y = 0;
  5526. rotation.z = 0;
  5527. rotation.w = 1;
  5528. }
  5529. return false;
  5530. }
  5531. if (rotation) {
  5532. 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]);
  5533. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5534. }
  5535. return true;
  5536. };
  5537. /**
  5538. * Gets specific row of the matrix
  5539. * @param index defines the number of the row to get
  5540. * @returns the index-th row of the current matrix as a new Vector4
  5541. */
  5542. Matrix.prototype.getRow = function (index) {
  5543. if (index < 0 || index > 3) {
  5544. return null;
  5545. }
  5546. var i = index * 4;
  5547. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5548. };
  5549. /**
  5550. * Sets the index-th row of the current matrix to the vector4 values
  5551. * @param index defines the number of the row to set
  5552. * @param row defines the target vector4
  5553. * @returns the updated current matrix
  5554. */
  5555. Matrix.prototype.setRow = function (index, row) {
  5556. if (index < 0 || index > 3) {
  5557. return this;
  5558. }
  5559. var i = index * 4;
  5560. this.m[i + 0] = row.x;
  5561. this.m[i + 1] = row.y;
  5562. this.m[i + 2] = row.z;
  5563. this.m[i + 3] = row.w;
  5564. this._markAsUpdated();
  5565. return this;
  5566. };
  5567. /**
  5568. * Compute the transpose of the matrix
  5569. * @returns the new transposed matrix
  5570. */
  5571. Matrix.prototype.transpose = function () {
  5572. return Matrix.Transpose(this);
  5573. };
  5574. /**
  5575. * Compute the transpose of the matrix and store it in a given matrix
  5576. * @param result defines the target matrix
  5577. * @returns the current matrix
  5578. */
  5579. Matrix.prototype.transposeToRef = function (result) {
  5580. Matrix.TransposeToRef(this, result);
  5581. return this;
  5582. };
  5583. /**
  5584. * Sets the index-th row of the current matrix with the given 4 x float values
  5585. * @param index defines the row index
  5586. * @param x defines the x component to set
  5587. * @param y defines the y component to set
  5588. * @param z defines the z component to set
  5589. * @param w defines the w component to set
  5590. * @returns the updated current matrix
  5591. */
  5592. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5593. if (index < 0 || index > 3) {
  5594. return this;
  5595. }
  5596. var i = index * 4;
  5597. this.m[i + 0] = x;
  5598. this.m[i + 1] = y;
  5599. this.m[i + 2] = z;
  5600. this.m[i + 3] = w;
  5601. this._markAsUpdated();
  5602. return this;
  5603. };
  5604. /**
  5605. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5606. * @param scale defines the scale factor
  5607. * @returns a new matrix
  5608. */
  5609. Matrix.prototype.scale = function (scale) {
  5610. var result = new Matrix();
  5611. this.scaleToRef(scale, result);
  5612. return result;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor to a given result matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] = this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Scale the current matrix values by a factor and add the result to a given matrix
  5629. * @param scale defines the scale factor
  5630. * @param result defines the Matrix to store the result
  5631. * @returns the current matrix
  5632. */
  5633. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5634. for (var index = 0; index < 16; index++) {
  5635. result.m[index] += this.m[index] * scale;
  5636. }
  5637. result._markAsUpdated();
  5638. return this;
  5639. };
  5640. /**
  5641. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5642. * @param ref matrix to store the result
  5643. */
  5644. Matrix.prototype.toNormalMatrix = function (ref) {
  5645. this.invertToRef(ref);
  5646. ref.transpose();
  5647. var m = ref.m;
  5648. 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);
  5649. };
  5650. /**
  5651. * Gets only rotation part of the current matrix
  5652. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5653. */
  5654. Matrix.prototype.getRotationMatrix = function () {
  5655. var result = Matrix.Identity();
  5656. this.getRotationMatrixToRef(result);
  5657. return result;
  5658. };
  5659. /**
  5660. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5661. * @param result defines the target matrix to store data to
  5662. * @returns the current matrix
  5663. */
  5664. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5665. var m = this.m;
  5666. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5667. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5668. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5669. if (this.determinant() <= 0) {
  5670. sy *= -1;
  5671. }
  5672. if (sx === 0 || sy === 0 || sz === 0) {
  5673. Matrix.IdentityToRef(result);
  5674. }
  5675. else {
  5676. 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);
  5677. }
  5678. return this;
  5679. };
  5680. // Statics
  5681. /**
  5682. * Creates a matrix from an array
  5683. * @param array defines the source array
  5684. * @param offset defines an offset in the source array
  5685. * @returns a new Matrix set from the starting index of the given array
  5686. */
  5687. Matrix.FromArray = function (array, offset) {
  5688. var result = new Matrix();
  5689. if (!offset) {
  5690. offset = 0;
  5691. }
  5692. Matrix.FromArrayToRef(array, offset, result);
  5693. return result;
  5694. };
  5695. /**
  5696. * Copy the content of an array into a given matrix
  5697. * @param array defines the source array
  5698. * @param offset defines an offset in the source array
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromArrayToRef = function (array, offset, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset];
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores an array into a matrix after having multiplied each component by a given factor
  5709. * @param array defines the source array
  5710. * @param offset defines the offset in the source array
  5711. * @param scale defines the scaling factor
  5712. * @param result defines the target matrix
  5713. */
  5714. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5715. for (var index = 0; index < 16; index++) {
  5716. result.m[index] = array[index + offset] * scale;
  5717. }
  5718. result._markAsUpdated();
  5719. };
  5720. /**
  5721. * Stores a list of values (16) inside a given matrix
  5722. * @param initialM11 defines 1st value of 1st row
  5723. * @param initialM12 defines 2nd value of 1st row
  5724. * @param initialM13 defines 3rd value of 1st row
  5725. * @param initialM14 defines 4th value of 1st row
  5726. * @param initialM21 defines 1st value of 2nd row
  5727. * @param initialM22 defines 2nd value of 2nd row
  5728. * @param initialM23 defines 3rd value of 2nd row
  5729. * @param initialM24 defines 4th value of 2nd row
  5730. * @param initialM31 defines 1st value of 3rd row
  5731. * @param initialM32 defines 2nd value of 3rd row
  5732. * @param initialM33 defines 3rd value of 3rd row
  5733. * @param initialM34 defines 4th value of 3rd row
  5734. * @param initialM41 defines 1st value of 4th row
  5735. * @param initialM42 defines 2nd value of 4th row
  5736. * @param initialM43 defines 3rd value of 4th row
  5737. * @param initialM44 defines 4th value of 4th row
  5738. * @param result defines the target matrix
  5739. */
  5740. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5741. result.m[0] = initialM11;
  5742. result.m[1] = initialM12;
  5743. result.m[2] = initialM13;
  5744. result.m[3] = initialM14;
  5745. result.m[4] = initialM21;
  5746. result.m[5] = initialM22;
  5747. result.m[6] = initialM23;
  5748. result.m[7] = initialM24;
  5749. result.m[8] = initialM31;
  5750. result.m[9] = initialM32;
  5751. result.m[10] = initialM33;
  5752. result.m[11] = initialM34;
  5753. result.m[12] = initialM41;
  5754. result.m[13] = initialM42;
  5755. result.m[14] = initialM43;
  5756. result.m[15] = initialM44;
  5757. result._markAsUpdated();
  5758. };
  5759. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5760. /**
  5761. * Gets an identity matrix that must not be updated
  5762. */
  5763. get: function () {
  5764. return Matrix._identityReadOnly;
  5765. },
  5766. enumerable: true,
  5767. configurable: true
  5768. });
  5769. /**
  5770. * Creates new matrix from a list of values (16)
  5771. * @param initialM11 defines 1st value of 1st row
  5772. * @param initialM12 defines 2nd value of 1st row
  5773. * @param initialM13 defines 3rd value of 1st row
  5774. * @param initialM14 defines 4th value of 1st row
  5775. * @param initialM21 defines 1st value of 2nd row
  5776. * @param initialM22 defines 2nd value of 2nd row
  5777. * @param initialM23 defines 3rd value of 2nd row
  5778. * @param initialM24 defines 4th value of 2nd row
  5779. * @param initialM31 defines 1st value of 3rd row
  5780. * @param initialM32 defines 2nd value of 3rd row
  5781. * @param initialM33 defines 3rd value of 3rd row
  5782. * @param initialM34 defines 4th value of 3rd row
  5783. * @param initialM41 defines 1st value of 4th row
  5784. * @param initialM42 defines 2nd value of 4th row
  5785. * @param initialM43 defines 3rd value of 4th row
  5786. * @param initialM44 defines 4th value of 4th row
  5787. * @returns the new matrix
  5788. */
  5789. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5790. var result = new Matrix();
  5791. result.m[0] = initialM11;
  5792. result.m[1] = initialM12;
  5793. result.m[2] = initialM13;
  5794. result.m[3] = initialM14;
  5795. result.m[4] = initialM21;
  5796. result.m[5] = initialM22;
  5797. result.m[6] = initialM23;
  5798. result.m[7] = initialM24;
  5799. result.m[8] = initialM31;
  5800. result.m[9] = initialM32;
  5801. result.m[10] = initialM33;
  5802. result.m[11] = initialM34;
  5803. result.m[12] = initialM41;
  5804. result.m[13] = initialM42;
  5805. result.m[14] = initialM43;
  5806. result.m[15] = initialM44;
  5807. return result;
  5808. };
  5809. /**
  5810. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5811. * @param scale defines the scale vector3
  5812. * @param rotation defines the rotation quaternion
  5813. * @param translation defines the translation vector3
  5814. * @returns a new matrix
  5815. */
  5816. Matrix.Compose = function (scale, rotation, translation) {
  5817. var result = Matrix.Identity();
  5818. Matrix.ComposeToRef(scale, rotation, translation, result);
  5819. return result;
  5820. };
  5821. /**
  5822. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5823. * @param scale defines the scale vector3
  5824. * @param rotation defines the rotation quaternion
  5825. * @param translation defines the translation vector3
  5826. * @param result defines the target matrix
  5827. */
  5828. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5829. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5830. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5831. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5832. result.setTranslation(translation);
  5833. };
  5834. /**
  5835. * Creates a new identity matrix
  5836. * @returns a new identity matrix
  5837. */
  5838. Matrix.Identity = function () {
  5839. 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);
  5840. };
  5841. /**
  5842. * Creates a new identity matrix and stores the result in a given matrix
  5843. * @param result defines the target matrix
  5844. */
  5845. Matrix.IdentityToRef = function (result) {
  5846. 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);
  5847. };
  5848. /**
  5849. * Creates a new zero matrix
  5850. * @returns a new zero matrix
  5851. */
  5852. Matrix.Zero = function () {
  5853. 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);
  5854. };
  5855. /**
  5856. * Creates a new rotation matrix for "angle" radians around the X axis
  5857. * @param angle defines the angle (in radians) to use
  5858. * @return the new matrix
  5859. */
  5860. Matrix.RotationX = function (angle) {
  5861. var result = new Matrix();
  5862. Matrix.RotationXToRef(angle, result);
  5863. return result;
  5864. };
  5865. /**
  5866. * Creates a new matrix as the invert of a given matrix
  5867. * @param source defines the source matrix
  5868. * @returns the new matrix
  5869. */
  5870. Matrix.Invert = function (source) {
  5871. var result = new Matrix();
  5872. source.invertToRef(result);
  5873. return result;
  5874. };
  5875. /**
  5876. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5877. * @param angle defines the angle (in radians) to use
  5878. * @param result defines the target matrix
  5879. */
  5880. Matrix.RotationXToRef = function (angle, result) {
  5881. var s = Math.sin(angle);
  5882. var c = Math.cos(angle);
  5883. result.m[0] = 1.0;
  5884. result.m[15] = 1.0;
  5885. result.m[5] = c;
  5886. result.m[10] = c;
  5887. result.m[9] = -s;
  5888. result.m[6] = s;
  5889. result.m[1] = 0.0;
  5890. result.m[2] = 0.0;
  5891. result.m[3] = 0.0;
  5892. result.m[4] = 0.0;
  5893. result.m[7] = 0.0;
  5894. result.m[8] = 0.0;
  5895. result.m[11] = 0.0;
  5896. result.m[12] = 0.0;
  5897. result.m[13] = 0.0;
  5898. result.m[14] = 0.0;
  5899. result._markAsUpdated();
  5900. };
  5901. /**
  5902. * Creates a new rotation matrix for "angle" radians around the Y axis
  5903. * @param angle defines the angle (in radians) to use
  5904. * @return the new matrix
  5905. */
  5906. Matrix.RotationY = function (angle) {
  5907. var result = new Matrix();
  5908. Matrix.RotationYToRef(angle, result);
  5909. return result;
  5910. };
  5911. /**
  5912. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5913. * @param angle defines the angle (in radians) to use
  5914. * @param result defines the target matrix
  5915. */
  5916. Matrix.RotationYToRef = function (angle, result) {
  5917. var s = Math.sin(angle);
  5918. var c = Math.cos(angle);
  5919. result.m[5] = 1.0;
  5920. result.m[15] = 1.0;
  5921. result.m[0] = c;
  5922. result.m[2] = -s;
  5923. result.m[8] = s;
  5924. result.m[10] = c;
  5925. result.m[1] = 0.0;
  5926. result.m[3] = 0.0;
  5927. result.m[4] = 0.0;
  5928. result.m[6] = 0.0;
  5929. result.m[7] = 0.0;
  5930. result.m[9] = 0.0;
  5931. result.m[11] = 0.0;
  5932. result.m[12] = 0.0;
  5933. result.m[13] = 0.0;
  5934. result.m[14] = 0.0;
  5935. result._markAsUpdated();
  5936. };
  5937. /**
  5938. * Creates a new rotation matrix for "angle" radians around the Z axis
  5939. * @param angle defines the angle (in radians) to use
  5940. * @return the new matrix
  5941. */
  5942. Matrix.RotationZ = function (angle) {
  5943. var result = new Matrix();
  5944. Matrix.RotationZToRef(angle, result);
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5949. * @param angle defines the angle (in radians) to use
  5950. * @param result defines the target matrix
  5951. */
  5952. Matrix.RotationZToRef = function (angle, result) {
  5953. var s = Math.sin(angle);
  5954. var c = Math.cos(angle);
  5955. result.m[10] = 1.0;
  5956. result.m[15] = 1.0;
  5957. result.m[0] = c;
  5958. result.m[1] = s;
  5959. result.m[4] = -s;
  5960. result.m[5] = c;
  5961. result.m[2] = 0.0;
  5962. result.m[3] = 0.0;
  5963. result.m[6] = 0.0;
  5964. result.m[7] = 0.0;
  5965. result.m[8] = 0.0;
  5966. result.m[9] = 0.0;
  5967. result.m[11] = 0.0;
  5968. result.m[12] = 0.0;
  5969. result.m[13] = 0.0;
  5970. result.m[14] = 0.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Creates a new rotation matrix for "angle" radians around the given axis
  5975. * @param axis defines the axis to use
  5976. * @param angle defines the angle (in radians) to use
  5977. * @return the new matrix
  5978. */
  5979. Matrix.RotationAxis = function (axis, angle) {
  5980. var result = Matrix.Zero();
  5981. Matrix.RotationAxisToRef(axis, angle, result);
  5982. return result;
  5983. };
  5984. /**
  5985. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5986. * @param axis defines the axis to use
  5987. * @param angle defines the angle (in radians) to use
  5988. * @param result defines the target matrix
  5989. */
  5990. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5991. var s = Math.sin(-angle);
  5992. var c = Math.cos(-angle);
  5993. var c1 = 1 - c;
  5994. axis.normalize();
  5995. result.m[0] = (axis.x * axis.x) * c1 + c;
  5996. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5997. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5998. result.m[3] = 0.0;
  5999. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6000. result.m[5] = (axis.y * axis.y) * c1 + c;
  6001. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6002. result.m[7] = 0.0;
  6003. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6004. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6005. result.m[10] = (axis.z * axis.z) * c1 + c;
  6006. result.m[11] = 0.0;
  6007. result.m[15] = 1.0;
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Creates a rotation matrix
  6012. * @param yaw defines the yaw angle in radians (Y axis)
  6013. * @param pitch defines the pitch angle in radians (X axis)
  6014. * @param roll defines the roll angle in radians (X axis)
  6015. * @returns the new rotation matrix
  6016. */
  6017. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6018. var result = new Matrix();
  6019. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6020. return result;
  6021. };
  6022. /**
  6023. * Creates a rotation matrix and stores it in a given matrix
  6024. * @param yaw defines the yaw angle in radians (Y axis)
  6025. * @param pitch defines the pitch angle in radians (X axis)
  6026. * @param roll defines the roll angle in radians (X axis)
  6027. * @param result defines the target matrix
  6028. */
  6029. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6030. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6031. this._tempQuaternion.toRotationMatrix(result);
  6032. };
  6033. /**
  6034. * Creates a scaling matrix
  6035. * @param x defines the scale factor on X axis
  6036. * @param y defines the scale factor on Y axis
  6037. * @param z defines the scale factor on Z axis
  6038. * @returns the new matrix
  6039. */
  6040. Matrix.Scaling = function (x, y, z) {
  6041. var result = Matrix.Zero();
  6042. Matrix.ScalingToRef(x, y, z, result);
  6043. return result;
  6044. };
  6045. /**
  6046. * Creates a scaling matrix and stores it in a given matrix
  6047. * @param x defines the scale factor on X axis
  6048. * @param y defines the scale factor on Y axis
  6049. * @param z defines the scale factor on Z axis
  6050. * @param result defines the target matrix
  6051. */
  6052. Matrix.ScalingToRef = function (x, y, z, result) {
  6053. result.m[0] = x;
  6054. result.m[1] = 0.0;
  6055. result.m[2] = 0.0;
  6056. result.m[3] = 0.0;
  6057. result.m[4] = 0.0;
  6058. result.m[5] = y;
  6059. result.m[6] = 0.0;
  6060. result.m[7] = 0.0;
  6061. result.m[8] = 0.0;
  6062. result.m[9] = 0.0;
  6063. result.m[10] = z;
  6064. result.m[11] = 0.0;
  6065. result.m[12] = 0.0;
  6066. result.m[13] = 0.0;
  6067. result.m[14] = 0.0;
  6068. result.m[15] = 1.0;
  6069. result._markAsUpdated();
  6070. };
  6071. /**
  6072. * Creates a translation matrix
  6073. * @param x defines the translation on X axis
  6074. * @param y defines the translation on Y axis
  6075. * @param z defines the translationon Z axis
  6076. * @returns the new matrix
  6077. */
  6078. Matrix.Translation = function (x, y, z) {
  6079. var result = Matrix.Identity();
  6080. Matrix.TranslationToRef(x, y, z, result);
  6081. return result;
  6082. };
  6083. /**
  6084. * Creates a translation matrix and stores it in a given matrix
  6085. * @param x defines the translation on X axis
  6086. * @param y defines the translation on Y axis
  6087. * @param z defines the translationon Z axis
  6088. * @param result defines the target matrix
  6089. */
  6090. Matrix.TranslationToRef = function (x, y, z, result) {
  6091. 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);
  6092. };
  6093. /**
  6094. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6095. * @param startValue defines the start value
  6096. * @param endValue defines the end value
  6097. * @param gradient defines the gradient factor
  6098. * @returns the new matrix
  6099. */
  6100. Matrix.Lerp = function (startValue, endValue, gradient) {
  6101. var result = Matrix.Zero();
  6102. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6103. return result;
  6104. };
  6105. /**
  6106. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6107. * @param startValue defines the start value
  6108. * @param endValue defines the end value
  6109. * @param gradient defines the gradient factor
  6110. * @param result defines the Matrix object where to store data
  6111. */
  6112. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6113. for (var index = 0; index < 16; index++) {
  6114. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6115. }
  6116. result._markAsUpdated();
  6117. };
  6118. /**
  6119. * Builds a new matrix whose values are computed by:
  6120. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6121. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6122. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6123. * @param startValue defines the first matrix
  6124. * @param endValue defines the second matrix
  6125. * @param gradient defines the gradient between the two matrices
  6126. * @returns the new matrix
  6127. */
  6128. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6129. var result = Matrix.Zero();
  6130. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6131. return result;
  6132. };
  6133. /**
  6134. * Update a matrix to values which are computed by:
  6135. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6136. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6137. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6138. * @param startValue defines the first matrix
  6139. * @param endValue defines the second matrix
  6140. * @param gradient defines the gradient between the two matrices
  6141. * @param result defines the target matrix
  6142. */
  6143. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6144. var startScale = MathTmp.Vector3[0];
  6145. var startRotation = MathTmp.Quaternion[0];
  6146. var startTranslation = MathTmp.Vector3[1];
  6147. startValue.decompose(startScale, startRotation, startTranslation);
  6148. var endScale = MathTmp.Vector3[2];
  6149. var endRotation = MathTmp.Quaternion[1];
  6150. var endTranslation = MathTmp.Vector3[3];
  6151. endValue.decompose(endScale, endRotation, endTranslation);
  6152. var resultScale = MathTmp.Vector3[4];
  6153. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6154. var resultRotation = MathTmp.Quaternion[2];
  6155. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6156. var resultTranslation = MathTmp.Vector3[5];
  6157. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6158. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6159. };
  6160. /**
  6161. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @returns the new matrix
  6167. */
  6168. Matrix.LookAtLH = function (eye, target, up) {
  6169. var result = Matrix.Zero();
  6170. Matrix.LookAtLHToRef(eye, target, up, result);
  6171. return result;
  6172. };
  6173. /**
  6174. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6175. * This function works in left handed mode
  6176. * @param eye defines the final position of the entity
  6177. * @param target defines where the entity should look at
  6178. * @param up defines the up vector for the entity
  6179. * @param result defines the target matrix
  6180. */
  6181. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6182. // Z axis
  6183. target.subtractToRef(eye, this._zAxis);
  6184. this._zAxis.normalize();
  6185. // X axis
  6186. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6187. if (this._xAxis.lengthSquared() === 0) {
  6188. this._xAxis.x = 1.0;
  6189. }
  6190. else {
  6191. this._xAxis.normalize();
  6192. }
  6193. // Y axis
  6194. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6195. this._yAxis.normalize();
  6196. // Eye angles
  6197. var ex = -Vector3.Dot(this._xAxis, eye);
  6198. var ey = -Vector3.Dot(this._yAxis, eye);
  6199. var ez = -Vector3.Dot(this._zAxis, eye);
  6200. 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);
  6201. };
  6202. /**
  6203. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @returns the new matrix
  6209. */
  6210. Matrix.LookAtRH = function (eye, target, up) {
  6211. var result = Matrix.Zero();
  6212. Matrix.LookAtRHToRef(eye, target, up, result);
  6213. return result;
  6214. };
  6215. /**
  6216. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6217. * This function works in right handed mode
  6218. * @param eye defines the final position of the entity
  6219. * @param target defines where the entity should look at
  6220. * @param up defines the up vector for the entity
  6221. * @param result defines the target matrix
  6222. */
  6223. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6224. // Z axis
  6225. eye.subtractToRef(target, this._zAxis);
  6226. this._zAxis.normalize();
  6227. // X axis
  6228. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6229. if (this._xAxis.lengthSquared() === 0) {
  6230. this._xAxis.x = 1.0;
  6231. }
  6232. else {
  6233. this._xAxis.normalize();
  6234. }
  6235. // Y axis
  6236. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6237. this._yAxis.normalize();
  6238. // Eye angles
  6239. var ex = -Vector3.Dot(this._xAxis, eye);
  6240. var ey = -Vector3.Dot(this._yAxis, eye);
  6241. var ez = -Vector3.Dot(this._zAxis, eye);
  6242. 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);
  6243. };
  6244. /**
  6245. * Create a left-handed orthographic projection matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @returns a new matrix as a left-handed orthographic projection matrix
  6251. */
  6252. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6253. var matrix = Matrix.Zero();
  6254. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6255. return matrix;
  6256. };
  6257. /**
  6258. * Store a left-handed orthographic projection to a given matrix
  6259. * @param width defines the viewport width
  6260. * @param height defines the viewport height
  6261. * @param znear defines the near clip plane
  6262. * @param zfar defines the far clip plane
  6263. * @param result defines the target matrix
  6264. */
  6265. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6266. var n = znear;
  6267. var f = zfar;
  6268. var a = 2.0 / width;
  6269. var b = 2.0 / height;
  6270. var c = 2.0 / (f - n);
  6271. var d = -(f + n) / (f - n);
  6272. 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);
  6273. };
  6274. /**
  6275. * Create a left-handed orthographic projection matrix
  6276. * @param left defines the viewport left coordinate
  6277. * @param right defines the viewport right coordinate
  6278. * @param bottom defines the viewport bottom coordinate
  6279. * @param top defines the viewport top coordinate
  6280. * @param znear defines the near clip plane
  6281. * @param zfar defines the far clip plane
  6282. * @returns a new matrix as a left-handed orthographic projection matrix
  6283. */
  6284. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6285. var matrix = Matrix.Zero();
  6286. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6287. return matrix;
  6288. };
  6289. /**
  6290. * Stores a left-handed orthographic projection into a given matrix
  6291. * @param left defines the viewport left coordinate
  6292. * @param right defines the viewport right coordinate
  6293. * @param bottom defines the viewport bottom coordinate
  6294. * @param top defines the viewport top coordinate
  6295. * @param znear defines the near clip plane
  6296. * @param zfar defines the far clip plane
  6297. * @param result defines the target matrix
  6298. */
  6299. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6300. var n = znear;
  6301. var f = zfar;
  6302. var a = 2.0 / (right - left);
  6303. var b = 2.0 / (top - bottom);
  6304. var c = 2.0 / (f - n);
  6305. var d = -(f + n) / (f - n);
  6306. var i0 = (left + right) / (left - right);
  6307. var i1 = (top + bottom) / (bottom - top);
  6308. 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);
  6309. };
  6310. /**
  6311. * Creates a right-handed orthographic projection matrix
  6312. * @param left defines the viewport left coordinate
  6313. * @param right defines the viewport right coordinate
  6314. * @param bottom defines the viewport bottom coordinate
  6315. * @param top defines the viewport top coordinate
  6316. * @param znear defines the near clip plane
  6317. * @param zfar defines the far clip plane
  6318. * @returns a new matrix as a right-handed orthographic projection matrix
  6319. */
  6320. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6321. var matrix = Matrix.Zero();
  6322. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6323. return matrix;
  6324. };
  6325. /**
  6326. * Stores a right-handed orthographic projection into a given matrix
  6327. * @param left defines the viewport left coordinate
  6328. * @param right defines the viewport right coordinate
  6329. * @param bottom defines the viewport bottom coordinate
  6330. * @param top defines the viewport top coordinate
  6331. * @param znear defines the near clip plane
  6332. * @param zfar defines the far clip plane
  6333. * @param result defines the target matrix
  6334. */
  6335. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6336. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6337. result.m[10] *= -1.0;
  6338. };
  6339. /**
  6340. * Creates a left-handed perspective projection matrix
  6341. * @param width defines the viewport width
  6342. * @param height defines the viewport height
  6343. * @param znear defines the near clip plane
  6344. * @param zfar defines the far clip plane
  6345. * @returns a new matrix as a left-handed perspective projection matrix
  6346. */
  6347. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6348. var matrix = Matrix.Zero();
  6349. var n = znear;
  6350. var f = zfar;
  6351. var a = 2.0 * n / width;
  6352. var b = 2.0 * n / height;
  6353. var c = (f + n) / (f - n);
  6354. var d = -2.0 * f * n / (f - n);
  6355. 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);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Creates a left-handed perspective projection matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @returns a new matrix as a left-handed perspective projection matrix
  6365. */
  6366. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6367. var matrix = Matrix.Zero();
  6368. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6369. return matrix;
  6370. };
  6371. /**
  6372. * Stores a left-handed perspective projection into a given matrix
  6373. * @param fov defines the horizontal field of view
  6374. * @param aspect defines the aspect ratio
  6375. * @param znear defines the near clip plane
  6376. * @param zfar defines the far clip plane
  6377. * @param result defines the target matrix
  6378. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6379. */
  6380. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6382. var n = znear;
  6383. var f = zfar;
  6384. var t = 1.0 / (Math.tan(fov * 0.5));
  6385. var a = isVerticalFovFixed ? (t / aspect) : t;
  6386. var b = isVerticalFovFixed ? t : (t * aspect);
  6387. var c = (f + n) / (f - n);
  6388. var d = -2.0 * f * n / (f - n);
  6389. 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);
  6390. };
  6391. /**
  6392. * Creates a right-handed perspective projection matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @returns a new matrix as a right-handed perspective projection matrix
  6398. */
  6399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6400. var matrix = Matrix.Zero();
  6401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6402. return matrix;
  6403. };
  6404. /**
  6405. * Stores a right-handed perspective projection into a given matrix
  6406. * @param fov defines the horizontal field of view
  6407. * @param aspect defines the aspect ratio
  6408. * @param znear defines the near clip plane
  6409. * @param zfar defines the far clip plane
  6410. * @param result defines the target matrix
  6411. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6412. */
  6413. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6414. //alternatively this could be expressed as:
  6415. // m = PerspectiveFovLHToRef
  6416. // m[10] *= -1.0;
  6417. // m[11] *= -1.0;
  6418. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6419. var n = znear;
  6420. var f = zfar;
  6421. var t = 1.0 / (Math.tan(fov * 0.5));
  6422. var a = isVerticalFovFixed ? (t / aspect) : t;
  6423. var b = isVerticalFovFixed ? t : (t * aspect);
  6424. var c = -(f + n) / (f - n);
  6425. var d = -2 * f * n / (f - n);
  6426. 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);
  6427. };
  6428. /**
  6429. * Stores a perspective projection for WebVR info a given matrix
  6430. * @param fov defines the field of view
  6431. * @param znear defines the near clip plane
  6432. * @param zfar defines the far clip plane
  6433. * @param result defines the target matrix
  6434. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6435. */
  6436. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6437. if (rightHanded === void 0) { rightHanded = false; }
  6438. var rightHandedFactor = rightHanded ? -1 : 1;
  6439. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6440. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6441. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6442. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6443. var xScale = 2.0 / (leftTan + rightTan);
  6444. var yScale = 2.0 / (upTan + downTan);
  6445. result.m[0] = xScale;
  6446. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6447. result.m[5] = yScale;
  6448. result.m[6] = result.m[7] = 0.0;
  6449. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6450. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6451. result.m[10] = -zfar / (znear - zfar);
  6452. result.m[11] = 1.0 * rightHandedFactor;
  6453. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6454. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6455. result._markAsUpdated();
  6456. };
  6457. /**
  6458. * Computes a complete transformation matrix
  6459. * @param viewport defines the viewport to use
  6460. * @param world defines the world matrix
  6461. * @param view defines the view matrix
  6462. * @param projection defines the projection matrix
  6463. * @param zmin defines the near clip plane
  6464. * @param zmax defines the far clip plane
  6465. * @returns the transformation matrix
  6466. */
  6467. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6468. var cw = viewport.width;
  6469. var ch = viewport.height;
  6470. var cx = viewport.x;
  6471. var cy = viewport.y;
  6472. 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);
  6473. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6474. };
  6475. /**
  6476. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6477. * @param matrix defines the matrix to use
  6478. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6479. */
  6480. Matrix.GetAsMatrix2x2 = function (matrix) {
  6481. return new Float32Array([
  6482. matrix.m[0], matrix.m[1],
  6483. matrix.m[4], matrix.m[5]
  6484. ]);
  6485. };
  6486. /**
  6487. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6488. * @param matrix defines the matrix to use
  6489. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6490. */
  6491. Matrix.GetAsMatrix3x3 = function (matrix) {
  6492. return new Float32Array([
  6493. matrix.m[0], matrix.m[1], matrix.m[2],
  6494. matrix.m[4], matrix.m[5], matrix.m[6],
  6495. matrix.m[8], matrix.m[9], matrix.m[10]
  6496. ]);
  6497. };
  6498. /**
  6499. * Compute the transpose of a given matrix
  6500. * @param matrix defines the matrix to transpose
  6501. * @returns the new matrix
  6502. */
  6503. Matrix.Transpose = function (matrix) {
  6504. var result = new Matrix();
  6505. Matrix.TransposeToRef(matrix, result);
  6506. return result;
  6507. };
  6508. /**
  6509. * Compute the transpose of a matrix and store it in a target matrix
  6510. * @param matrix defines the matrix to transpose
  6511. * @param result defines the target matrix
  6512. */
  6513. Matrix.TransposeToRef = function (matrix, result) {
  6514. result.m[0] = matrix.m[0];
  6515. result.m[1] = matrix.m[4];
  6516. result.m[2] = matrix.m[8];
  6517. result.m[3] = matrix.m[12];
  6518. result.m[4] = matrix.m[1];
  6519. result.m[5] = matrix.m[5];
  6520. result.m[6] = matrix.m[9];
  6521. result.m[7] = matrix.m[13];
  6522. result.m[8] = matrix.m[2];
  6523. result.m[9] = matrix.m[6];
  6524. result.m[10] = matrix.m[10];
  6525. result.m[11] = matrix.m[14];
  6526. result.m[12] = matrix.m[3];
  6527. result.m[13] = matrix.m[7];
  6528. result.m[14] = matrix.m[11];
  6529. result.m[15] = matrix.m[15];
  6530. };
  6531. /**
  6532. * Computes a reflection matrix from a plane
  6533. * @param plane defines the reflection plane
  6534. * @returns a new matrix
  6535. */
  6536. Matrix.Reflection = function (plane) {
  6537. var matrix = new Matrix();
  6538. Matrix.ReflectionToRef(plane, matrix);
  6539. return matrix;
  6540. };
  6541. /**
  6542. * Computes a reflection matrix from a plane
  6543. * @param plane defines the reflection plane
  6544. * @param result defines the target matrix
  6545. */
  6546. Matrix.ReflectionToRef = function (plane, result) {
  6547. plane.normalize();
  6548. var x = plane.normal.x;
  6549. var y = plane.normal.y;
  6550. var z = plane.normal.z;
  6551. var temp = -2 * x;
  6552. var temp2 = -2 * y;
  6553. var temp3 = -2 * z;
  6554. result.m[0] = (temp * x) + 1;
  6555. result.m[1] = temp2 * x;
  6556. result.m[2] = temp3 * x;
  6557. result.m[3] = 0.0;
  6558. result.m[4] = temp * y;
  6559. result.m[5] = (temp2 * y) + 1;
  6560. result.m[6] = temp3 * y;
  6561. result.m[7] = 0.0;
  6562. result.m[8] = temp * z;
  6563. result.m[9] = temp2 * z;
  6564. result.m[10] = (temp3 * z) + 1;
  6565. result.m[11] = 0.0;
  6566. result.m[12] = temp * plane.d;
  6567. result.m[13] = temp2 * plane.d;
  6568. result.m[14] = temp3 * plane.d;
  6569. result.m[15] = 1.0;
  6570. result._markAsUpdated();
  6571. };
  6572. /**
  6573. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6574. * @param xaxis defines the value of the 1st axis
  6575. * @param yaxis defines the value of the 2nd axis
  6576. * @param zaxis defines the value of the 3rd axis
  6577. * @param result defines the target matrix
  6578. */
  6579. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6580. result.m[0] = xaxis.x;
  6581. result.m[1] = xaxis.y;
  6582. result.m[2] = xaxis.z;
  6583. result.m[3] = 0.0;
  6584. result.m[4] = yaxis.x;
  6585. result.m[5] = yaxis.y;
  6586. result.m[6] = yaxis.z;
  6587. result.m[7] = 0.0;
  6588. result.m[8] = zaxis.x;
  6589. result.m[9] = zaxis.y;
  6590. result.m[10] = zaxis.z;
  6591. result.m[11] = 0.0;
  6592. result.m[12] = 0.0;
  6593. result.m[13] = 0.0;
  6594. result.m[14] = 0.0;
  6595. result.m[15] = 1.0;
  6596. result._markAsUpdated();
  6597. };
  6598. /**
  6599. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6600. * @param quat defines the quaternion to use
  6601. * @param result defines the target matrix
  6602. */
  6603. Matrix.FromQuaternionToRef = function (quat, result) {
  6604. var xx = quat.x * quat.x;
  6605. var yy = quat.y * quat.y;
  6606. var zz = quat.z * quat.z;
  6607. var xy = quat.x * quat.y;
  6608. var zw = quat.z * quat.w;
  6609. var zx = quat.z * quat.x;
  6610. var yw = quat.y * quat.w;
  6611. var yz = quat.y * quat.z;
  6612. var xw = quat.x * quat.w;
  6613. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6614. result.m[1] = 2.0 * (xy + zw);
  6615. result.m[2] = 2.0 * (zx - yw);
  6616. result.m[3] = 0.0;
  6617. result.m[4] = 2.0 * (xy - zw);
  6618. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6619. result.m[6] = 2.0 * (yz + xw);
  6620. result.m[7] = 0.0;
  6621. result.m[8] = 2.0 * (zx + yw);
  6622. result.m[9] = 2.0 * (yz - xw);
  6623. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6624. result.m[11] = 0.0;
  6625. result.m[12] = 0.0;
  6626. result.m[13] = 0.0;
  6627. result.m[14] = 0.0;
  6628. result.m[15] = 1.0;
  6629. result._markAsUpdated();
  6630. };
  6631. Matrix._tempQuaternion = new Quaternion();
  6632. Matrix._xAxis = Vector3.Zero();
  6633. Matrix._yAxis = Vector3.Zero();
  6634. Matrix._zAxis = Vector3.Zero();
  6635. Matrix._updateFlagSeed = 0;
  6636. Matrix._identityReadOnly = Matrix.Identity();
  6637. return Matrix;
  6638. }());
  6639. BABYLON.Matrix = Matrix;
  6640. var Plane = /** @class */ (function () {
  6641. /**
  6642. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6643. */
  6644. function Plane(a, b, c, d) {
  6645. this.normal = new Vector3(a, b, c);
  6646. this.d = d;
  6647. }
  6648. /**
  6649. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6650. */
  6651. Plane.prototype.asArray = function () {
  6652. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6653. };
  6654. // Methods
  6655. /**
  6656. * Returns a new plane copied from the current Plane.
  6657. */
  6658. Plane.prototype.clone = function () {
  6659. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6660. };
  6661. /**
  6662. * Returns the string "Plane".
  6663. */
  6664. Plane.prototype.getClassName = function () {
  6665. return "Plane";
  6666. };
  6667. /**
  6668. * Returns the Plane hash code.
  6669. */
  6670. Plane.prototype.getHashCode = function () {
  6671. var hash = this.normal.getHashCode();
  6672. hash = (hash * 397) ^ (this.d || 0);
  6673. return hash;
  6674. };
  6675. /**
  6676. * Normalize the current Plane in place.
  6677. * Returns the updated Plane.
  6678. */
  6679. Plane.prototype.normalize = function () {
  6680. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6681. var magnitude = 0.0;
  6682. if (norm !== 0) {
  6683. magnitude = 1.0 / norm;
  6684. }
  6685. this.normal.x *= magnitude;
  6686. this.normal.y *= magnitude;
  6687. this.normal.z *= magnitude;
  6688. this.d *= magnitude;
  6689. return this;
  6690. };
  6691. /**
  6692. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6693. */
  6694. Plane.prototype.transform = function (transformation) {
  6695. var transposedMatrix = Matrix.Transpose(transformation);
  6696. var x = this.normal.x;
  6697. var y = this.normal.y;
  6698. var z = this.normal.z;
  6699. var d = this.d;
  6700. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6701. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6702. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6703. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6704. return new Plane(normalX, normalY, normalZ, finalD);
  6705. };
  6706. /**
  6707. * Returns the dot product (float) of the point coordinates and the plane normal.
  6708. */
  6709. Plane.prototype.dotCoordinate = function (point) {
  6710. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6711. };
  6712. /**
  6713. * Updates the current Plane from the plane defined by the three given points.
  6714. * Returns the updated Plane.
  6715. */
  6716. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6717. var x1 = point2.x - point1.x;
  6718. var y1 = point2.y - point1.y;
  6719. var z1 = point2.z - point1.z;
  6720. var x2 = point3.x - point1.x;
  6721. var y2 = point3.y - point1.y;
  6722. var z2 = point3.z - point1.z;
  6723. var yz = (y1 * z2) - (z1 * y2);
  6724. var xz = (z1 * x2) - (x1 * z2);
  6725. var xy = (x1 * y2) - (y1 * x2);
  6726. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6727. var invPyth;
  6728. if (pyth !== 0) {
  6729. invPyth = 1.0 / pyth;
  6730. }
  6731. else {
  6732. invPyth = 0.0;
  6733. }
  6734. this.normal.x = yz * invPyth;
  6735. this.normal.y = xz * invPyth;
  6736. this.normal.z = xy * invPyth;
  6737. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6738. return this;
  6739. };
  6740. /**
  6741. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6742. */
  6743. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6744. var dot = Vector3.Dot(this.normal, direction);
  6745. return (dot <= epsilon);
  6746. };
  6747. /**
  6748. * Returns the signed distance (float) from the given point to the Plane.
  6749. */
  6750. Plane.prototype.signedDistanceTo = function (point) {
  6751. return Vector3.Dot(point, this.normal) + this.d;
  6752. };
  6753. // Statics
  6754. /**
  6755. * Returns a new Plane from the given array.
  6756. */
  6757. Plane.FromArray = function (array) {
  6758. return new Plane(array[0], array[1], array[2], array[3]);
  6759. };
  6760. /**
  6761. * Returns a new Plane defined by the three given points.
  6762. */
  6763. Plane.FromPoints = function (point1, point2, point3) {
  6764. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6765. result.copyFromPoints(point1, point2, point3);
  6766. return result;
  6767. };
  6768. /**
  6769. * Returns a new Plane the normal vector to this plane at the given origin point.
  6770. * Note : the vector "normal" is updated because normalized.
  6771. */
  6772. Plane.FromPositionAndNormal = function (origin, normal) {
  6773. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6774. normal.normalize();
  6775. result.normal = normal;
  6776. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6777. return result;
  6778. };
  6779. /**
  6780. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6781. */
  6782. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6783. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6784. return Vector3.Dot(point, normal) + d;
  6785. };
  6786. return Plane;
  6787. }());
  6788. BABYLON.Plane = Plane;
  6789. var Viewport = /** @class */ (function () {
  6790. /**
  6791. * Creates a Viewport object located at (x, y) and sized (width, height).
  6792. */
  6793. function Viewport(x, y, width, height) {
  6794. this.x = x;
  6795. this.y = y;
  6796. this.width = width;
  6797. this.height = height;
  6798. }
  6799. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6800. if (renderWidthOrEngine.getRenderWidth) {
  6801. var engine = renderWidthOrEngine;
  6802. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6803. }
  6804. var renderWidth = renderWidthOrEngine;
  6805. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6806. };
  6807. /**
  6808. * Returns a new Viewport copied from the current one.
  6809. */
  6810. Viewport.prototype.clone = function () {
  6811. return new Viewport(this.x, this.y, this.width, this.height);
  6812. };
  6813. return Viewport;
  6814. }());
  6815. BABYLON.Viewport = Viewport;
  6816. var Frustum = /** @class */ (function () {
  6817. function Frustum() {
  6818. }
  6819. /**
  6820. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6821. */
  6822. Frustum.GetPlanes = function (transform) {
  6823. var frustumPlanes = [];
  6824. for (var index = 0; index < 6; index++) {
  6825. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6826. }
  6827. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6828. return frustumPlanes;
  6829. };
  6830. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6831. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6832. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6833. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6834. frustumPlane.d = transform.m[15] + transform.m[14];
  6835. frustumPlane.normalize();
  6836. };
  6837. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6838. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6839. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6840. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6841. frustumPlane.d = transform.m[15] - transform.m[14];
  6842. frustumPlane.normalize();
  6843. };
  6844. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6845. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6846. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6847. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6848. frustumPlane.d = transform.m[15] + transform.m[12];
  6849. frustumPlane.normalize();
  6850. };
  6851. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6852. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6853. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6854. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6855. frustumPlane.d = transform.m[15] - transform.m[12];
  6856. frustumPlane.normalize();
  6857. };
  6858. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6859. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6860. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6861. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6862. frustumPlane.d = transform.m[15] - transform.m[13];
  6863. frustumPlane.normalize();
  6864. };
  6865. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6866. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6867. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6868. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6869. frustumPlane.d = transform.m[15] + transform.m[13];
  6870. frustumPlane.normalize();
  6871. };
  6872. /**
  6873. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6874. */
  6875. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6876. // Near
  6877. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6878. // Far
  6879. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6880. // Left
  6881. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6882. // Right
  6883. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6884. // Top
  6885. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6886. // Bottom
  6887. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6888. };
  6889. return Frustum;
  6890. }());
  6891. BABYLON.Frustum = Frustum;
  6892. /** Defines supported spaces */
  6893. var Space;
  6894. (function (Space) {
  6895. /** Local (object) space */
  6896. Space[Space["LOCAL"] = 0] = "LOCAL";
  6897. /** World space */
  6898. Space[Space["WORLD"] = 1] = "WORLD";
  6899. /** Bone space */
  6900. Space[Space["BONE"] = 2] = "BONE";
  6901. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6902. /** Defines the 3 main axes */
  6903. var Axis = /** @class */ (function () {
  6904. function Axis() {
  6905. }
  6906. /** X axis */
  6907. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6908. /** Y axis */
  6909. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6910. /** Z axis */
  6911. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6912. return Axis;
  6913. }());
  6914. BABYLON.Axis = Axis;
  6915. ;
  6916. var BezierCurve = /** @class */ (function () {
  6917. function BezierCurve() {
  6918. }
  6919. /**
  6920. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6921. */
  6922. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6923. // Extract X (which is equal to time here)
  6924. var f0 = 1 - 3 * x2 + 3 * x1;
  6925. var f1 = 3 * x2 - 6 * x1;
  6926. var f2 = 3 * x1;
  6927. var refinedT = t;
  6928. for (var i = 0; i < 5; i++) {
  6929. var refinedT2 = refinedT * refinedT;
  6930. var refinedT3 = refinedT2 * refinedT;
  6931. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6932. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6933. refinedT -= (x - t) * slope;
  6934. refinedT = Math.min(1, Math.max(0, refinedT));
  6935. }
  6936. // Resolve cubic bezier for the given x
  6937. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6938. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6939. Math.pow(refinedT, 3);
  6940. };
  6941. return BezierCurve;
  6942. }());
  6943. BABYLON.BezierCurve = BezierCurve;
  6944. /**
  6945. * Defines potential orientation for back face culling
  6946. */
  6947. var Orientation;
  6948. (function (Orientation) {
  6949. /**
  6950. * Clockwise
  6951. */
  6952. Orientation[Orientation["CW"] = 0] = "CW";
  6953. /** Counter clockwise */
  6954. Orientation[Orientation["CCW"] = 1] = "CCW";
  6955. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6956. /**
  6957. * Defines angle representation
  6958. */
  6959. var Angle = /** @class */ (function () {
  6960. /**
  6961. * Creates an Angle object of "radians" radians (float).
  6962. */
  6963. function Angle(radians) {
  6964. this._radians = radians;
  6965. if (this._radians < 0.0)
  6966. this._radians += (2.0 * Math.PI);
  6967. }
  6968. /**
  6969. * Get value in degrees
  6970. * @returns the Angle value in degrees (float)
  6971. */
  6972. Angle.prototype.degrees = function () {
  6973. return this._radians * 180.0 / Math.PI;
  6974. };
  6975. /**
  6976. * Get value in radians
  6977. * @returns the Angle value in radians (float)
  6978. */
  6979. Angle.prototype.radians = function () {
  6980. return this._radians;
  6981. };
  6982. /**
  6983. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6984. * @param a defines first vector
  6985. * @param b defines second vector
  6986. * @returns a new Angle
  6987. */
  6988. Angle.BetweenTwoPoints = function (a, b) {
  6989. var delta = b.subtract(a);
  6990. var theta = Math.atan2(delta.y, delta.x);
  6991. return new Angle(theta);
  6992. };
  6993. /**
  6994. * Gets a new Angle object from the given float in radians
  6995. * @param radians defines the angle value in radians
  6996. * @returns a new Angle
  6997. */
  6998. Angle.FromRadians = function (radians) {
  6999. return new Angle(radians);
  7000. };
  7001. /**
  7002. * Gets a new Angle object from the given float in degrees
  7003. * @param degrees defines the angle value in degrees
  7004. * @returns a new Angle
  7005. */
  7006. Angle.FromDegrees = function (degrees) {
  7007. return new Angle(degrees * Math.PI / 180.0);
  7008. };
  7009. return Angle;
  7010. }());
  7011. BABYLON.Angle = Angle;
  7012. /**
  7013. * This represents an arc in a 2d space.
  7014. */
  7015. var Arc2 = /** @class */ (function () {
  7016. /**
  7017. * Creates an Arc object from the three given points : start, middle and end.
  7018. * @param startPoint Defines the start point of the arc
  7019. * @param midPoint Defines the midlle point of the arc
  7020. * @param endPoint Defines the end point of the arc
  7021. */
  7022. function Arc2(
  7023. /** Defines the start point of the arc */
  7024. startPoint,
  7025. /** Defines the mid point of the arc */
  7026. midPoint,
  7027. /** Defines the end point of the arc */
  7028. endPoint) {
  7029. this.startPoint = startPoint;
  7030. this.midPoint = midPoint;
  7031. this.endPoint = endPoint;
  7032. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7033. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7034. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7035. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7036. 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);
  7037. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7038. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7039. var a1 = this.startAngle.degrees();
  7040. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7041. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7042. // angles correction
  7043. if (a2 - a1 > +180.0)
  7044. a2 -= 360.0;
  7045. if (a2 - a1 < -180.0)
  7046. a2 += 360.0;
  7047. if (a3 - a2 > +180.0)
  7048. a3 -= 360.0;
  7049. if (a3 - a2 < -180.0)
  7050. a3 += 360.0;
  7051. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7052. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7053. }
  7054. return Arc2;
  7055. }());
  7056. BABYLON.Arc2 = Arc2;
  7057. var Path2 = /** @class */ (function () {
  7058. /**
  7059. * Creates a Path2 object from the starting 2D coordinates x and y.
  7060. */
  7061. function Path2(x, y) {
  7062. this._points = new Array();
  7063. this._length = 0.0;
  7064. this.closed = false;
  7065. this._points.push(new Vector2(x, y));
  7066. }
  7067. /**
  7068. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7069. * Returns the updated Path2.
  7070. */
  7071. Path2.prototype.addLineTo = function (x, y) {
  7072. if (this.closed) {
  7073. return this;
  7074. }
  7075. var newPoint = new Vector2(x, y);
  7076. var previousPoint = this._points[this._points.length - 1];
  7077. this._points.push(newPoint);
  7078. this._length += newPoint.subtract(previousPoint).length();
  7079. return this;
  7080. };
  7081. /**
  7082. * 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.
  7083. * Returns the updated Path2.
  7084. */
  7085. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7086. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7087. if (this.closed) {
  7088. return this;
  7089. }
  7090. var startPoint = this._points[this._points.length - 1];
  7091. var midPoint = new Vector2(midX, midY);
  7092. var endPoint = new Vector2(endX, endY);
  7093. var arc = new Arc2(startPoint, midPoint, endPoint);
  7094. var increment = arc.angle.radians() / numberOfSegments;
  7095. if (arc.orientation === Orientation.CW)
  7096. increment *= -1;
  7097. var currentAngle = arc.startAngle.radians() + increment;
  7098. for (var i = 0; i < numberOfSegments; i++) {
  7099. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7100. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7101. this.addLineTo(x, y);
  7102. currentAngle += increment;
  7103. }
  7104. return this;
  7105. };
  7106. /**
  7107. * Closes the Path2.
  7108. * Returns the Path2.
  7109. */
  7110. Path2.prototype.close = function () {
  7111. this.closed = true;
  7112. return this;
  7113. };
  7114. /**
  7115. * Returns the Path2 total length (float).
  7116. */
  7117. Path2.prototype.length = function () {
  7118. var result = this._length;
  7119. if (!this.closed) {
  7120. var lastPoint = this._points[this._points.length - 1];
  7121. var firstPoint = this._points[0];
  7122. result += (firstPoint.subtract(lastPoint).length());
  7123. }
  7124. return result;
  7125. };
  7126. /**
  7127. * Returns the Path2 internal array of points.
  7128. */
  7129. Path2.prototype.getPoints = function () {
  7130. return this._points;
  7131. };
  7132. /**
  7133. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7134. */
  7135. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7136. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7137. return Vector2.Zero();
  7138. }
  7139. var lengthPosition = normalizedLengthPosition * this.length();
  7140. var previousOffset = 0;
  7141. for (var i = 0; i < this._points.length; i++) {
  7142. var j = (i + 1) % this._points.length;
  7143. var a = this._points[i];
  7144. var b = this._points[j];
  7145. var bToA = b.subtract(a);
  7146. var nextOffset = (bToA.length() + previousOffset);
  7147. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7148. var dir = bToA.normalize();
  7149. var localOffset = lengthPosition - previousOffset;
  7150. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7151. }
  7152. previousOffset = nextOffset;
  7153. }
  7154. return Vector2.Zero();
  7155. };
  7156. /**
  7157. * Returns a new Path2 starting at the coordinates (x, y).
  7158. */
  7159. Path2.StartingAt = function (x, y) {
  7160. return new Path2(x, y);
  7161. };
  7162. return Path2;
  7163. }());
  7164. BABYLON.Path2 = Path2;
  7165. var Path3D = /** @class */ (function () {
  7166. /**
  7167. * new Path3D(path, normal, raw)
  7168. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7169. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7170. * path : an array of Vector3, the curve axis of the Path3D
  7171. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7172. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7173. */
  7174. function Path3D(path, firstNormal, raw) {
  7175. if (firstNormal === void 0) { firstNormal = null; }
  7176. this.path = path;
  7177. this._curve = new Array();
  7178. this._distances = new Array();
  7179. this._tangents = new Array();
  7180. this._normals = new Array();
  7181. this._binormals = new Array();
  7182. for (var p = 0; p < path.length; p++) {
  7183. this._curve[p] = path[p].clone(); // hard copy
  7184. }
  7185. this._raw = raw || false;
  7186. this._compute(firstNormal);
  7187. }
  7188. /**
  7189. * Returns the Path3D array of successive Vector3 designing its curve.
  7190. */
  7191. Path3D.prototype.getCurve = function () {
  7192. return this._curve;
  7193. };
  7194. /**
  7195. * Returns an array populated with tangent vectors on each Path3D curve point.
  7196. */
  7197. Path3D.prototype.getTangents = function () {
  7198. return this._tangents;
  7199. };
  7200. /**
  7201. * Returns an array populated with normal vectors on each Path3D curve point.
  7202. */
  7203. Path3D.prototype.getNormals = function () {
  7204. return this._normals;
  7205. };
  7206. /**
  7207. * Returns an array populated with binormal vectors on each Path3D curve point.
  7208. */
  7209. Path3D.prototype.getBinormals = function () {
  7210. return this._binormals;
  7211. };
  7212. /**
  7213. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7214. */
  7215. Path3D.prototype.getDistances = function () {
  7216. return this._distances;
  7217. };
  7218. /**
  7219. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7220. * Returns the same object updated.
  7221. */
  7222. Path3D.prototype.update = function (path, firstNormal) {
  7223. if (firstNormal === void 0) { firstNormal = null; }
  7224. for (var p = 0; p < path.length; p++) {
  7225. this._curve[p].x = path[p].x;
  7226. this._curve[p].y = path[p].y;
  7227. this._curve[p].z = path[p].z;
  7228. }
  7229. this._compute(firstNormal);
  7230. return this;
  7231. };
  7232. // private function compute() : computes tangents, normals and binormals
  7233. Path3D.prototype._compute = function (firstNormal) {
  7234. var l = this._curve.length;
  7235. // first and last tangents
  7236. this._tangents[0] = this._getFirstNonNullVector(0);
  7237. if (!this._raw) {
  7238. this._tangents[0].normalize();
  7239. }
  7240. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7241. if (!this._raw) {
  7242. this._tangents[l - 1].normalize();
  7243. }
  7244. // normals and binormals at first point : arbitrary vector with _normalVector()
  7245. var tg0 = this._tangents[0];
  7246. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7247. this._normals[0] = pp0;
  7248. if (!this._raw) {
  7249. this._normals[0].normalize();
  7250. }
  7251. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7252. if (!this._raw) {
  7253. this._binormals[0].normalize();
  7254. }
  7255. this._distances[0] = 0.0;
  7256. // normals and binormals : next points
  7257. var prev; // previous vector (segment)
  7258. var cur; // current vector (segment)
  7259. var curTang; // current tangent
  7260. // previous normal
  7261. var prevBinor; // previous binormal
  7262. for (var i = 1; i < l; i++) {
  7263. // tangents
  7264. prev = this._getLastNonNullVector(i);
  7265. if (i < l - 1) {
  7266. cur = this._getFirstNonNullVector(i);
  7267. this._tangents[i] = prev.add(cur);
  7268. this._tangents[i].normalize();
  7269. }
  7270. this._distances[i] = this._distances[i - 1] + prev.length();
  7271. // normals and binormals
  7272. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7273. curTang = this._tangents[i];
  7274. prevBinor = this._binormals[i - 1];
  7275. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7276. if (!this._raw) {
  7277. this._normals[i].normalize();
  7278. }
  7279. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7280. if (!this._raw) {
  7281. this._binormals[i].normalize();
  7282. }
  7283. }
  7284. };
  7285. // private function getFirstNonNullVector(index)
  7286. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7287. Path3D.prototype._getFirstNonNullVector = function (index) {
  7288. var i = 1;
  7289. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7290. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7291. i++;
  7292. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7293. }
  7294. return nNVector;
  7295. };
  7296. // private function getLastNonNullVector(index)
  7297. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7298. Path3D.prototype._getLastNonNullVector = function (index) {
  7299. var i = 1;
  7300. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7301. while (nLVector.length() === 0 && index > i + 1) {
  7302. i++;
  7303. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7304. }
  7305. return nLVector;
  7306. };
  7307. // private function normalVector(v0, vt, va) :
  7308. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7309. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7310. Path3D.prototype._normalVector = function (v0, vt, va) {
  7311. var normal0;
  7312. var tgl = vt.length();
  7313. if (tgl === 0.0) {
  7314. tgl = 1.0;
  7315. }
  7316. if (va === undefined || va === null) {
  7317. var point;
  7318. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7319. point = new Vector3(0.0, -1.0, 0.0);
  7320. }
  7321. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7322. point = new Vector3(1.0, 0.0, 0.0);
  7323. }
  7324. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7325. point = new Vector3(0.0, 0.0, 1.0);
  7326. }
  7327. else {
  7328. point = Vector3.Zero();
  7329. }
  7330. normal0 = Vector3.Cross(vt, point);
  7331. }
  7332. else {
  7333. normal0 = Vector3.Cross(vt, va);
  7334. Vector3.CrossToRef(normal0, vt, normal0);
  7335. }
  7336. normal0.normalize();
  7337. return normal0;
  7338. };
  7339. return Path3D;
  7340. }());
  7341. BABYLON.Path3D = Path3D;
  7342. var Curve3 = /** @class */ (function () {
  7343. /**
  7344. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7345. * A Curve3 is designed from a series of successive Vector3.
  7346. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7347. */
  7348. function Curve3(points) {
  7349. this._length = 0.0;
  7350. this._points = points;
  7351. this._length = this._computeLength(points);
  7352. }
  7353. /**
  7354. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7355. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7356. * @param v1 (Vector3) the control point
  7357. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7358. * @param nbPoints (integer) the wanted number of points in the curve
  7359. */
  7360. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7361. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7362. var bez = new Array();
  7363. var equation = function (t, val0, val1, val2) {
  7364. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7365. return res;
  7366. };
  7367. for (var i = 0; i <= nbPoints; i++) {
  7368. 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)));
  7369. }
  7370. return new Curve3(bez);
  7371. };
  7372. /**
  7373. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7374. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7375. * @param v1 (Vector3) the first control point
  7376. * @param v2 (Vector3) the second control point
  7377. * @param v3 (Vector3) the end point of the Cubic Bezier
  7378. * @param nbPoints (integer) the wanted number of points in the curve
  7379. */
  7380. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7381. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7382. var bez = new Array();
  7383. var equation = function (t, val0, val1, val2, val3) {
  7384. 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;
  7385. return res;
  7386. };
  7387. for (var i = 0; i <= nbPoints; i++) {
  7388. 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)));
  7389. }
  7390. return new Curve3(bez);
  7391. };
  7392. /**
  7393. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7394. * @param p1 (Vector3) the origin point of the Hermite Spline
  7395. * @param t1 (Vector3) the tangent vector at the origin point
  7396. * @param p2 (Vector3) the end point of the Hermite Spline
  7397. * @param t2 (Vector3) the tangent vector at the end point
  7398. * @param nbPoints (integer) the wanted number of points in the curve
  7399. */
  7400. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7401. var hermite = new Array();
  7402. var step = 1.0 / nbPoints;
  7403. for (var i = 0; i <= nbPoints; i++) {
  7404. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7405. }
  7406. return new Curve3(hermite);
  7407. };
  7408. /**
  7409. * Returns a Curve3 object along a CatmullRom Spline curve :
  7410. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7411. * @param nbPoints (integer) the wanted number of points between each curve control points
  7412. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7413. */
  7414. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7415. var catmullRom = new Array();
  7416. var step = 1.0 / nbPoints;
  7417. var amount = 0.0;
  7418. if (closed) {
  7419. var pointsCount = points.length;
  7420. for (var i = 0; i < pointsCount; i++) {
  7421. amount = 0;
  7422. for (var c = 0; c < nbPoints; c++) {
  7423. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7424. amount += step;
  7425. }
  7426. }
  7427. catmullRom.push(catmullRom[0]);
  7428. }
  7429. else {
  7430. var totalPoints = new Array();
  7431. totalPoints.push(points[0].clone());
  7432. Array.prototype.push.apply(totalPoints, points);
  7433. totalPoints.push(points[points.length - 1].clone());
  7434. for (var i = 0; i < totalPoints.length - 3; i++) {
  7435. amount = 0;
  7436. for (var c = 0; c < nbPoints; c++) {
  7437. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7438. amount += step;
  7439. }
  7440. }
  7441. i--;
  7442. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7443. }
  7444. return new Curve3(catmullRom);
  7445. };
  7446. /**
  7447. * Returns the Curve3 stored array of successive Vector3
  7448. */
  7449. Curve3.prototype.getPoints = function () {
  7450. return this._points;
  7451. };
  7452. /**
  7453. * Returns the computed length (float) of the curve.
  7454. */
  7455. Curve3.prototype.length = function () {
  7456. return this._length;
  7457. };
  7458. /**
  7459. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7460. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7461. * curveA and curveB keep unchanged.
  7462. */
  7463. Curve3.prototype.continue = function (curve) {
  7464. var lastPoint = this._points[this._points.length - 1];
  7465. var continuedPoints = this._points.slice();
  7466. var curvePoints = curve.getPoints();
  7467. for (var i = 1; i < curvePoints.length; i++) {
  7468. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7469. }
  7470. var continuedCurve = new Curve3(continuedPoints);
  7471. return continuedCurve;
  7472. };
  7473. Curve3.prototype._computeLength = function (path) {
  7474. var l = 0;
  7475. for (var i = 1; i < path.length; i++) {
  7476. l += (path[i].subtract(path[i - 1])).length();
  7477. }
  7478. return l;
  7479. };
  7480. return Curve3;
  7481. }());
  7482. BABYLON.Curve3 = Curve3;
  7483. // Vertex formats
  7484. var PositionNormalVertex = /** @class */ (function () {
  7485. function PositionNormalVertex(position, normal) {
  7486. if (position === void 0) { position = Vector3.Zero(); }
  7487. if (normal === void 0) { normal = Vector3.Up(); }
  7488. this.position = position;
  7489. this.normal = normal;
  7490. }
  7491. PositionNormalVertex.prototype.clone = function () {
  7492. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7493. };
  7494. return PositionNormalVertex;
  7495. }());
  7496. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7497. var PositionNormalTextureVertex = /** @class */ (function () {
  7498. function PositionNormalTextureVertex(position, normal, uv) {
  7499. if (position === void 0) { position = Vector3.Zero(); }
  7500. if (normal === void 0) { normal = Vector3.Up(); }
  7501. if (uv === void 0) { uv = Vector2.Zero(); }
  7502. this.position = position;
  7503. this.normal = normal;
  7504. this.uv = uv;
  7505. }
  7506. PositionNormalTextureVertex.prototype.clone = function () {
  7507. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7508. };
  7509. return PositionNormalTextureVertex;
  7510. }());
  7511. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7512. // Temporary pre-allocated objects for engine internal use
  7513. // usage in any internal function :
  7514. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7515. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7516. var Tmp = /** @class */ (function () {
  7517. function Tmp() {
  7518. }
  7519. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7520. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7521. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7522. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7523. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7524. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7525. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7526. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7527. Matrix.Zero(), Matrix.Zero(),
  7528. Matrix.Zero(), Matrix.Zero(),
  7529. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7530. return Tmp;
  7531. }());
  7532. BABYLON.Tmp = Tmp;
  7533. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7534. var MathTmp = /** @class */ (function () {
  7535. function MathTmp() {
  7536. }
  7537. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7538. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7539. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7540. return MathTmp;
  7541. }());
  7542. })(BABYLON || (BABYLON = {}));
  7543. //# sourceMappingURL=babylon.math.js.map
  7544. var BABYLON;
  7545. (function (BABYLON) {
  7546. var Scalar = /** @class */ (function () {
  7547. function Scalar() {
  7548. }
  7549. /**
  7550. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7551. */
  7552. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7553. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7554. var num = a - b;
  7555. return -epsilon <= num && num <= epsilon;
  7556. };
  7557. /**
  7558. * Returns a string : the upper case translation of the number i to hexadecimal.
  7559. */
  7560. Scalar.ToHex = function (i) {
  7561. var str = i.toString(16);
  7562. if (i <= 15) {
  7563. return ("0" + str).toUpperCase();
  7564. }
  7565. return str.toUpperCase();
  7566. };
  7567. /**
  7568. * Returns -1 if value is negative and +1 is value is positive.
  7569. * Returns the value itself if it's equal to zero.
  7570. */
  7571. Scalar.Sign = function (value) {
  7572. value = +value; // convert to a number
  7573. if (value === 0 || isNaN(value))
  7574. return value;
  7575. return value > 0 ? 1 : -1;
  7576. };
  7577. /**
  7578. * Returns the value itself if it's between min and max.
  7579. * Returns min if the value is lower than min.
  7580. * Returns max if the value is greater than max.
  7581. */
  7582. Scalar.Clamp = function (value, min, max) {
  7583. if (min === void 0) { min = 0; }
  7584. if (max === void 0) { max = 1; }
  7585. return Math.min(max, Math.max(min, value));
  7586. };
  7587. /**
  7588. * Returns the log2 of value.
  7589. */
  7590. Scalar.Log2 = function (value) {
  7591. return Math.log(value) * Math.LOG2E;
  7592. };
  7593. /**
  7594. * Loops the value, so that it is never larger than length and never smaller than 0.
  7595. *
  7596. * This is similar to the modulo operator but it works with floating point numbers.
  7597. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7598. * With t = 5 and length = 2.5, the result would be 0.0.
  7599. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7600. */
  7601. Scalar.Repeat = function (value, length) {
  7602. return value - Math.floor(value / length) * length;
  7603. };
  7604. /**
  7605. * Normalize the value between 0.0 and 1.0 using min and max values
  7606. */
  7607. Scalar.Normalize = function (value, min, max) {
  7608. return (value - min) / (max - min);
  7609. };
  7610. /**
  7611. * Denormalize the value from 0.0 and 1.0 using min and max values
  7612. */
  7613. Scalar.Denormalize = function (normalized, min, max) {
  7614. return (normalized * (max - min) + min);
  7615. };
  7616. /**
  7617. * Calculates the shortest difference between two given angles given in degrees.
  7618. */
  7619. Scalar.DeltaAngle = function (current, target) {
  7620. var num = Scalar.Repeat(target - current, 360.0);
  7621. if (num > 180.0) {
  7622. num -= 360.0;
  7623. }
  7624. return num;
  7625. };
  7626. /**
  7627. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7628. *
  7629. * The returned value will move back and forth between 0 and length
  7630. */
  7631. Scalar.PingPong = function (tx, length) {
  7632. var t = Scalar.Repeat(tx, length * 2.0);
  7633. return length - Math.abs(t - length);
  7634. };
  7635. /**
  7636. * Interpolates between min and max with smoothing at the limits.
  7637. *
  7638. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7639. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7640. */
  7641. Scalar.SmoothStep = function (from, to, tx) {
  7642. var t = Scalar.Clamp(tx);
  7643. t = -2.0 * t * t * t + 3.0 * t * t;
  7644. return to * t + from * (1.0 - t);
  7645. };
  7646. /**
  7647. * Moves a value current towards target.
  7648. *
  7649. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7650. * Negative values of maxDelta pushes the value away from target.
  7651. */
  7652. Scalar.MoveTowards = function (current, target, maxDelta) {
  7653. var result = 0;
  7654. if (Math.abs(target - current) <= maxDelta) {
  7655. result = target;
  7656. }
  7657. else {
  7658. result = current + Scalar.Sign(target - current) * maxDelta;
  7659. }
  7660. return result;
  7661. };
  7662. /**
  7663. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7664. *
  7665. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7666. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7667. */
  7668. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7669. var num = Scalar.DeltaAngle(current, target);
  7670. var result = 0;
  7671. if (-maxDelta < num && num < maxDelta) {
  7672. result = target;
  7673. }
  7674. else {
  7675. target = current + num;
  7676. result = Scalar.MoveTowards(current, target, maxDelta);
  7677. }
  7678. return result;
  7679. };
  7680. /**
  7681. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7682. */
  7683. Scalar.Lerp = function (start, end, amount) {
  7684. return start + ((end - start) * amount);
  7685. };
  7686. /**
  7687. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7688. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7689. */
  7690. Scalar.LerpAngle = function (start, end, amount) {
  7691. var num = Scalar.Repeat(end - start, 360.0);
  7692. if (num > 180.0) {
  7693. num -= 360.0;
  7694. }
  7695. return start + num * Scalar.Clamp(amount);
  7696. };
  7697. /**
  7698. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7699. */
  7700. Scalar.InverseLerp = function (a, b, value) {
  7701. var result = 0;
  7702. if (a != b) {
  7703. result = Scalar.Clamp((value - a) / (b - a));
  7704. }
  7705. else {
  7706. result = 0.0;
  7707. }
  7708. return result;
  7709. };
  7710. /**
  7711. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7712. */
  7713. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7714. var squared = amount * amount;
  7715. var cubed = amount * squared;
  7716. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7717. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7718. var part3 = (cubed - (2.0 * squared)) + amount;
  7719. var part4 = cubed - squared;
  7720. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7721. };
  7722. /**
  7723. * Returns a random float number between and min and max values
  7724. */
  7725. Scalar.RandomRange = function (min, max) {
  7726. if (min === max)
  7727. return min;
  7728. return ((Math.random() * (max - min)) + min);
  7729. };
  7730. /**
  7731. * This function returns percentage of a number in a given range.
  7732. *
  7733. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7734. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7735. */
  7736. Scalar.RangeToPercent = function (number, min, max) {
  7737. return ((number - min) / (max - min));
  7738. };
  7739. /**
  7740. * This function returns number that corresponds to the percentage in a given range.
  7741. *
  7742. * PercentToRange(0.34,0,100) will return 34.
  7743. */
  7744. Scalar.PercentToRange = function (percent, min, max) {
  7745. return ((max - min) * percent + min);
  7746. };
  7747. /**
  7748. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7749. * @param angle The angle to normalize in radian.
  7750. * @return The converted angle.
  7751. */
  7752. Scalar.NormalizeRadians = function (angle) {
  7753. // More precise but slower version kept for reference.
  7754. // angle = angle % Tools.TwoPi;
  7755. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7756. //if (angle > Math.PI) {
  7757. // angle -= Tools.TwoPi;
  7758. //}
  7759. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7760. return angle;
  7761. };
  7762. /**
  7763. * Two pi constants convenient for computation.
  7764. */
  7765. Scalar.TwoPi = Math.PI * 2;
  7766. return Scalar;
  7767. }());
  7768. BABYLON.Scalar = Scalar;
  7769. })(BABYLON || (BABYLON = {}));
  7770. //# sourceMappingURL=babylon.math.scalar.js.map
  7771. //# sourceMappingURL=babylon.mixins.js.map
  7772. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7773. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7774. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7775. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7776. //# sourceMappingURL=babylon.webgl2.js.map
  7777. var BABYLON;
  7778. (function (BABYLON) {
  7779. var __decoratorInitialStore = {};
  7780. var __mergedStore = {};
  7781. var _copySource = function (creationFunction, source, instanciate) {
  7782. var destination = creationFunction();
  7783. // Tags
  7784. if (BABYLON.Tags) {
  7785. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7786. }
  7787. var classStore = getMergedStore(destination);
  7788. // Properties
  7789. for (var property in classStore) {
  7790. var propertyDescriptor = classStore[property];
  7791. var sourceProperty = source[property];
  7792. var propertyType = propertyDescriptor.type;
  7793. if (sourceProperty !== undefined && sourceProperty !== null) {
  7794. switch (propertyType) {
  7795. case 0: // Value
  7796. case 6: // Mesh reference
  7797. case 11: // Camera reference
  7798. destination[property] = sourceProperty;
  7799. break;
  7800. case 1: // Texture
  7801. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7802. break;
  7803. case 2: // Color3
  7804. case 3: // FresnelParameters
  7805. case 4: // Vector2
  7806. case 5: // Vector3
  7807. case 7: // Color Curves
  7808. case 10: // Quaternion
  7809. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7810. break;
  7811. }
  7812. }
  7813. }
  7814. return destination;
  7815. };
  7816. function getDirectStore(target) {
  7817. var classKey = target.getClassName();
  7818. if (!__decoratorInitialStore[classKey]) {
  7819. __decoratorInitialStore[classKey] = {};
  7820. }
  7821. return __decoratorInitialStore[classKey];
  7822. }
  7823. /**
  7824. * Return the list of properties flagged as serializable
  7825. * @param target: host object
  7826. */
  7827. function getMergedStore(target) {
  7828. var classKey = target.getClassName();
  7829. if (__mergedStore[classKey]) {
  7830. return __mergedStore[classKey];
  7831. }
  7832. __mergedStore[classKey] = {};
  7833. var store = __mergedStore[classKey];
  7834. var currentTarget = target;
  7835. var currentKey = classKey;
  7836. while (currentKey) {
  7837. var initialStore = __decoratorInitialStore[currentKey];
  7838. for (var property in initialStore) {
  7839. store[property] = initialStore[property];
  7840. }
  7841. var parent_1 = void 0;
  7842. var done = false;
  7843. do {
  7844. parent_1 = Object.getPrototypeOf(currentTarget);
  7845. if (!parent_1.getClassName) {
  7846. done = true;
  7847. break;
  7848. }
  7849. if (parent_1.getClassName() !== currentKey) {
  7850. break;
  7851. }
  7852. currentTarget = parent_1;
  7853. } while (parent_1);
  7854. if (done) {
  7855. break;
  7856. }
  7857. currentKey = parent_1.getClassName();
  7858. currentTarget = parent_1;
  7859. }
  7860. return store;
  7861. }
  7862. function generateSerializableMember(type, sourceName) {
  7863. return function (target, propertyKey) {
  7864. var classStore = getDirectStore(target);
  7865. if (!classStore[propertyKey]) {
  7866. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7867. }
  7868. };
  7869. }
  7870. function generateExpandMember(setCallback, targetKey) {
  7871. if (targetKey === void 0) { targetKey = null; }
  7872. return function (target, propertyKey) {
  7873. var key = targetKey || ("_" + propertyKey);
  7874. Object.defineProperty(target, propertyKey, {
  7875. get: function () {
  7876. return this[key];
  7877. },
  7878. set: function (value) {
  7879. if (this[key] === value) {
  7880. return;
  7881. }
  7882. this[key] = value;
  7883. target[setCallback].apply(this);
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. };
  7889. }
  7890. function expandToProperty(callback, targetKey) {
  7891. if (targetKey === void 0) { targetKey = null; }
  7892. return generateExpandMember(callback, targetKey);
  7893. }
  7894. BABYLON.expandToProperty = expandToProperty;
  7895. function serialize(sourceName) {
  7896. return generateSerializableMember(0, sourceName); // value member
  7897. }
  7898. BABYLON.serialize = serialize;
  7899. function serializeAsTexture(sourceName) {
  7900. return generateSerializableMember(1, sourceName); // texture member
  7901. }
  7902. BABYLON.serializeAsTexture = serializeAsTexture;
  7903. function serializeAsColor3(sourceName) {
  7904. return generateSerializableMember(2, sourceName); // color3 member
  7905. }
  7906. BABYLON.serializeAsColor3 = serializeAsColor3;
  7907. function serializeAsFresnelParameters(sourceName) {
  7908. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7909. }
  7910. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7911. function serializeAsVector2(sourceName) {
  7912. return generateSerializableMember(4, sourceName); // vector2 member
  7913. }
  7914. BABYLON.serializeAsVector2 = serializeAsVector2;
  7915. function serializeAsVector3(sourceName) {
  7916. return generateSerializableMember(5, sourceName); // vector3 member
  7917. }
  7918. BABYLON.serializeAsVector3 = serializeAsVector3;
  7919. function serializeAsMeshReference(sourceName) {
  7920. return generateSerializableMember(6, sourceName); // mesh reference member
  7921. }
  7922. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7923. function serializeAsColorCurves(sourceName) {
  7924. return generateSerializableMember(7, sourceName); // color curves
  7925. }
  7926. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7927. function serializeAsColor4(sourceName) {
  7928. return generateSerializableMember(8, sourceName); // color 4
  7929. }
  7930. BABYLON.serializeAsColor4 = serializeAsColor4;
  7931. function serializeAsImageProcessingConfiguration(sourceName) {
  7932. return generateSerializableMember(9, sourceName); // image processing
  7933. }
  7934. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7935. function serializeAsQuaternion(sourceName) {
  7936. return generateSerializableMember(10, sourceName); // quaternion member
  7937. }
  7938. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7939. /**
  7940. * Decorator used to define property that can be serialized as reference to a camera
  7941. * @param sourceName defines the name of the property to decorate
  7942. */
  7943. function serializeAsCameraReference(sourceName) {
  7944. return generateSerializableMember(11, sourceName); // camera reference member
  7945. }
  7946. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7947. var SerializationHelper = /** @class */ (function () {
  7948. function SerializationHelper() {
  7949. }
  7950. SerializationHelper.Serialize = function (entity, serializationObject) {
  7951. if (!serializationObject) {
  7952. serializationObject = {};
  7953. }
  7954. // Tags
  7955. if (BABYLON.Tags) {
  7956. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7957. }
  7958. var serializedProperties = getMergedStore(entity);
  7959. // Properties
  7960. for (var property in serializedProperties) {
  7961. var propertyDescriptor = serializedProperties[property];
  7962. var targetPropertyName = propertyDescriptor.sourceName || property;
  7963. var propertyType = propertyDescriptor.type;
  7964. var sourceProperty = entity[property];
  7965. if (sourceProperty !== undefined && sourceProperty !== null) {
  7966. switch (propertyType) {
  7967. case 0: // Value
  7968. serializationObject[targetPropertyName] = sourceProperty;
  7969. break;
  7970. case 1: // Texture
  7971. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7972. break;
  7973. case 2: // Color3
  7974. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7975. break;
  7976. case 3: // FresnelParameters
  7977. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7978. break;
  7979. case 4: // Vector2
  7980. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7981. break;
  7982. case 5: // Vector3
  7983. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7984. break;
  7985. case 6: // Mesh reference
  7986. serializationObject[targetPropertyName] = sourceProperty.id;
  7987. break;
  7988. case 7: // Color Curves
  7989. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7990. break;
  7991. case 8: // Color 4
  7992. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7993. break;
  7994. case 9: // Image Processing
  7995. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7996. break;
  7997. case 10: // Quaternion
  7998. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7999. break;
  8000. case 11: // Camera reference
  8001. serializationObject[targetPropertyName] = sourceProperty.id;
  8002. break;
  8003. }
  8004. }
  8005. }
  8006. return serializationObject;
  8007. };
  8008. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8009. if (rootUrl === void 0) { rootUrl = null; }
  8010. var destination = creationFunction();
  8011. if (!rootUrl) {
  8012. rootUrl = "";
  8013. }
  8014. // Tags
  8015. if (BABYLON.Tags) {
  8016. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8017. }
  8018. var classStore = getMergedStore(destination);
  8019. // Properties
  8020. for (var property in classStore) {
  8021. var propertyDescriptor = classStore[property];
  8022. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8023. var propertyType = propertyDescriptor.type;
  8024. if (sourceProperty !== undefined && sourceProperty !== null) {
  8025. var dest = destination;
  8026. switch (propertyType) {
  8027. case 0: // Value
  8028. dest[property] = sourceProperty;
  8029. break;
  8030. case 1: // Texture
  8031. if (scene) {
  8032. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8033. }
  8034. break;
  8035. case 2: // Color3
  8036. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8037. break;
  8038. case 3: // FresnelParameters
  8039. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8040. break;
  8041. case 4: // Vector2
  8042. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8043. break;
  8044. case 5: // Vector3
  8045. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8046. break;
  8047. case 6: // Mesh reference
  8048. if (scene) {
  8049. dest[property] = scene.getLastMeshByID(sourceProperty);
  8050. }
  8051. break;
  8052. case 7: // Color Curves
  8053. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8054. break;
  8055. case 8: // Color 4
  8056. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8057. break;
  8058. case 9: // Image Processing
  8059. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8060. break;
  8061. case 10: // Quaternion
  8062. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8063. break;
  8064. case 11: // Camera reference
  8065. if (scene) {
  8066. dest[property] = scene.getCameraByID(sourceProperty);
  8067. }
  8068. break;
  8069. }
  8070. }
  8071. }
  8072. return destination;
  8073. };
  8074. SerializationHelper.Clone = function (creationFunction, source) {
  8075. return _copySource(creationFunction, source, false);
  8076. };
  8077. SerializationHelper.Instanciate = function (creationFunction, source) {
  8078. return _copySource(creationFunction, source, true);
  8079. };
  8080. return SerializationHelper;
  8081. }());
  8082. BABYLON.SerializationHelper = SerializationHelper;
  8083. })(BABYLON || (BABYLON = {}));
  8084. //# sourceMappingURL=babylon.decorators.js.map
  8085. var BABYLON;
  8086. (function (BABYLON) {
  8087. /**
  8088. * Wrapper class for promise with external resolve and reject.
  8089. */
  8090. var Deferred = /** @class */ (function () {
  8091. /**
  8092. * Constructor for this deferred object.
  8093. */
  8094. function Deferred() {
  8095. var _this = this;
  8096. this.promise = new Promise(function (resolve, reject) {
  8097. _this._resolve = resolve;
  8098. _this._reject = reject;
  8099. });
  8100. }
  8101. Object.defineProperty(Deferred.prototype, "resolve", {
  8102. /**
  8103. * The resolve method of the promise associated with this deferred object.
  8104. */
  8105. get: function () {
  8106. return this._resolve;
  8107. },
  8108. enumerable: true,
  8109. configurable: true
  8110. });
  8111. Object.defineProperty(Deferred.prototype, "reject", {
  8112. /**
  8113. * The reject method of the promise associated with this deferred object.
  8114. */
  8115. get: function () {
  8116. return this._reject;
  8117. },
  8118. enumerable: true,
  8119. configurable: true
  8120. });
  8121. return Deferred;
  8122. }());
  8123. BABYLON.Deferred = Deferred;
  8124. })(BABYLON || (BABYLON = {}));
  8125. //# sourceMappingURL=babylon.deferred.js.map
  8126. var BABYLON;
  8127. (function (BABYLON) {
  8128. /**
  8129. * A class serves as a medium between the observable and its observers
  8130. */
  8131. var EventState = /** @class */ (function () {
  8132. /**
  8133. * Create a new EventState
  8134. * @param mask defines the mask associated with this state
  8135. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8136. * @param target defines the original target of the state
  8137. * @param currentTarget defines the current target of the state
  8138. */
  8139. function EventState(mask, skipNextObservers, target, currentTarget) {
  8140. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8141. this.initalize(mask, skipNextObservers, target, currentTarget);
  8142. }
  8143. /**
  8144. * Initialize the current event state
  8145. * @param mask defines the mask associated with this state
  8146. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8147. * @param target defines the original target of the state
  8148. * @param currentTarget defines the current target of the state
  8149. * @returns the current event state
  8150. */
  8151. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8152. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8153. this.mask = mask;
  8154. this.skipNextObservers = skipNextObservers;
  8155. this.target = target;
  8156. this.currentTarget = currentTarget;
  8157. return this;
  8158. };
  8159. return EventState;
  8160. }());
  8161. BABYLON.EventState = EventState;
  8162. /**
  8163. * Represent an Observer registered to a given Observable object.
  8164. */
  8165. var Observer = /** @class */ (function () {
  8166. /**
  8167. * Creates a new observer
  8168. * @param callback defines the callback to call when the observer is notified
  8169. * @param mask defines the mask of the observer (used to filter notifications)
  8170. * @param scope defines the current scope used to restore the JS context
  8171. */
  8172. function Observer(
  8173. /**
  8174. * Defines the callback to call when the observer is notified
  8175. */
  8176. callback,
  8177. /**
  8178. * Defines the mask of the observer (used to filter notifications)
  8179. */
  8180. mask,
  8181. /**
  8182. * Defines the current scope used to restore the JS context
  8183. */
  8184. scope) {
  8185. if (scope === void 0) { scope = null; }
  8186. this.callback = callback;
  8187. this.mask = mask;
  8188. this.scope = scope;
  8189. /** @hidden */
  8190. this._willBeUnregistered = false;
  8191. /**
  8192. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8193. */
  8194. this.unregisterOnNextCall = false;
  8195. }
  8196. return Observer;
  8197. }());
  8198. BABYLON.Observer = Observer;
  8199. /**
  8200. * Represent a list of observers registered to multiple Observables object.
  8201. */
  8202. var MultiObserver = /** @class */ (function () {
  8203. function MultiObserver() {
  8204. }
  8205. /**
  8206. * Release associated resources
  8207. */
  8208. MultiObserver.prototype.dispose = function () {
  8209. if (this._observers && this._observables) {
  8210. for (var index = 0; index < this._observers.length; index++) {
  8211. this._observables[index].remove(this._observers[index]);
  8212. }
  8213. }
  8214. this._observers = null;
  8215. this._observables = null;
  8216. };
  8217. /**
  8218. * Raise a callback when one of the observable will notify
  8219. * @param observables defines a list of observables to watch
  8220. * @param callback defines the callback to call on notification
  8221. * @param mask defines the mask used to filter notifications
  8222. * @param scope defines the current scope used to restore the JS context
  8223. * @returns the new MultiObserver
  8224. */
  8225. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8226. if (mask === void 0) { mask = -1; }
  8227. if (scope === void 0) { scope = null; }
  8228. var result = new MultiObserver();
  8229. result._observers = new Array();
  8230. result._observables = observables;
  8231. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8232. var observable = observables_1[_i];
  8233. var observer = observable.add(callback, mask, false, scope);
  8234. if (observer) {
  8235. result._observers.push(observer);
  8236. }
  8237. }
  8238. return result;
  8239. };
  8240. return MultiObserver;
  8241. }());
  8242. BABYLON.MultiObserver = MultiObserver;
  8243. /**
  8244. * The Observable class is a simple implementation of the Observable pattern.
  8245. *
  8246. * 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.
  8247. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8248. * 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).
  8249. * 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.
  8250. */
  8251. var Observable = /** @class */ (function () {
  8252. /**
  8253. * Creates a new observable
  8254. * @param onObserverAdded defines a callback to call when a new observer is added
  8255. */
  8256. function Observable(onObserverAdded) {
  8257. this._observers = new Array();
  8258. this._eventState = new EventState(0);
  8259. if (onObserverAdded) {
  8260. this._onObserverAdded = onObserverAdded;
  8261. }
  8262. }
  8263. /**
  8264. * Create a new Observer with the specified callback
  8265. * @param callback the callback that will be executed for that Observer
  8266. * @param mask the mask used to filter observers
  8267. * @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.
  8268. * @param scope optional scope for the callback to be called from
  8269. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8270. * @returns the new observer created for the callback
  8271. */
  8272. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8273. if (mask === void 0) { mask = -1; }
  8274. if (insertFirst === void 0) { insertFirst = false; }
  8275. if (scope === void 0) { scope = null; }
  8276. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8277. if (!callback) {
  8278. return null;
  8279. }
  8280. var observer = new Observer(callback, mask, scope);
  8281. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8282. if (insertFirst) {
  8283. this._observers.unshift(observer);
  8284. }
  8285. else {
  8286. this._observers.push(observer);
  8287. }
  8288. if (this._onObserverAdded) {
  8289. this._onObserverAdded(observer);
  8290. }
  8291. return observer;
  8292. };
  8293. /**
  8294. * Create a new Observer with the specified callback and unregisters after the next notification
  8295. * @param callback the callback that will be executed for that Observer
  8296. * @returns the new observer created for the callback
  8297. */
  8298. Observable.prototype.addOnce = function (callback) {
  8299. return this.add(callback, undefined, undefined, undefined, true);
  8300. };
  8301. /**
  8302. * Remove an Observer from the Observable object
  8303. * @param observer the instance of the Observer to remove
  8304. * @returns false if it doesn't belong to this Observable
  8305. */
  8306. Observable.prototype.remove = function (observer) {
  8307. if (!observer) {
  8308. return false;
  8309. }
  8310. var index = this._observers.indexOf(observer);
  8311. if (index !== -1) {
  8312. this._deferUnregister(observer);
  8313. return true;
  8314. }
  8315. return false;
  8316. };
  8317. /**
  8318. * Remove a callback from the Observable object
  8319. * @param callback the callback to remove
  8320. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8321. * @returns false if it doesn't belong to this Observable
  8322. */
  8323. Observable.prototype.removeCallback = function (callback, scope) {
  8324. for (var index = 0; index < this._observers.length; index++) {
  8325. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8326. this._deferUnregister(this._observers[index]);
  8327. return true;
  8328. }
  8329. }
  8330. return false;
  8331. };
  8332. Observable.prototype._deferUnregister = function (observer) {
  8333. var _this = this;
  8334. observer.unregisterOnNextCall = false;
  8335. observer._willBeUnregistered = true;
  8336. BABYLON.Tools.SetImmediate(function () {
  8337. _this._remove(observer);
  8338. });
  8339. };
  8340. // This should only be called when not iterating over _observers to avoid callback skipping.
  8341. // Removes an observer from the _observer Array.
  8342. Observable.prototype._remove = function (observer) {
  8343. if (!observer) {
  8344. return false;
  8345. }
  8346. var index = this._observers.indexOf(observer);
  8347. if (index !== -1) {
  8348. this._observers.splice(index, 1);
  8349. return true;
  8350. }
  8351. return false;
  8352. };
  8353. /**
  8354. * Notify all Observers by calling their respective callback with the given data
  8355. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8356. * @param eventData defines the data to send to all observers
  8357. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8358. * @param target defines the original target of the state
  8359. * @param currentTarget defines the current target of the state
  8360. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8361. */
  8362. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8363. if (mask === void 0) { mask = -1; }
  8364. if (!this._observers.length) {
  8365. return true;
  8366. }
  8367. var state = this._eventState;
  8368. state.mask = mask;
  8369. state.target = target;
  8370. state.currentTarget = currentTarget;
  8371. state.skipNextObservers = false;
  8372. state.lastReturnValue = eventData;
  8373. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8374. var obs = _a[_i];
  8375. if (obs._willBeUnregistered) {
  8376. continue;
  8377. }
  8378. if (obs.mask & mask) {
  8379. if (obs.scope) {
  8380. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8381. }
  8382. else {
  8383. state.lastReturnValue = obs.callback(eventData, state);
  8384. }
  8385. if (obs.unregisterOnNextCall) {
  8386. this._deferUnregister(obs);
  8387. }
  8388. }
  8389. if (state.skipNextObservers) {
  8390. return false;
  8391. }
  8392. }
  8393. return true;
  8394. };
  8395. /**
  8396. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8397. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8398. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8399. * and it is crucial that all callbacks will be executed.
  8400. * The order of the callbacks is kept, callbacks are not executed parallel.
  8401. *
  8402. * @param eventData The data to be sent to each callback
  8403. * @param mask is used to filter observers defaults to -1
  8404. * @param target defines the callback target (see EventState)
  8405. * @param currentTarget defines he current object in the bubbling phase
  8406. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8407. */
  8408. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8409. var _this = this;
  8410. if (mask === void 0) { mask = -1; }
  8411. // create an empty promise
  8412. var p = Promise.resolve(eventData);
  8413. // no observers? return this promise.
  8414. if (!this._observers.length) {
  8415. return p;
  8416. }
  8417. var state = this._eventState;
  8418. state.mask = mask;
  8419. state.target = target;
  8420. state.currentTarget = currentTarget;
  8421. state.skipNextObservers = false;
  8422. // execute one callback after another (not using Promise.all, the order is important)
  8423. this._observers.forEach(function (obs) {
  8424. if (state.skipNextObservers) {
  8425. return;
  8426. }
  8427. if (obs._willBeUnregistered) {
  8428. return;
  8429. }
  8430. if (obs.mask & mask) {
  8431. if (obs.scope) {
  8432. p = p.then(function (lastReturnedValue) {
  8433. state.lastReturnValue = lastReturnedValue;
  8434. return obs.callback.apply(obs.scope, [eventData, state]);
  8435. });
  8436. }
  8437. else {
  8438. p = p.then(function (lastReturnedValue) {
  8439. state.lastReturnValue = lastReturnedValue;
  8440. return obs.callback(eventData, state);
  8441. });
  8442. }
  8443. if (obs.unregisterOnNextCall) {
  8444. _this._deferUnregister(obs);
  8445. }
  8446. }
  8447. });
  8448. // return the eventData
  8449. return p.then(function () { return eventData; });
  8450. };
  8451. /**
  8452. * Notify a specific observer
  8453. * @param observer defines the observer to notify
  8454. * @param eventData defines the data to be sent to each callback
  8455. * @param mask is used to filter observers defaults to -1
  8456. */
  8457. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8458. if (mask === void 0) { mask = -1; }
  8459. var state = this._eventState;
  8460. state.mask = mask;
  8461. state.skipNextObservers = false;
  8462. observer.callback(eventData, state);
  8463. };
  8464. /**
  8465. * Gets a boolean indicating if the observable has at least one observer
  8466. * @returns true is the Observable has at least one Observer registered
  8467. */
  8468. Observable.prototype.hasObservers = function () {
  8469. return this._observers.length > 0;
  8470. };
  8471. /**
  8472. * Clear the list of observers
  8473. */
  8474. Observable.prototype.clear = function () {
  8475. this._observers = new Array();
  8476. this._onObserverAdded = null;
  8477. };
  8478. /**
  8479. * Clone the current observable
  8480. * @returns a new observable
  8481. */
  8482. Observable.prototype.clone = function () {
  8483. var result = new Observable();
  8484. result._observers = this._observers.slice(0);
  8485. return result;
  8486. };
  8487. /**
  8488. * Does this observable handles observer registered with a given mask
  8489. * @param mask defines the mask to be tested
  8490. * @return whether or not one observer registered with the given mask is handeled
  8491. **/
  8492. Observable.prototype.hasSpecificMask = function (mask) {
  8493. if (mask === void 0) { mask = -1; }
  8494. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8495. var obs = _a[_i];
  8496. if (obs.mask & mask || obs.mask === mask) {
  8497. return true;
  8498. }
  8499. }
  8500. return false;
  8501. };
  8502. return Observable;
  8503. }());
  8504. BABYLON.Observable = Observable;
  8505. })(BABYLON || (BABYLON = {}));
  8506. //# sourceMappingURL=babylon.observable.js.map
  8507. var BABYLON;
  8508. (function (BABYLON) {
  8509. /**
  8510. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8511. */
  8512. var SmartArray = /** @class */ (function () {
  8513. /**
  8514. * Instantiates a Smart Array.
  8515. * @param capacity defines the default capacity of the array.
  8516. */
  8517. function SmartArray(capacity) {
  8518. /**
  8519. * The active length of the array.
  8520. */
  8521. this.length = 0;
  8522. this.data = new Array(capacity);
  8523. this._id = SmartArray._GlobalId++;
  8524. }
  8525. /**
  8526. * Pushes a value at the end of the active data.
  8527. * @param value defines the object to push in the array.
  8528. */
  8529. SmartArray.prototype.push = function (value) {
  8530. this.data[this.length++] = value;
  8531. if (this.length > this.data.length) {
  8532. this.data.length *= 2;
  8533. }
  8534. };
  8535. /**
  8536. * Iterates over the active data and apply the lambda to them.
  8537. * @param func defines the action to apply on each value.
  8538. */
  8539. SmartArray.prototype.forEach = function (func) {
  8540. for (var index = 0; index < this.length; index++) {
  8541. func(this.data[index]);
  8542. }
  8543. };
  8544. /**
  8545. * Sorts the full sets of data.
  8546. * @param compareFn defines the comparison function to apply.
  8547. */
  8548. SmartArray.prototype.sort = function (compareFn) {
  8549. this.data.sort(compareFn);
  8550. };
  8551. /**
  8552. * Resets the active data to an empty array.
  8553. */
  8554. SmartArray.prototype.reset = function () {
  8555. this.length = 0;
  8556. };
  8557. /**
  8558. * Releases all the data from the array as well as the array.
  8559. */
  8560. SmartArray.prototype.dispose = function () {
  8561. this.reset();
  8562. if (this.data) {
  8563. this.data.length = 0;
  8564. this.data = [];
  8565. }
  8566. };
  8567. /**
  8568. * Concats the active data with a given array.
  8569. * @param array defines the data to concatenate with.
  8570. */
  8571. SmartArray.prototype.concat = function (array) {
  8572. if (array.length === 0) {
  8573. return;
  8574. }
  8575. if (this.length + array.length > this.data.length) {
  8576. this.data.length = (this.length + array.length) * 2;
  8577. }
  8578. for (var index = 0; index < array.length; index++) {
  8579. this.data[this.length++] = (array.data || array)[index];
  8580. }
  8581. };
  8582. /**
  8583. * Returns the position of a value in the active data.
  8584. * @param value defines the value to find the index for
  8585. * @returns the index if found in the active data otherwise -1
  8586. */
  8587. SmartArray.prototype.indexOf = function (value) {
  8588. var position = this.data.indexOf(value);
  8589. if (position >= this.length) {
  8590. return -1;
  8591. }
  8592. return position;
  8593. };
  8594. /**
  8595. * Returns whether an element is part of the active data.
  8596. * @param value defines the value to look for
  8597. * @returns true if found in the active data otherwise false
  8598. */
  8599. SmartArray.prototype.contains = function (value) {
  8600. return this.indexOf(value) !== -1;
  8601. };
  8602. // Statics
  8603. SmartArray._GlobalId = 0;
  8604. return SmartArray;
  8605. }());
  8606. BABYLON.SmartArray = SmartArray;
  8607. /**
  8608. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  8609. * The data in this array can only be present once
  8610. */
  8611. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8612. __extends(SmartArrayNoDuplicate, _super);
  8613. function SmartArrayNoDuplicate() {
  8614. var _this = _super !== null && _super.apply(this, arguments) || this;
  8615. _this._duplicateId = 0;
  8616. return _this;
  8617. }
  8618. /**
  8619. * Pushes a value at the end of the active data.
  8620. * THIS DOES NOT PREVENT DUPPLICATE DATA
  8621. * @param value defines the object to push in the array.
  8622. */
  8623. SmartArrayNoDuplicate.prototype.push = function (value) {
  8624. _super.prototype.push.call(this, value);
  8625. if (!value.__smartArrayFlags) {
  8626. value.__smartArrayFlags = {};
  8627. }
  8628. value.__smartArrayFlags[this._id] = this._duplicateId;
  8629. };
  8630. /**
  8631. * Pushes a value at the end of the active data.
  8632. * If the data is already present, it won t be added again
  8633. * @param value defines the object to push in the array.
  8634. * @returns true if added false if it was already present
  8635. */
  8636. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8637. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8638. return false;
  8639. }
  8640. this.push(value);
  8641. return true;
  8642. };
  8643. /**
  8644. * Resets the active data to an empty array.
  8645. */
  8646. SmartArrayNoDuplicate.prototype.reset = function () {
  8647. _super.prototype.reset.call(this);
  8648. this._duplicateId++;
  8649. };
  8650. /**
  8651. * Concats the active data with a given array.
  8652. * This ensures no dupplicate will be present in the result.
  8653. * @param array defines the data to concatenate with.
  8654. */
  8655. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8656. if (array.length === 0) {
  8657. return;
  8658. }
  8659. if (this.length + array.length > this.data.length) {
  8660. this.data.length = (this.length + array.length) * 2;
  8661. }
  8662. for (var index = 0; index < array.length; index++) {
  8663. var item = (array.data || array)[index];
  8664. this.pushNoDuplicate(item);
  8665. }
  8666. };
  8667. return SmartArrayNoDuplicate;
  8668. }(SmartArray));
  8669. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8670. })(BABYLON || (BABYLON = {}));
  8671. //# sourceMappingURL=babylon.smartArray.js.map
  8672. var BABYLON;
  8673. (function (BABYLON) {
  8674. /** Class used to store color4 gradient */
  8675. var ColorGradient = /** @class */ (function () {
  8676. function ColorGradient() {
  8677. }
  8678. /**
  8679. * Will get a color picked randomly between color1 and color2.
  8680. * If color2 is undefined then color1 will be used
  8681. * @param result defines the target Color4 to store the result in
  8682. */
  8683. ColorGradient.prototype.getColorToRef = function (result) {
  8684. if (!this.color2) {
  8685. result.copyFrom(this.color1);
  8686. return;
  8687. }
  8688. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8689. };
  8690. return ColorGradient;
  8691. }());
  8692. BABYLON.ColorGradient = ColorGradient;
  8693. /** Class used to store color 3 gradient */
  8694. var Color3Gradient = /** @class */ (function () {
  8695. function Color3Gradient() {
  8696. }
  8697. return Color3Gradient;
  8698. }());
  8699. BABYLON.Color3Gradient = Color3Gradient;
  8700. /** Class used to store factor gradient */
  8701. var FactorGradient = /** @class */ (function () {
  8702. function FactorGradient() {
  8703. }
  8704. /**
  8705. * Will get a number picked randomly between factor1 and factor2.
  8706. * If factor2 is undefined then factor1 will be used
  8707. * @returns the picked number
  8708. */
  8709. FactorGradient.prototype.getFactor = function () {
  8710. if (this.factor2 === undefined) {
  8711. return this.factor1;
  8712. }
  8713. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8714. };
  8715. return FactorGradient;
  8716. }());
  8717. BABYLON.FactorGradient = FactorGradient;
  8718. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8719. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8720. var LoadFileError = /** @class */ (function (_super) {
  8721. __extends(LoadFileError, _super);
  8722. function LoadFileError(message, request) {
  8723. var _this = _super.call(this, message) || this;
  8724. _this.request = request;
  8725. _this.name = "LoadFileError";
  8726. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8727. return _this;
  8728. }
  8729. // Polyfill for Object.setPrototypeOf if necessary.
  8730. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8731. return LoadFileError;
  8732. }(Error));
  8733. BABYLON.LoadFileError = LoadFileError;
  8734. var RetryStrategy = /** @class */ (function () {
  8735. function RetryStrategy() {
  8736. }
  8737. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8738. if (maxRetries === void 0) { maxRetries = 3; }
  8739. if (baseInterval === void 0) { baseInterval = 500; }
  8740. return function (url, request, retryIndex) {
  8741. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8742. return -1;
  8743. }
  8744. return Math.pow(2, retryIndex) * baseInterval;
  8745. };
  8746. };
  8747. return RetryStrategy;
  8748. }());
  8749. BABYLON.RetryStrategy = RetryStrategy;
  8750. // Screenshots
  8751. var screenshotCanvas;
  8752. var cloneValue = function (source, destinationObject) {
  8753. if (!source)
  8754. return null;
  8755. if (source instanceof BABYLON.Mesh) {
  8756. return null;
  8757. }
  8758. if (source instanceof BABYLON.SubMesh) {
  8759. return source.clone(destinationObject);
  8760. }
  8761. else if (source.clone) {
  8762. return source.clone();
  8763. }
  8764. return null;
  8765. };
  8766. var Tools = /** @class */ (function () {
  8767. function Tools() {
  8768. }
  8769. /**
  8770. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8771. * @param u defines the coordinate on X axis
  8772. * @param v defines the coordinate on Y axis
  8773. * @param width defines the width of the source data
  8774. * @param height defines the height of the source data
  8775. * @param pixels defines the source byte array
  8776. * @param color defines the output color
  8777. */
  8778. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8779. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8780. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8781. var position = (wrappedU + wrappedV * width) * 4;
  8782. color.r = pixels[position] / 255;
  8783. color.g = pixels[position + 1] / 255;
  8784. color.b = pixels[position + 2] / 255;
  8785. color.a = pixels[position + 3] / 255;
  8786. };
  8787. /**
  8788. * Interpolates between a and b via alpha
  8789. * @param a The lower value (returned when alpha = 0)
  8790. * @param b The upper value (returned when alpha = 1)
  8791. * @param alpha The interpolation-factor
  8792. * @return The mixed value
  8793. */
  8794. Tools.Mix = function (a, b, alpha) {
  8795. return a * (1 - alpha) + b * alpha;
  8796. };
  8797. Tools.Instantiate = function (className) {
  8798. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8799. return Tools.RegisteredExternalClasses[className];
  8800. }
  8801. var arr = className.split(".");
  8802. var fn = (window || this);
  8803. for (var i = 0, len = arr.length; i < len; i++) {
  8804. fn = fn[arr[i]];
  8805. }
  8806. if (typeof fn !== "function") {
  8807. return null;
  8808. }
  8809. return fn;
  8810. };
  8811. /**
  8812. * Provides a slice function that will work even on IE
  8813. * @param data defines the array to slice
  8814. * @param start defines the start of the data (optional)
  8815. * @param end defines the end of the data (optional)
  8816. * @returns the new sliced array
  8817. */
  8818. Tools.Slice = function (data, start, end) {
  8819. if (data.slice) {
  8820. return data.slice(start, end);
  8821. }
  8822. return Array.prototype.slice.call(data, start, end);
  8823. };
  8824. Tools.SetImmediate = function (action) {
  8825. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8826. window.setImmediate(action);
  8827. }
  8828. else {
  8829. setTimeout(action, 1);
  8830. }
  8831. };
  8832. Tools.IsExponentOfTwo = function (value) {
  8833. var count = 1;
  8834. do {
  8835. count *= 2;
  8836. } while (count < value);
  8837. return count === value;
  8838. };
  8839. /**
  8840. * Returns the nearest 32-bit single precision float representation of a Number
  8841. * @param value A Number. If the parameter is of a different type, it will get converted
  8842. * to a number or to NaN if it cannot be converted
  8843. * @returns number
  8844. */
  8845. Tools.FloatRound = function (value) {
  8846. if (Math.fround) {
  8847. return Math.fround(value);
  8848. }
  8849. return (Tools._tmpFloatArray[0] = value);
  8850. };
  8851. /**
  8852. * Find the next highest power of two.
  8853. * @param x Number to start search from.
  8854. * @return Next highest power of two.
  8855. */
  8856. Tools.CeilingPOT = function (x) {
  8857. x--;
  8858. x |= x >> 1;
  8859. x |= x >> 2;
  8860. x |= x >> 4;
  8861. x |= x >> 8;
  8862. x |= x >> 16;
  8863. x++;
  8864. return x;
  8865. };
  8866. /**
  8867. * Find the next lowest power of two.
  8868. * @param x Number to start search from.
  8869. * @return Next lowest power of two.
  8870. */
  8871. Tools.FloorPOT = function (x) {
  8872. x = x | (x >> 1);
  8873. x = x | (x >> 2);
  8874. x = x | (x >> 4);
  8875. x = x | (x >> 8);
  8876. x = x | (x >> 16);
  8877. return x - (x >> 1);
  8878. };
  8879. /**
  8880. * Find the nearest power of two.
  8881. * @param x Number to start search from.
  8882. * @return Next nearest power of two.
  8883. */
  8884. Tools.NearestPOT = function (x) {
  8885. var c = Tools.CeilingPOT(x);
  8886. var f = Tools.FloorPOT(x);
  8887. return (c - x) > (x - f) ? f : c;
  8888. };
  8889. Tools.GetExponentOfTwo = function (value, max, mode) {
  8890. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8891. var pot;
  8892. switch (mode) {
  8893. case BABYLON.Engine.SCALEMODE_FLOOR:
  8894. pot = Tools.FloorPOT(value);
  8895. break;
  8896. case BABYLON.Engine.SCALEMODE_NEAREST:
  8897. pot = Tools.NearestPOT(value);
  8898. break;
  8899. case BABYLON.Engine.SCALEMODE_CEILING:
  8900. default:
  8901. pot = Tools.CeilingPOT(value);
  8902. break;
  8903. }
  8904. return Math.min(pot, max);
  8905. };
  8906. Tools.GetFilename = function (path) {
  8907. var index = path.lastIndexOf("/");
  8908. if (index < 0)
  8909. return path;
  8910. return path.substring(index + 1);
  8911. };
  8912. /**
  8913. * Extracts the "folder" part of a path (everything before the filename).
  8914. * @param uri The URI to extract the info from
  8915. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8916. * @returns The "folder" part of the path
  8917. */
  8918. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8919. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8920. var index = uri.lastIndexOf("/");
  8921. if (index < 0) {
  8922. if (returnUnchangedIfNoSlash) {
  8923. return uri;
  8924. }
  8925. return "";
  8926. }
  8927. return uri.substring(0, index + 1);
  8928. };
  8929. Tools.GetDOMTextContent = function (element) {
  8930. var result = "";
  8931. var child = element.firstChild;
  8932. while (child) {
  8933. if (child.nodeType === 3) {
  8934. result += child.textContent;
  8935. }
  8936. child = child.nextSibling;
  8937. }
  8938. return result;
  8939. };
  8940. Tools.ToDegrees = function (angle) {
  8941. return angle * 180 / Math.PI;
  8942. };
  8943. Tools.ToRadians = function (angle) {
  8944. return angle * Math.PI / 180;
  8945. };
  8946. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8947. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8948. var output = "";
  8949. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8950. var i = 0;
  8951. var bytes = new Uint8Array(buffer);
  8952. while (i < bytes.length) {
  8953. chr1 = bytes[i++];
  8954. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8955. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8956. enc1 = chr1 >> 2;
  8957. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8958. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8959. enc4 = chr3 & 63;
  8960. if (isNaN(chr2)) {
  8961. enc3 = enc4 = 64;
  8962. }
  8963. else if (isNaN(chr3)) {
  8964. enc4 = 64;
  8965. }
  8966. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8967. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8968. }
  8969. return "data:image/png;base64," + output;
  8970. };
  8971. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8972. if (bias === void 0) { bias = null; }
  8973. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8974. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8975. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8976. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8977. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8978. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8979. }
  8980. if (bias) {
  8981. minimum.x -= minimum.x * bias.x + bias.y;
  8982. minimum.y -= minimum.y * bias.x + bias.y;
  8983. minimum.z -= minimum.z * bias.x + bias.y;
  8984. maximum.x += maximum.x * bias.x + bias.y;
  8985. maximum.y += maximum.y * bias.x + bias.y;
  8986. maximum.z += maximum.z * bias.x + bias.y;
  8987. }
  8988. return {
  8989. minimum: minimum,
  8990. maximum: maximum
  8991. };
  8992. };
  8993. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8994. if (bias === void 0) { bias = null; }
  8995. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8996. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8997. if (!stride) {
  8998. stride = 3;
  8999. }
  9000. for (var index = start; index < start + count; index++) {
  9001. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  9002. minimum = BABYLON.Vector3.Minimize(current, minimum);
  9003. maximum = BABYLON.Vector3.Maximize(current, maximum);
  9004. }
  9005. if (bias) {
  9006. minimum.x -= minimum.x * bias.x + bias.y;
  9007. minimum.y -= minimum.y * bias.x + bias.y;
  9008. minimum.z -= minimum.z * bias.x + bias.y;
  9009. maximum.x += maximum.x * bias.x + bias.y;
  9010. maximum.y += maximum.y * bias.x + bias.y;
  9011. maximum.z += maximum.z * bias.x + bias.y;
  9012. }
  9013. return {
  9014. minimum: minimum,
  9015. maximum: maximum
  9016. };
  9017. };
  9018. Tools.Vector2ArrayFeeder = function (array) {
  9019. return function (index) {
  9020. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  9021. var length = isFloatArray ? array.length / 2 : array.length;
  9022. if (index >= length) {
  9023. return null;
  9024. }
  9025. if (isFloatArray) {
  9026. var fa = array;
  9027. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  9028. }
  9029. var a = array;
  9030. return a[index];
  9031. };
  9032. };
  9033. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  9034. if (bias === void 0) { bias = null; }
  9035. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  9036. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  9037. var i = 0;
  9038. var cur = feeder(i++);
  9039. while (cur) {
  9040. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  9041. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  9042. cur = feeder(i++);
  9043. }
  9044. if (bias) {
  9045. minimum.x -= minimum.x * bias.x + bias.y;
  9046. minimum.y -= minimum.y * bias.x + bias.y;
  9047. maximum.x += maximum.x * bias.x + bias.y;
  9048. maximum.y += maximum.y * bias.x + bias.y;
  9049. }
  9050. return {
  9051. minimum: minimum,
  9052. maximum: maximum
  9053. };
  9054. };
  9055. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9056. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9057. return null;
  9058. return Array.isArray(obj) ? obj : [obj];
  9059. };
  9060. // Misc.
  9061. Tools.GetPointerPrefix = function () {
  9062. var eventPrefix = "pointer";
  9063. // Check if pointer events are supported
  9064. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9065. eventPrefix = "mouse";
  9066. }
  9067. return eventPrefix;
  9068. };
  9069. /**
  9070. * @param func - the function to be called
  9071. * @param requester - the object that will request the next frame. Falls back to window.
  9072. */
  9073. Tools.QueueNewFrame = function (func, requester) {
  9074. if (!Tools.IsWindowObjectExist()) {
  9075. return setTimeout(func, 16);
  9076. }
  9077. if (!requester) {
  9078. requester = window;
  9079. }
  9080. if (requester.requestAnimationFrame) {
  9081. return requester.requestAnimationFrame(func);
  9082. }
  9083. else if (requester.msRequestAnimationFrame) {
  9084. return requester.msRequestAnimationFrame(func);
  9085. }
  9086. else if (requester.webkitRequestAnimationFrame) {
  9087. return requester.webkitRequestAnimationFrame(func);
  9088. }
  9089. else if (requester.mozRequestAnimationFrame) {
  9090. return requester.mozRequestAnimationFrame(func);
  9091. }
  9092. else if (requester.oRequestAnimationFrame) {
  9093. return requester.oRequestAnimationFrame(func);
  9094. }
  9095. else {
  9096. return window.setTimeout(func, 16);
  9097. }
  9098. };
  9099. Tools.RequestFullscreen = function (element) {
  9100. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9101. if (!requestFunction)
  9102. return;
  9103. requestFunction.call(element);
  9104. };
  9105. Tools.ExitFullscreen = function () {
  9106. if (document.exitFullscreen) {
  9107. document.exitFullscreen();
  9108. }
  9109. else if (document.mozCancelFullScreen) {
  9110. document.mozCancelFullScreen();
  9111. }
  9112. else if (document.webkitCancelFullScreen) {
  9113. document.webkitCancelFullScreen();
  9114. }
  9115. else if (document.msCancelFullScreen) {
  9116. document.msCancelFullScreen();
  9117. }
  9118. };
  9119. Tools.SetCorsBehavior = function (url, element) {
  9120. if (url && url.indexOf("data:") === 0) {
  9121. return;
  9122. }
  9123. if (Tools.CorsBehavior) {
  9124. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9125. element.crossOrigin = Tools.CorsBehavior;
  9126. }
  9127. else {
  9128. var result = Tools.CorsBehavior(url);
  9129. if (result) {
  9130. element.crossOrigin = result;
  9131. }
  9132. }
  9133. }
  9134. };
  9135. // External files
  9136. Tools.CleanUrl = function (url) {
  9137. url = url.replace(/#/mg, "%23");
  9138. return url;
  9139. };
  9140. /**
  9141. * Loads an image as an HTMLImageElement.
  9142. * @param input url string, ArrayBuffer, or Blob to load
  9143. * @param onLoad callback called when the image successfully loads
  9144. * @param onError callback called when the image fails to load
  9145. * @param database database for caching
  9146. * @returns the HTMLImageElement of the loaded image
  9147. */
  9148. Tools.LoadImage = function (input, onLoad, onError, database) {
  9149. var url;
  9150. var usingObjectURL = false;
  9151. if (input instanceof ArrayBuffer) {
  9152. url = URL.createObjectURL(new Blob([input]));
  9153. usingObjectURL = true;
  9154. }
  9155. else if (input instanceof Blob) {
  9156. url = URL.createObjectURL(input);
  9157. usingObjectURL = true;
  9158. }
  9159. else {
  9160. url = Tools.CleanUrl(input);
  9161. url = Tools.PreprocessUrl(input);
  9162. }
  9163. var img = new Image();
  9164. Tools.SetCorsBehavior(url, img);
  9165. var loadHandler = function () {
  9166. if (usingObjectURL && img.src) {
  9167. URL.revokeObjectURL(img.src);
  9168. }
  9169. img.removeEventListener("load", loadHandler);
  9170. img.removeEventListener("error", errorHandler);
  9171. onLoad(img);
  9172. };
  9173. var errorHandler = function (err) {
  9174. if (usingObjectURL && img.src) {
  9175. URL.revokeObjectURL(img.src);
  9176. }
  9177. img.removeEventListener("load", loadHandler);
  9178. img.removeEventListener("error", errorHandler);
  9179. Tools.Error("Error while trying to load image: " + input);
  9180. if (onError) {
  9181. onError("Error while trying to load image: " + input, err);
  9182. }
  9183. };
  9184. img.addEventListener("load", loadHandler);
  9185. img.addEventListener("error", errorHandler);
  9186. var noIndexedDB = function () {
  9187. img.src = url;
  9188. };
  9189. var loadFromIndexedDB = function () {
  9190. if (database) {
  9191. database.loadImageFromDB(url, img);
  9192. }
  9193. };
  9194. //ANY database to do!
  9195. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9196. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9197. }
  9198. else {
  9199. if (url.indexOf("file:") !== -1) {
  9200. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9201. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9202. try {
  9203. var blobURL;
  9204. try {
  9205. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9206. }
  9207. catch (ex) {
  9208. // Chrome doesn't support oneTimeOnly parameter
  9209. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9210. }
  9211. img.src = blobURL;
  9212. usingObjectURL = true;
  9213. }
  9214. catch (e) {
  9215. img.src = "";
  9216. }
  9217. return img;
  9218. }
  9219. }
  9220. noIndexedDB();
  9221. }
  9222. return img;
  9223. };
  9224. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9225. url = Tools.CleanUrl(url);
  9226. url = Tools.PreprocessUrl(url);
  9227. // If file and file input are set
  9228. if (url.indexOf("file:") !== -1) {
  9229. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9230. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9231. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9232. }
  9233. }
  9234. var loadUrl = Tools.BaseUrl + url;
  9235. var aborted = false;
  9236. var fileRequest = {
  9237. onCompleteObservable: new BABYLON.Observable(),
  9238. abort: function () { return aborted = true; },
  9239. };
  9240. var requestFile = function () {
  9241. var request = new XMLHttpRequest();
  9242. var retryHandle = null;
  9243. fileRequest.abort = function () {
  9244. aborted = true;
  9245. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9246. request.abort();
  9247. }
  9248. if (retryHandle !== null) {
  9249. clearTimeout(retryHandle);
  9250. retryHandle = null;
  9251. }
  9252. };
  9253. var retryLoop = function (retryIndex) {
  9254. request.open('GET', loadUrl, true);
  9255. if (useArrayBuffer) {
  9256. request.responseType = "arraybuffer";
  9257. }
  9258. if (onProgress) {
  9259. request.addEventListener("progress", onProgress);
  9260. }
  9261. var onLoadEnd = function () {
  9262. request.removeEventListener("loadend", onLoadEnd);
  9263. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9264. fileRequest.onCompleteObservable.clear();
  9265. };
  9266. request.addEventListener("loadend", onLoadEnd);
  9267. var onReadyStateChange = function () {
  9268. if (aborted) {
  9269. return;
  9270. }
  9271. // In case of undefined state in some browsers.
  9272. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9273. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9274. request.removeEventListener("readystatechange", onReadyStateChange);
  9275. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9276. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9277. return;
  9278. }
  9279. var retryStrategy = Tools.DefaultRetryStrategy;
  9280. if (retryStrategy) {
  9281. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9282. if (waitTime !== -1) {
  9283. // Prevent the request from completing for retry.
  9284. request.removeEventListener("loadend", onLoadEnd);
  9285. request = new XMLHttpRequest();
  9286. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9287. return;
  9288. }
  9289. }
  9290. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9291. if (onError) {
  9292. onError(request, e);
  9293. }
  9294. else {
  9295. throw e;
  9296. }
  9297. }
  9298. };
  9299. request.addEventListener("readystatechange", onReadyStateChange);
  9300. request.send();
  9301. };
  9302. retryLoop(0);
  9303. };
  9304. // Caching all files
  9305. if (database && database.enableSceneOffline) {
  9306. var noIndexedDB_1 = function (request) {
  9307. if (request && request.status > 400) {
  9308. if (onError) {
  9309. onError(request);
  9310. }
  9311. }
  9312. else {
  9313. if (!aborted) {
  9314. requestFile();
  9315. }
  9316. }
  9317. };
  9318. var loadFromIndexedDB = function () {
  9319. // TODO: database needs to support aborting and should return a IFileRequest
  9320. if (aborted) {
  9321. return;
  9322. }
  9323. if (database) {
  9324. database.loadFileFromDB(url, function (data) {
  9325. if (!aborted) {
  9326. onSuccess(data);
  9327. }
  9328. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9329. }, onProgress ? function (event) {
  9330. if (!aborted) {
  9331. onProgress(event);
  9332. }
  9333. } : undefined, noIndexedDB_1, useArrayBuffer);
  9334. }
  9335. };
  9336. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9337. }
  9338. else {
  9339. requestFile();
  9340. }
  9341. return fileRequest;
  9342. };
  9343. /**
  9344. * Load a script (identified by an url). When the url returns, the
  9345. * content of this file is added into a new script element, attached to the DOM (body element)
  9346. */
  9347. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9348. if (!Tools.IsWindowObjectExist()) {
  9349. return;
  9350. }
  9351. var head = document.getElementsByTagName('head')[0];
  9352. var script = document.createElement('script');
  9353. script.type = 'text/javascript';
  9354. script.src = scriptUrl;
  9355. script.onload = function () {
  9356. if (onSuccess) {
  9357. onSuccess();
  9358. }
  9359. };
  9360. script.onerror = function (e) {
  9361. if (onError) {
  9362. onError("Unable to load script '" + scriptUrl + "'", e);
  9363. }
  9364. };
  9365. head.appendChild(script);
  9366. };
  9367. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9368. var reader = new FileReader();
  9369. var request = {
  9370. onCompleteObservable: new BABYLON.Observable(),
  9371. abort: function () { return reader.abort(); },
  9372. };
  9373. reader.onloadend = function (e) {
  9374. request.onCompleteObservable.notifyObservers(request);
  9375. };
  9376. reader.onload = function (e) {
  9377. //target doesn't have result from ts 1.3
  9378. callback(e.target['result']);
  9379. };
  9380. reader.onprogress = progressCallback;
  9381. reader.readAsDataURL(fileToLoad);
  9382. return request;
  9383. };
  9384. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9385. var reader = new FileReader();
  9386. var request = {
  9387. onCompleteObservable: new BABYLON.Observable(),
  9388. abort: function () { return reader.abort(); },
  9389. };
  9390. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9391. reader.onerror = function (e) {
  9392. Tools.Log("Error while reading file: " + fileToLoad.name);
  9393. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9394. };
  9395. reader.onload = function (e) {
  9396. //target doesn't have result from ts 1.3
  9397. callback(e.target['result']);
  9398. };
  9399. if (progressCallBack) {
  9400. reader.onprogress = progressCallBack;
  9401. }
  9402. if (!useArrayBuffer) {
  9403. // Asynchronous read
  9404. reader.readAsText(fileToLoad);
  9405. }
  9406. else {
  9407. reader.readAsArrayBuffer(fileToLoad);
  9408. }
  9409. return request;
  9410. };
  9411. //returns a downloadable url to a file content.
  9412. Tools.FileAsURL = function (content) {
  9413. var fileBlob = new Blob([content]);
  9414. var url = window.URL || window.webkitURL;
  9415. var link = url.createObjectURL(fileBlob);
  9416. return link;
  9417. };
  9418. // Misc.
  9419. Tools.Format = function (value, decimals) {
  9420. if (decimals === void 0) { decimals = 2; }
  9421. return value.toFixed(decimals);
  9422. };
  9423. Tools.CheckExtends = function (v, min, max) {
  9424. if (v.x < min.x)
  9425. min.x = v.x;
  9426. if (v.y < min.y)
  9427. min.y = v.y;
  9428. if (v.z < min.z)
  9429. min.z = v.z;
  9430. if (v.x > max.x)
  9431. max.x = v.x;
  9432. if (v.y > max.y)
  9433. max.y = v.y;
  9434. if (v.z > max.z)
  9435. max.z = v.z;
  9436. };
  9437. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9438. for (var prop in source) {
  9439. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9440. continue;
  9441. }
  9442. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9443. continue;
  9444. }
  9445. var sourceValue = source[prop];
  9446. var typeOfSourceValue = typeof sourceValue;
  9447. if (typeOfSourceValue === "function") {
  9448. continue;
  9449. }
  9450. try {
  9451. if (typeOfSourceValue === "object") {
  9452. if (sourceValue instanceof Array) {
  9453. destination[prop] = [];
  9454. if (sourceValue.length > 0) {
  9455. if (typeof sourceValue[0] == "object") {
  9456. for (var index = 0; index < sourceValue.length; index++) {
  9457. var clonedValue = cloneValue(sourceValue[index], destination);
  9458. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9459. destination[prop].push(clonedValue);
  9460. }
  9461. }
  9462. }
  9463. else {
  9464. destination[prop] = sourceValue.slice(0);
  9465. }
  9466. }
  9467. }
  9468. else {
  9469. destination[prop] = cloneValue(sourceValue, destination);
  9470. }
  9471. }
  9472. else {
  9473. destination[prop] = sourceValue;
  9474. }
  9475. }
  9476. catch (e) {
  9477. // Just ignore error (it could be because of a read-only property)
  9478. }
  9479. }
  9480. };
  9481. Tools.IsEmpty = function (obj) {
  9482. for (var i in obj) {
  9483. if (obj.hasOwnProperty(i)) {
  9484. return false;
  9485. }
  9486. }
  9487. return true;
  9488. };
  9489. Tools.RegisterTopRootEvents = function (events) {
  9490. for (var index = 0; index < events.length; index++) {
  9491. var event = events[index];
  9492. window.addEventListener(event.name, event.handler, false);
  9493. try {
  9494. if (window.parent) {
  9495. window.parent.addEventListener(event.name, event.handler, false);
  9496. }
  9497. }
  9498. catch (e) {
  9499. // Silently fails...
  9500. }
  9501. }
  9502. };
  9503. Tools.UnregisterTopRootEvents = function (events) {
  9504. for (var index = 0; index < events.length; index++) {
  9505. var event = events[index];
  9506. window.removeEventListener(event.name, event.handler);
  9507. try {
  9508. if (window.parent) {
  9509. window.parent.removeEventListener(event.name, event.handler);
  9510. }
  9511. }
  9512. catch (e) {
  9513. // Silently fails...
  9514. }
  9515. }
  9516. };
  9517. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9518. if (mimeType === void 0) { mimeType = "image/png"; }
  9519. // Read the contents of the framebuffer
  9520. var numberOfChannelsByLine = width * 4;
  9521. var halfHeight = height / 2;
  9522. //Reading datas from WebGL
  9523. var data = engine.readPixels(0, 0, width, height);
  9524. //To flip image on Y axis.
  9525. for (var i = 0; i < halfHeight; i++) {
  9526. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9527. var currentCell = j + i * numberOfChannelsByLine;
  9528. var targetLine = height - i - 1;
  9529. var targetCell = j + targetLine * numberOfChannelsByLine;
  9530. var temp = data[currentCell];
  9531. data[currentCell] = data[targetCell];
  9532. data[targetCell] = temp;
  9533. }
  9534. }
  9535. // Create a 2D canvas to store the result
  9536. if (!screenshotCanvas) {
  9537. screenshotCanvas = document.createElement('canvas');
  9538. }
  9539. screenshotCanvas.width = width;
  9540. screenshotCanvas.height = height;
  9541. var context = screenshotCanvas.getContext('2d');
  9542. if (context) {
  9543. // Copy the pixels to a 2D canvas
  9544. var imageData = context.createImageData(width, height);
  9545. var castData = (imageData.data);
  9546. castData.set(data);
  9547. context.putImageData(imageData, 0, 0);
  9548. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9549. }
  9550. };
  9551. /**
  9552. * Converts the canvas data to blob.
  9553. * This acts as a polyfill for browsers not supporting the to blob function.
  9554. * @param canvas Defines the canvas to extract the data from
  9555. * @param successCallback Defines the callback triggered once the data are available
  9556. * @param mimeType Defines the mime type of the result
  9557. */
  9558. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9559. if (mimeType === void 0) { mimeType = "image/png"; }
  9560. // We need HTMLCanvasElement.toBlob for HD screenshots
  9561. if (!canvas.toBlob) {
  9562. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9563. canvas.toBlob = function (callback, type, quality) {
  9564. var _this = this;
  9565. setTimeout(function () {
  9566. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9567. for (var i = 0; i < len; i++) {
  9568. arr[i] = binStr.charCodeAt(i);
  9569. }
  9570. callback(new Blob([arr]));
  9571. });
  9572. };
  9573. }
  9574. canvas.toBlob(function (blob) {
  9575. successCallback(blob);
  9576. }, mimeType);
  9577. };
  9578. /**
  9579. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9580. * @param successCallback Defines the callback triggered once the data are available
  9581. * @param mimeType Defines the mime type of the result
  9582. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9583. */
  9584. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9585. if (mimeType === void 0) { mimeType = "image/png"; }
  9586. if (successCallback) {
  9587. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9588. successCallback(base64Image);
  9589. }
  9590. else {
  9591. this.ToBlob(screenshotCanvas, function (blob) {
  9592. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9593. if (("download" in document.createElement("a"))) {
  9594. if (!fileName) {
  9595. var date = new Date();
  9596. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9597. fileName = "screenshot_" + stringDate + ".png";
  9598. }
  9599. Tools.Download(blob, fileName);
  9600. }
  9601. else {
  9602. var url = URL.createObjectURL(blob);
  9603. var newWindow = window.open("");
  9604. if (!newWindow)
  9605. return;
  9606. var img = newWindow.document.createElement("img");
  9607. img.onload = function () {
  9608. // no longer need to read the blob so it's revoked
  9609. URL.revokeObjectURL(url);
  9610. };
  9611. img.src = url;
  9612. newWindow.document.body.appendChild(img);
  9613. }
  9614. }, mimeType);
  9615. }
  9616. };
  9617. /**
  9618. * Downloads a blob in the browser
  9619. * @param blob defines the blob to download
  9620. * @param fileName defines the name of the downloaded file
  9621. */
  9622. Tools.Download = function (blob, fileName) {
  9623. if (navigator && navigator.msSaveBlob) {
  9624. navigator.msSaveBlob(blob, fileName);
  9625. return;
  9626. }
  9627. var url = window.URL.createObjectURL(blob);
  9628. var a = document.createElement("a");
  9629. document.body.appendChild(a);
  9630. a.style.display = "none";
  9631. a.href = url;
  9632. a.download = fileName;
  9633. a.addEventListener("click", function () {
  9634. if (a.parentElement) {
  9635. a.parentElement.removeChild(a);
  9636. }
  9637. });
  9638. a.click();
  9639. window.URL.revokeObjectURL(url);
  9640. };
  9641. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9642. if (mimeType === void 0) { mimeType = "image/png"; }
  9643. var width;
  9644. var height;
  9645. // If a precision value is specified
  9646. if (size.precision) {
  9647. width = Math.round(engine.getRenderWidth() * size.precision);
  9648. height = Math.round(width / engine.getAspectRatio(camera));
  9649. }
  9650. else if (size.width && size.height) {
  9651. width = size.width;
  9652. height = size.height;
  9653. }
  9654. //If passing only width, computing height to keep display canvas ratio.
  9655. else if (size.width && !size.height) {
  9656. width = size.width;
  9657. height = Math.round(width / engine.getAspectRatio(camera));
  9658. }
  9659. //If passing only height, computing width to keep display canvas ratio.
  9660. else if (size.height && !size.width) {
  9661. height = size.height;
  9662. width = Math.round(height * engine.getAspectRatio(camera));
  9663. }
  9664. //Assuming here that "size" parameter is a number
  9665. else if (!isNaN(size)) {
  9666. height = size;
  9667. width = size;
  9668. }
  9669. else {
  9670. Tools.Error("Invalid 'size' parameter !");
  9671. return;
  9672. }
  9673. if (!screenshotCanvas) {
  9674. screenshotCanvas = document.createElement('canvas');
  9675. }
  9676. screenshotCanvas.width = width;
  9677. screenshotCanvas.height = height;
  9678. var renderContext = screenshotCanvas.getContext("2d");
  9679. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9680. var newWidth = width;
  9681. var newHeight = newWidth / ratio;
  9682. if (newHeight > height) {
  9683. newHeight = height;
  9684. newWidth = newHeight * ratio;
  9685. }
  9686. var offsetX = Math.max(0, width - newWidth) / 2;
  9687. var offsetY = Math.max(0, height - newHeight) / 2;
  9688. var renderingCanvas = engine.getRenderingCanvas();
  9689. if (renderContext && renderingCanvas) {
  9690. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9691. }
  9692. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9693. };
  9694. /**
  9695. * Generates an image screenshot from the specified camera.
  9696. *
  9697. * @param engine The engine to use for rendering
  9698. * @param camera The camera to use for rendering
  9699. * @param size This parameter can be set to a single number or to an object with the
  9700. * following (optional) properties: precision, width, height. If a single number is passed,
  9701. * it will be used for both width and height. If an object is passed, the screenshot size
  9702. * will be derived from the parameters. The precision property is a multiplier allowing
  9703. * rendering at a higher or lower resolution.
  9704. * @param successCallback The callback receives a single parameter which contains the
  9705. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9706. * src parameter of an <img> to display it.
  9707. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9708. * Check your browser for supported MIME types.
  9709. * @param samples Texture samples (default: 1)
  9710. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9711. * @param fileName A name for for the downloaded file.
  9712. * @constructor
  9713. */
  9714. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9715. if (mimeType === void 0) { mimeType = "image/png"; }
  9716. if (samples === void 0) { samples = 1; }
  9717. if (antialiasing === void 0) { antialiasing = false; }
  9718. var width;
  9719. var height;
  9720. //If a precision value is specified
  9721. if (size.precision) {
  9722. width = Math.round(engine.getRenderWidth() * size.precision);
  9723. height = Math.round(width / engine.getAspectRatio(camera));
  9724. size = { width: width, height: height };
  9725. }
  9726. else if (size.width && size.height) {
  9727. width = size.width;
  9728. height = size.height;
  9729. }
  9730. //If passing only width, computing height to keep display canvas ratio.
  9731. else if (size.width && !size.height) {
  9732. width = size.width;
  9733. height = Math.round(width / engine.getAspectRatio(camera));
  9734. size = { width: width, height: height };
  9735. }
  9736. //If passing only height, computing width to keep display canvas ratio.
  9737. else if (size.height && !size.width) {
  9738. height = size.height;
  9739. width = Math.round(height * engine.getAspectRatio(camera));
  9740. size = { width: width, height: height };
  9741. }
  9742. //Assuming here that "size" parameter is a number
  9743. else if (!isNaN(size)) {
  9744. height = size;
  9745. width = size;
  9746. }
  9747. else {
  9748. Tools.Error("Invalid 'size' parameter !");
  9749. return;
  9750. }
  9751. var scene = camera.getScene();
  9752. var previousCamera = null;
  9753. if (scene.activeCamera !== camera) {
  9754. previousCamera = scene.activeCamera;
  9755. scene.activeCamera = camera;
  9756. }
  9757. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9758. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9759. texture.renderList = null;
  9760. texture.samples = samples;
  9761. if (antialiasing) {
  9762. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9763. }
  9764. texture.onAfterRenderObservable.add(function () {
  9765. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9766. });
  9767. scene.incrementRenderId();
  9768. scene.resetCachedMaterial();
  9769. texture.render(true);
  9770. texture.dispose();
  9771. if (previousCamera) {
  9772. scene.activeCamera = previousCamera;
  9773. }
  9774. camera.getProjectionMatrix(true); // Force cache refresh;
  9775. };
  9776. // XHR response validator for local file scenario
  9777. Tools.ValidateXHRData = function (xhr, dataType) {
  9778. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9779. if (dataType === void 0) { dataType = 7; }
  9780. try {
  9781. if (dataType & 1) {
  9782. if (xhr.responseText && xhr.responseText.length > 0) {
  9783. return true;
  9784. }
  9785. else if (dataType === 1) {
  9786. return false;
  9787. }
  9788. }
  9789. if (dataType & 2) {
  9790. // Check header width and height since there is no "TGA" magic number
  9791. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9792. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9793. return true;
  9794. }
  9795. else if (dataType === 2) {
  9796. return false;
  9797. }
  9798. }
  9799. if (dataType & 4) {
  9800. // Check for the "DDS" magic number
  9801. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9802. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9803. return true;
  9804. }
  9805. else {
  9806. return false;
  9807. }
  9808. }
  9809. }
  9810. catch (e) {
  9811. // Global protection
  9812. }
  9813. return false;
  9814. };
  9815. /**
  9816. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9817. * Be aware Math.random() could cause collisions, but:
  9818. * "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"
  9819. */
  9820. Tools.RandomId = function () {
  9821. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9822. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9823. return v.toString(16);
  9824. });
  9825. };
  9826. /**
  9827. * Test if the given uri is a base64 string.
  9828. * @param uri The uri to test
  9829. * @return True if the uri is a base64 string or false otherwise.
  9830. */
  9831. Tools.IsBase64 = function (uri) {
  9832. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9833. };
  9834. /**
  9835. * Decode the given base64 uri.
  9836. * @param uri The uri to decode
  9837. * @return The decoded base64 data.
  9838. */
  9839. Tools.DecodeBase64 = function (uri) {
  9840. var decodedString = atob(uri.split(",")[1]);
  9841. var bufferLength = decodedString.length;
  9842. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9843. for (var i = 0; i < bufferLength; i++) {
  9844. bufferView[i] = decodedString.charCodeAt(i);
  9845. }
  9846. return bufferView.buffer;
  9847. };
  9848. Object.defineProperty(Tools, "NoneLogLevel", {
  9849. get: function () {
  9850. return Tools._NoneLogLevel;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(Tools, "MessageLogLevel", {
  9856. get: function () {
  9857. return Tools._MessageLogLevel;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(Tools, "WarningLogLevel", {
  9863. get: function () {
  9864. return Tools._WarningLogLevel;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(Tools, "ErrorLogLevel", {
  9870. get: function () {
  9871. return Tools._ErrorLogLevel;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(Tools, "AllLogLevel", {
  9877. get: function () {
  9878. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Tools._AddLogEntry = function (entry) {
  9884. Tools._LogCache = entry + Tools._LogCache;
  9885. if (Tools.OnNewCacheEntry) {
  9886. Tools.OnNewCacheEntry(entry);
  9887. }
  9888. };
  9889. Tools._FormatMessage = function (message) {
  9890. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9891. var date = new Date();
  9892. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9893. };
  9894. Tools._LogDisabled = function (message) {
  9895. // nothing to do
  9896. };
  9897. Tools._LogEnabled = function (message) {
  9898. var formattedMessage = Tools._FormatMessage(message);
  9899. console.log("BJS - " + formattedMessage);
  9900. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9901. Tools._AddLogEntry(entry);
  9902. };
  9903. Tools._WarnDisabled = function (message) {
  9904. // nothing to do
  9905. };
  9906. Tools._WarnEnabled = function (message) {
  9907. var formattedMessage = Tools._FormatMessage(message);
  9908. console.warn("BJS - " + formattedMessage);
  9909. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9910. Tools._AddLogEntry(entry);
  9911. };
  9912. Tools._ErrorDisabled = function (message) {
  9913. // nothing to do
  9914. };
  9915. Tools._ErrorEnabled = function (message) {
  9916. Tools.errorsCount++;
  9917. var formattedMessage = Tools._FormatMessage(message);
  9918. console.error("BJS - " + formattedMessage);
  9919. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9920. Tools._AddLogEntry(entry);
  9921. };
  9922. Object.defineProperty(Tools, "LogCache", {
  9923. get: function () {
  9924. return Tools._LogCache;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Tools.ClearLogCache = function () {
  9930. Tools._LogCache = "";
  9931. Tools.errorsCount = 0;
  9932. };
  9933. Object.defineProperty(Tools, "LogLevels", {
  9934. set: function (level) {
  9935. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9936. Tools.Log = Tools._LogEnabled;
  9937. }
  9938. else {
  9939. Tools.Log = Tools._LogDisabled;
  9940. }
  9941. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9942. Tools.Warn = Tools._WarnEnabled;
  9943. }
  9944. else {
  9945. Tools.Warn = Tools._WarnDisabled;
  9946. }
  9947. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9948. Tools.Error = Tools._ErrorEnabled;
  9949. }
  9950. else {
  9951. Tools.Error = Tools._ErrorDisabled;
  9952. }
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. /**
  9958. * Check if the loaded document was accessed via `file:`-Protocol.
  9959. * @returns boolean
  9960. */
  9961. Tools.IsFileURL = function () {
  9962. return location.protocol === "file:";
  9963. };
  9964. Tools.IsWindowObjectExist = function () {
  9965. return (typeof window) !== "undefined";
  9966. };
  9967. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9968. get: function () {
  9969. return Tools._PerformanceNoneLogLevel;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9975. get: function () {
  9976. return Tools._PerformanceUserMarkLogLevel;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9982. get: function () {
  9983. return Tools._PerformanceConsoleLogLevel;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9989. set: function (level) {
  9990. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9991. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9992. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9993. return;
  9994. }
  9995. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9996. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9997. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9998. return;
  9999. }
  10000. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10001. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10002. },
  10003. enumerable: true,
  10004. configurable: true
  10005. });
  10006. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10007. };
  10008. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10009. };
  10010. Tools._StartUserMark = function (counterName, condition) {
  10011. if (condition === void 0) { condition = true; }
  10012. if (!Tools._performance) {
  10013. if (!Tools.IsWindowObjectExist()) {
  10014. return;
  10015. }
  10016. Tools._performance = window.performance;
  10017. }
  10018. if (!condition || !Tools._performance.mark) {
  10019. return;
  10020. }
  10021. Tools._performance.mark(counterName + "-Begin");
  10022. };
  10023. Tools._EndUserMark = function (counterName, condition) {
  10024. if (condition === void 0) { condition = true; }
  10025. if (!condition || !Tools._performance.mark) {
  10026. return;
  10027. }
  10028. Tools._performance.mark(counterName + "-End");
  10029. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10030. };
  10031. Tools._StartPerformanceConsole = function (counterName, condition) {
  10032. if (condition === void 0) { condition = true; }
  10033. if (!condition) {
  10034. return;
  10035. }
  10036. Tools._StartUserMark(counterName, condition);
  10037. if (console.time) {
  10038. console.time(counterName);
  10039. }
  10040. };
  10041. Tools._EndPerformanceConsole = function (counterName, condition) {
  10042. if (condition === void 0) { condition = true; }
  10043. if (!condition) {
  10044. return;
  10045. }
  10046. Tools._EndUserMark(counterName, condition);
  10047. if (console.time) {
  10048. console.timeEnd(counterName);
  10049. }
  10050. };
  10051. Object.defineProperty(Tools, "Now", {
  10052. get: function () {
  10053. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10054. return window.performance.now();
  10055. }
  10056. return Date.now();
  10057. },
  10058. enumerable: true,
  10059. configurable: true
  10060. });
  10061. /**
  10062. * This method will return the name of the class used to create the instance of the given object.
  10063. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10064. * @param object the object to get the class name from
  10065. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  10066. */
  10067. Tools.GetClassName = function (object, isType) {
  10068. if (isType === void 0) { isType = false; }
  10069. var name = null;
  10070. if (!isType && object.getClassName) {
  10071. name = object.getClassName();
  10072. }
  10073. else {
  10074. if (object instanceof Object) {
  10075. var classObj = isType ? object : Object.getPrototypeOf(object);
  10076. name = classObj.constructor["__bjsclassName__"];
  10077. }
  10078. if (!name) {
  10079. name = typeof object;
  10080. }
  10081. }
  10082. return name;
  10083. };
  10084. Tools.First = function (array, predicate) {
  10085. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10086. var el = array_1[_i];
  10087. if (predicate(el)) {
  10088. return el;
  10089. }
  10090. }
  10091. return null;
  10092. };
  10093. /**
  10094. * This method will return the name of the full name of the class, including its owning module (if any).
  10095. * 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).
  10096. * @param object the object to get the class name from
  10097. * @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.
  10098. */
  10099. Tools.getFullClassName = function (object, isType) {
  10100. if (isType === void 0) { isType = false; }
  10101. var className = null;
  10102. var moduleName = null;
  10103. if (!isType && object.getClassName) {
  10104. className = object.getClassName();
  10105. }
  10106. else {
  10107. if (object instanceof Object) {
  10108. var classObj = isType ? object : Object.getPrototypeOf(object);
  10109. className = classObj.constructor["__bjsclassName__"];
  10110. moduleName = classObj.constructor["__bjsmoduleName__"];
  10111. }
  10112. if (!className) {
  10113. className = typeof object;
  10114. }
  10115. }
  10116. if (!className) {
  10117. return null;
  10118. }
  10119. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10120. };
  10121. /**
  10122. * 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.
  10123. * @param array
  10124. */
  10125. Tools.arrayOrStringFeeder = function (array) {
  10126. return function (index) {
  10127. if (index >= array.length) {
  10128. return null;
  10129. }
  10130. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10131. if (val && val.getHashCode) {
  10132. val = val.getHashCode();
  10133. }
  10134. if (typeof val === "string") {
  10135. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10136. }
  10137. return val;
  10138. };
  10139. };
  10140. /**
  10141. * Compute the hashCode of a stream of number
  10142. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10143. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10144. * @return the hash code computed
  10145. */
  10146. Tools.hashCodeFromStream = function (feeder) {
  10147. // Based from here: http://stackoverflow.com/a/7616484/802124
  10148. var hash = 0;
  10149. var index = 0;
  10150. var chr = feeder(index++);
  10151. while (chr != null) {
  10152. hash = ((hash << 5) - hash) + chr;
  10153. hash |= 0; // Convert to 32bit integer
  10154. chr = feeder(index++);
  10155. }
  10156. return hash;
  10157. };
  10158. /**
  10159. * Returns a promise that resolves after the given amount of time.
  10160. * @param delay Number of milliseconds to delay
  10161. * @returns Promise that resolves after the given amount of time
  10162. */
  10163. Tools.DelayAsync = function (delay) {
  10164. return new Promise(function (resolve) {
  10165. setTimeout(function () {
  10166. resolve();
  10167. }, delay);
  10168. });
  10169. };
  10170. /**
  10171. * Gets the current gradient from an array of IValueGradient
  10172. * @param ratio defines the current ratio to get
  10173. * @param gradients defines the array of IValueGradient
  10174. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10175. */
  10176. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10177. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10178. var currentGradient = gradients[gradientIndex];
  10179. var nextGradient = gradients[gradientIndex + 1];
  10180. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10181. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10182. updateFunc(currentGradient, nextGradient, scale);
  10183. return;
  10184. }
  10185. }
  10186. // Use last index if over
  10187. var lastIndex = gradients.length - 1;
  10188. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10189. };
  10190. Tools.BaseUrl = "";
  10191. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10192. /**
  10193. * Default behaviour for cors in the application.
  10194. * It can be a string if the expected behavior is identical in the entire app.
  10195. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10196. */
  10197. Tools.CorsBehavior = "anonymous";
  10198. Tools.UseFallbackTexture = true;
  10199. /**
  10200. * Use this object to register external classes like custom textures or material
  10201. * to allow the laoders to instantiate them
  10202. */
  10203. Tools.RegisteredExternalClasses = {};
  10204. // Used in case of a texture loading problem
  10205. 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";
  10206. Tools._tmpFloatArray = new Float32Array(1);
  10207. Tools.PreprocessUrl = function (url) {
  10208. return url;
  10209. };
  10210. // Logs
  10211. Tools._NoneLogLevel = 0;
  10212. Tools._MessageLogLevel = 1;
  10213. Tools._WarningLogLevel = 2;
  10214. Tools._ErrorLogLevel = 4;
  10215. Tools._LogCache = "";
  10216. Tools.errorsCount = 0;
  10217. Tools.Log = Tools._LogEnabled;
  10218. Tools.Warn = Tools._WarnEnabled;
  10219. Tools.Error = Tools._ErrorEnabled;
  10220. // Performances
  10221. Tools._PerformanceNoneLogLevel = 0;
  10222. Tools._PerformanceUserMarkLogLevel = 1;
  10223. Tools._PerformanceConsoleLogLevel = 2;
  10224. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10225. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10226. return Tools;
  10227. }());
  10228. BABYLON.Tools = Tools;
  10229. /**
  10230. * This class is used to track a performance counter which is number based.
  10231. * The user has access to many properties which give statistics of different nature
  10232. *
  10233. * The implementer can track two kinds of Performance Counter: time and count
  10234. * 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.
  10235. * 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.
  10236. */
  10237. var PerfCounter = /** @class */ (function () {
  10238. function PerfCounter() {
  10239. this._startMonitoringTime = 0;
  10240. this._min = 0;
  10241. this._max = 0;
  10242. this._average = 0;
  10243. this._lastSecAverage = 0;
  10244. this._current = 0;
  10245. this._totalValueCount = 0;
  10246. this._totalAccumulated = 0;
  10247. this._lastSecAccumulated = 0;
  10248. this._lastSecTime = 0;
  10249. this._lastSecValueCount = 0;
  10250. }
  10251. Object.defineProperty(PerfCounter.prototype, "min", {
  10252. /**
  10253. * Returns the smallest value ever
  10254. */
  10255. get: function () {
  10256. return this._min;
  10257. },
  10258. enumerable: true,
  10259. configurable: true
  10260. });
  10261. Object.defineProperty(PerfCounter.prototype, "max", {
  10262. /**
  10263. * Returns the biggest value ever
  10264. */
  10265. get: function () {
  10266. return this._max;
  10267. },
  10268. enumerable: true,
  10269. configurable: true
  10270. });
  10271. Object.defineProperty(PerfCounter.prototype, "average", {
  10272. /**
  10273. * Returns the average value since the performance counter is running
  10274. */
  10275. get: function () {
  10276. return this._average;
  10277. },
  10278. enumerable: true,
  10279. configurable: true
  10280. });
  10281. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10282. /**
  10283. * Returns the average value of the last second the counter was monitored
  10284. */
  10285. get: function () {
  10286. return this._lastSecAverage;
  10287. },
  10288. enumerable: true,
  10289. configurable: true
  10290. });
  10291. Object.defineProperty(PerfCounter.prototype, "current", {
  10292. /**
  10293. * Returns the current value
  10294. */
  10295. get: function () {
  10296. return this._current;
  10297. },
  10298. enumerable: true,
  10299. configurable: true
  10300. });
  10301. Object.defineProperty(PerfCounter.prototype, "total", {
  10302. get: function () {
  10303. return this._totalAccumulated;
  10304. },
  10305. enumerable: true,
  10306. configurable: true
  10307. });
  10308. Object.defineProperty(PerfCounter.prototype, "count", {
  10309. get: function () {
  10310. return this._totalValueCount;
  10311. },
  10312. enumerable: true,
  10313. configurable: true
  10314. });
  10315. /**
  10316. * Call this method to start monitoring a new frame.
  10317. * 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.
  10318. */
  10319. PerfCounter.prototype.fetchNewFrame = function () {
  10320. this._totalValueCount++;
  10321. this._current = 0;
  10322. this._lastSecValueCount++;
  10323. };
  10324. /**
  10325. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10326. * @param newCount the count value to add to the monitored count
  10327. * @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.
  10328. */
  10329. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10330. if (!PerfCounter.Enabled) {
  10331. return;
  10332. }
  10333. this._current += newCount;
  10334. if (fetchResult) {
  10335. this._fetchResult();
  10336. }
  10337. };
  10338. /**
  10339. * Start monitoring this performance counter
  10340. */
  10341. PerfCounter.prototype.beginMonitoring = function () {
  10342. if (!PerfCounter.Enabled) {
  10343. return;
  10344. }
  10345. this._startMonitoringTime = Tools.Now;
  10346. };
  10347. /**
  10348. * Compute the time lapsed since the previous beginMonitoring() call.
  10349. * @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
  10350. */
  10351. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10352. if (newFrame === void 0) { newFrame = true; }
  10353. if (!PerfCounter.Enabled) {
  10354. return;
  10355. }
  10356. if (newFrame) {
  10357. this.fetchNewFrame();
  10358. }
  10359. var currentTime = Tools.Now;
  10360. this._current = currentTime - this._startMonitoringTime;
  10361. if (newFrame) {
  10362. this._fetchResult();
  10363. }
  10364. };
  10365. PerfCounter.prototype._fetchResult = function () {
  10366. this._totalAccumulated += this._current;
  10367. this._lastSecAccumulated += this._current;
  10368. // Min/Max update
  10369. this._min = Math.min(this._min, this._current);
  10370. this._max = Math.max(this._max, this._current);
  10371. this._average = this._totalAccumulated / this._totalValueCount;
  10372. // Reset last sec?
  10373. var now = Tools.Now;
  10374. if ((now - this._lastSecTime) > 1000) {
  10375. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10376. this._lastSecTime = now;
  10377. this._lastSecAccumulated = 0;
  10378. this._lastSecValueCount = 0;
  10379. }
  10380. };
  10381. PerfCounter.Enabled = true;
  10382. return PerfCounter;
  10383. }());
  10384. BABYLON.PerfCounter = PerfCounter;
  10385. /**
  10386. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10387. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10388. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10389. * @param name The name of the class, case should be preserved
  10390. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10391. */
  10392. function className(name, module) {
  10393. return function (target) {
  10394. target["__bjsclassName__"] = name;
  10395. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10396. };
  10397. }
  10398. BABYLON.className = className;
  10399. /**
  10400. * An implementation of a loop for asynchronous functions.
  10401. */
  10402. var AsyncLoop = /** @class */ (function () {
  10403. /**
  10404. * Constructor.
  10405. * @param iterations the number of iterations.
  10406. * @param func the function to run each iteration
  10407. * @param successCallback the callback that will be called upon succesful execution
  10408. * @param offset starting offset.
  10409. */
  10410. function AsyncLoop(
  10411. /**
  10412. * Defines the number of iterations for the loop
  10413. */
  10414. iterations, func, successCallback, offset) {
  10415. if (offset === void 0) { offset = 0; }
  10416. this.iterations = iterations;
  10417. this.index = offset - 1;
  10418. this._done = false;
  10419. this._fn = func;
  10420. this._successCallback = successCallback;
  10421. }
  10422. /**
  10423. * Execute the next iteration. Must be called after the last iteration was finished.
  10424. */
  10425. AsyncLoop.prototype.executeNext = function () {
  10426. if (!this._done) {
  10427. if (this.index + 1 < this.iterations) {
  10428. ++this.index;
  10429. this._fn(this);
  10430. }
  10431. else {
  10432. this.breakLoop();
  10433. }
  10434. }
  10435. };
  10436. /**
  10437. * Break the loop and run the success callback.
  10438. */
  10439. AsyncLoop.prototype.breakLoop = function () {
  10440. this._done = true;
  10441. this._successCallback();
  10442. };
  10443. /**
  10444. * Create and run an async loop.
  10445. * @param iterations the number of iterations.
  10446. * @param _fn the function to run each iteration
  10447. * @param _successCallback the callback that will be called upon succesful execution
  10448. * @param offset starting offset.
  10449. * @returns the created async loop object
  10450. */
  10451. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10452. if (offset === void 0) { offset = 0; }
  10453. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10454. loop.executeNext();
  10455. return loop;
  10456. };
  10457. /**
  10458. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10459. * @param iterations total number of iterations
  10460. * @param syncedIterations number of synchronous iterations in each async iteration.
  10461. * @param fn the function to call each iteration.
  10462. * @param callback a success call back that will be called when iterating stops.
  10463. * @param breakFunction a break condition (optional)
  10464. * @param timeout timeout settings for the setTimeout function. default - 0.
  10465. * @returns the created async loop object
  10466. */
  10467. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10468. if (timeout === void 0) { timeout = 0; }
  10469. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10470. if (breakFunction && breakFunction())
  10471. loop.breakLoop();
  10472. else {
  10473. setTimeout(function () {
  10474. for (var i = 0; i < syncedIterations; ++i) {
  10475. var iteration = (loop.index * syncedIterations) + i;
  10476. if (iteration >= iterations)
  10477. break;
  10478. fn(iteration);
  10479. if (breakFunction && breakFunction()) {
  10480. loop.breakLoop();
  10481. break;
  10482. }
  10483. }
  10484. loop.executeNext();
  10485. }, timeout);
  10486. }
  10487. }, callback);
  10488. };
  10489. return AsyncLoop;
  10490. }());
  10491. BABYLON.AsyncLoop = AsyncLoop;
  10492. })(BABYLON || (BABYLON = {}));
  10493. //# sourceMappingURL=babylon.tools.js.map
  10494. var BABYLON;
  10495. (function (BABYLON) {
  10496. var PromiseStates;
  10497. (function (PromiseStates) {
  10498. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10499. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10500. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10501. })(PromiseStates || (PromiseStates = {}));
  10502. var FulFillmentAgregator = /** @class */ (function () {
  10503. function FulFillmentAgregator() {
  10504. this.count = 0;
  10505. this.target = 0;
  10506. this.results = [];
  10507. }
  10508. return FulFillmentAgregator;
  10509. }());
  10510. var InternalPromise = /** @class */ (function () {
  10511. function InternalPromise(resolver) {
  10512. var _this = this;
  10513. this._state = PromiseStates.Pending;
  10514. this._children = new Array();
  10515. this._rejectWasConsumed = false;
  10516. if (!resolver) {
  10517. return;
  10518. }
  10519. try {
  10520. resolver(function (value) {
  10521. _this._resolve(value);
  10522. }, function (reason) {
  10523. _this._reject(reason);
  10524. });
  10525. }
  10526. catch (e) {
  10527. this._reject(e);
  10528. }
  10529. }
  10530. Object.defineProperty(InternalPromise.prototype, "_result", {
  10531. get: function () {
  10532. return this._resultValue;
  10533. },
  10534. set: function (value) {
  10535. this._resultValue = value;
  10536. if (this._parent && this._parent._result === undefined) {
  10537. this._parent._result = value;
  10538. }
  10539. },
  10540. enumerable: true,
  10541. configurable: true
  10542. });
  10543. InternalPromise.prototype.catch = function (onRejected) {
  10544. return this.then(undefined, onRejected);
  10545. };
  10546. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10547. var _this = this;
  10548. var newPromise = new InternalPromise();
  10549. newPromise._onFulfilled = onFulfilled;
  10550. newPromise._onRejected = onRejected;
  10551. // Composition
  10552. this._children.push(newPromise);
  10553. newPromise._parent = this;
  10554. if (this._state !== PromiseStates.Pending) {
  10555. BABYLON.Tools.SetImmediate(function () {
  10556. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10557. var returnedValue = newPromise._resolve(_this._result);
  10558. if (returnedValue !== undefined && returnedValue !== null) {
  10559. if (returnedValue._state !== undefined) {
  10560. var returnedPromise = returnedValue;
  10561. newPromise._children.push(returnedPromise);
  10562. returnedPromise._parent = newPromise;
  10563. newPromise = returnedPromise;
  10564. }
  10565. else {
  10566. newPromise._result = returnedValue;
  10567. }
  10568. }
  10569. }
  10570. else {
  10571. newPromise._reject(_this._reason);
  10572. }
  10573. });
  10574. }
  10575. return newPromise;
  10576. };
  10577. InternalPromise.prototype._moveChildren = function (children) {
  10578. var _this = this;
  10579. var _a;
  10580. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10581. this._children.forEach(function (child) {
  10582. child._parent = _this;
  10583. });
  10584. if (this._state === PromiseStates.Fulfilled) {
  10585. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10586. var child = _b[_i];
  10587. child._resolve(this._result);
  10588. }
  10589. }
  10590. else if (this._state === PromiseStates.Rejected) {
  10591. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10592. var child = _d[_c];
  10593. child._reject(this._reason);
  10594. }
  10595. }
  10596. };
  10597. InternalPromise.prototype._resolve = function (value) {
  10598. try {
  10599. this._state = PromiseStates.Fulfilled;
  10600. var returnedValue = null;
  10601. if (this._onFulfilled) {
  10602. returnedValue = this._onFulfilled(value);
  10603. }
  10604. if (returnedValue !== undefined && returnedValue !== null) {
  10605. if (returnedValue._state !== undefined) {
  10606. // Transmit children
  10607. var returnedPromise = returnedValue;
  10608. returnedPromise._parent = this;
  10609. returnedPromise._moveChildren(this._children);
  10610. value = returnedPromise._result;
  10611. }
  10612. else {
  10613. value = returnedValue;
  10614. }
  10615. }
  10616. this._result = value;
  10617. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10618. var child = _a[_i];
  10619. child._resolve(value);
  10620. }
  10621. this._children.length = 0;
  10622. delete this._onFulfilled;
  10623. delete this._onRejected;
  10624. }
  10625. catch (e) {
  10626. this._reject(e, true);
  10627. }
  10628. };
  10629. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10630. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10631. this._state = PromiseStates.Rejected;
  10632. this._reason = reason;
  10633. if (this._onRejected && !onLocalThrow) {
  10634. try {
  10635. this._onRejected(reason);
  10636. this._rejectWasConsumed = true;
  10637. }
  10638. catch (e) {
  10639. reason = e;
  10640. }
  10641. }
  10642. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10643. var child = _a[_i];
  10644. if (this._rejectWasConsumed) {
  10645. child._resolve(null);
  10646. }
  10647. else {
  10648. child._reject(reason);
  10649. }
  10650. }
  10651. this._children.length = 0;
  10652. delete this._onFulfilled;
  10653. delete this._onRejected;
  10654. };
  10655. InternalPromise.resolve = function (value) {
  10656. var newPromise = new InternalPromise();
  10657. newPromise._resolve(value);
  10658. return newPromise;
  10659. };
  10660. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10661. promise.then(function (value) {
  10662. agregator.results[index] = value;
  10663. agregator.count++;
  10664. if (agregator.count === agregator.target) {
  10665. agregator.rootPromise._resolve(agregator.results);
  10666. }
  10667. return null;
  10668. }, function (reason) {
  10669. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10670. agregator.rootPromise._reject(reason);
  10671. }
  10672. });
  10673. };
  10674. InternalPromise.all = function (promises) {
  10675. var newPromise = new InternalPromise();
  10676. var agregator = new FulFillmentAgregator();
  10677. agregator.target = promises.length;
  10678. agregator.rootPromise = newPromise;
  10679. if (promises.length) {
  10680. for (var index = 0; index < promises.length; index++) {
  10681. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10682. }
  10683. }
  10684. else {
  10685. newPromise._resolve([]);
  10686. }
  10687. return newPromise;
  10688. };
  10689. InternalPromise.race = function (promises) {
  10690. var newPromise = new InternalPromise();
  10691. if (promises.length) {
  10692. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10693. var promise = promises_1[_i];
  10694. promise.then(function (value) {
  10695. if (newPromise) {
  10696. newPromise._resolve(value);
  10697. newPromise = null;
  10698. }
  10699. return null;
  10700. }, function (reason) {
  10701. if (newPromise) {
  10702. newPromise._reject(reason);
  10703. newPromise = null;
  10704. }
  10705. });
  10706. }
  10707. }
  10708. return newPromise;
  10709. };
  10710. return InternalPromise;
  10711. }());
  10712. /**
  10713. * Helper class that provides a small promise polyfill
  10714. */
  10715. var PromisePolyfill = /** @class */ (function () {
  10716. function PromisePolyfill() {
  10717. }
  10718. /**
  10719. * Static function used to check if the polyfill is required
  10720. * If this is the case then the function will inject the polyfill to window.Promise
  10721. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10722. */
  10723. PromisePolyfill.Apply = function (force) {
  10724. if (force === void 0) { force = false; }
  10725. if (force || typeof Promise === 'undefined') {
  10726. var root = window;
  10727. root.Promise = InternalPromise;
  10728. }
  10729. };
  10730. return PromisePolyfill;
  10731. }());
  10732. BABYLON.PromisePolyfill = PromisePolyfill;
  10733. })(BABYLON || (BABYLON = {}));
  10734. //# sourceMappingURL=babylon.promise.js.map
  10735. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10736. var BABYLON;
  10737. (function (BABYLON) {
  10738. /**
  10739. * Helper class to push actions to a pool of workers.
  10740. */
  10741. var WorkerPool = /** @class */ (function () {
  10742. /**
  10743. * Constructor
  10744. * @param workers Array of workers to use for actions
  10745. */
  10746. function WorkerPool(workers) {
  10747. this._pendingActions = new Array();
  10748. this._workerInfos = workers.map(function (worker) { return ({
  10749. worker: worker,
  10750. active: false
  10751. }); });
  10752. }
  10753. /**
  10754. * Terminates all workers and clears any pending actions.
  10755. */
  10756. WorkerPool.prototype.dispose = function () {
  10757. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10758. var workerInfo = _a[_i];
  10759. workerInfo.worker.terminate();
  10760. }
  10761. delete this._workerInfos;
  10762. delete this._pendingActions;
  10763. };
  10764. /**
  10765. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10766. * pended until a worker has completed its action.
  10767. * @param action The action to perform. Call onComplete when the action is complete.
  10768. */
  10769. WorkerPool.prototype.push = function (action) {
  10770. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10771. var workerInfo = _a[_i];
  10772. if (!workerInfo.active) {
  10773. this._execute(workerInfo, action);
  10774. return;
  10775. }
  10776. }
  10777. this._pendingActions.push(action);
  10778. };
  10779. WorkerPool.prototype._execute = function (workerInfo, action) {
  10780. var _this = this;
  10781. workerInfo.active = true;
  10782. action(workerInfo.worker, function () {
  10783. workerInfo.active = false;
  10784. var nextAction = _this._pendingActions.shift();
  10785. if (nextAction) {
  10786. _this._execute(workerInfo, nextAction);
  10787. }
  10788. });
  10789. };
  10790. return WorkerPool;
  10791. }());
  10792. BABYLON.WorkerPool = WorkerPool;
  10793. })(BABYLON || (BABYLON = {}));
  10794. //# sourceMappingURL=babylon.workerPool.js.map
  10795. var BABYLON;
  10796. (function (BABYLON) {
  10797. /**
  10798. * @hidden
  10799. **/
  10800. var _AlphaState = /** @class */ (function () {
  10801. /**
  10802. * Initializes the state.
  10803. */
  10804. function _AlphaState() {
  10805. this._isAlphaBlendDirty = false;
  10806. this._isBlendFunctionParametersDirty = false;
  10807. this._isBlendEquationParametersDirty = false;
  10808. this._isBlendConstantsDirty = false;
  10809. this._alphaBlend = false;
  10810. this._blendFunctionParameters = new Array(4);
  10811. this._blendEquationParameters = new Array(2);
  10812. this._blendConstants = new Array(4);
  10813. this.reset();
  10814. }
  10815. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10816. get: function () {
  10817. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10818. },
  10819. enumerable: true,
  10820. configurable: true
  10821. });
  10822. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10823. get: function () {
  10824. return this._alphaBlend;
  10825. },
  10826. set: function (value) {
  10827. if (this._alphaBlend === value) {
  10828. return;
  10829. }
  10830. this._alphaBlend = value;
  10831. this._isAlphaBlendDirty = true;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10837. if (this._blendConstants[0] === r &&
  10838. this._blendConstants[1] === g &&
  10839. this._blendConstants[2] === b &&
  10840. this._blendConstants[3] === a) {
  10841. return;
  10842. }
  10843. this._blendConstants[0] = r;
  10844. this._blendConstants[1] = g;
  10845. this._blendConstants[2] = b;
  10846. this._blendConstants[3] = a;
  10847. this._isBlendConstantsDirty = true;
  10848. };
  10849. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10850. if (this._blendFunctionParameters[0] === value0 &&
  10851. this._blendFunctionParameters[1] === value1 &&
  10852. this._blendFunctionParameters[2] === value2 &&
  10853. this._blendFunctionParameters[3] === value3) {
  10854. return;
  10855. }
  10856. this._blendFunctionParameters[0] = value0;
  10857. this._blendFunctionParameters[1] = value1;
  10858. this._blendFunctionParameters[2] = value2;
  10859. this._blendFunctionParameters[3] = value3;
  10860. this._isBlendFunctionParametersDirty = true;
  10861. };
  10862. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10863. if (this._blendEquationParameters[0] === rgb &&
  10864. this._blendEquationParameters[1] === alpha) {
  10865. return;
  10866. }
  10867. this._blendEquationParameters[0] = rgb;
  10868. this._blendEquationParameters[1] = alpha;
  10869. this._isBlendEquationParametersDirty = true;
  10870. };
  10871. _AlphaState.prototype.reset = function () {
  10872. this._alphaBlend = false;
  10873. this._blendFunctionParameters[0] = null;
  10874. this._blendFunctionParameters[1] = null;
  10875. this._blendFunctionParameters[2] = null;
  10876. this._blendFunctionParameters[3] = null;
  10877. this._blendEquationParameters[0] = null;
  10878. this._blendEquationParameters[1] = null;
  10879. this._blendConstants[0] = null;
  10880. this._blendConstants[1] = null;
  10881. this._blendConstants[2] = null;
  10882. this._blendConstants[3] = null;
  10883. this._isAlphaBlendDirty = true;
  10884. this._isBlendFunctionParametersDirty = false;
  10885. this._isBlendEquationParametersDirty = false;
  10886. this._isBlendConstantsDirty = false;
  10887. };
  10888. _AlphaState.prototype.apply = function (gl) {
  10889. if (!this.isDirty) {
  10890. return;
  10891. }
  10892. // Alpha blend
  10893. if (this._isAlphaBlendDirty) {
  10894. if (this._alphaBlend) {
  10895. gl.enable(gl.BLEND);
  10896. }
  10897. else {
  10898. gl.disable(gl.BLEND);
  10899. }
  10900. this._isAlphaBlendDirty = false;
  10901. }
  10902. // Alpha function
  10903. if (this._isBlendFunctionParametersDirty) {
  10904. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10905. this._isBlendFunctionParametersDirty = false;
  10906. }
  10907. // Alpha equation
  10908. if (this._isBlendEquationParametersDirty) {
  10909. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10910. this._isBlendEquationParametersDirty = false;
  10911. }
  10912. // Constants
  10913. if (this._isBlendConstantsDirty) {
  10914. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10915. this._isBlendConstantsDirty = false;
  10916. }
  10917. };
  10918. return _AlphaState;
  10919. }());
  10920. BABYLON._AlphaState = _AlphaState;
  10921. })(BABYLON || (BABYLON = {}));
  10922. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10923. var BABYLON;
  10924. (function (BABYLON) {
  10925. /**
  10926. * @hidden
  10927. **/
  10928. var _DepthCullingState = /** @class */ (function () {
  10929. /**
  10930. * Initializes the state.
  10931. */
  10932. function _DepthCullingState() {
  10933. this._isDepthTestDirty = false;
  10934. this._isDepthMaskDirty = false;
  10935. this._isDepthFuncDirty = false;
  10936. this._isCullFaceDirty = false;
  10937. this._isCullDirty = false;
  10938. this._isZOffsetDirty = false;
  10939. this._isFrontFaceDirty = false;
  10940. this.reset();
  10941. }
  10942. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10943. get: function () {
  10944. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10945. },
  10946. enumerable: true,
  10947. configurable: true
  10948. });
  10949. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10950. get: function () {
  10951. return this._zOffset;
  10952. },
  10953. set: function (value) {
  10954. if (this._zOffset === value) {
  10955. return;
  10956. }
  10957. this._zOffset = value;
  10958. this._isZOffsetDirty = true;
  10959. },
  10960. enumerable: true,
  10961. configurable: true
  10962. });
  10963. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10964. get: function () {
  10965. return this._cullFace;
  10966. },
  10967. set: function (value) {
  10968. if (this._cullFace === value) {
  10969. return;
  10970. }
  10971. this._cullFace = value;
  10972. this._isCullFaceDirty = true;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10978. get: function () {
  10979. return this._cull;
  10980. },
  10981. set: function (value) {
  10982. if (this._cull === value) {
  10983. return;
  10984. }
  10985. this._cull = value;
  10986. this._isCullDirty = true;
  10987. },
  10988. enumerable: true,
  10989. configurable: true
  10990. });
  10991. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10992. get: function () {
  10993. return this._depthFunc;
  10994. },
  10995. set: function (value) {
  10996. if (this._depthFunc === value) {
  10997. return;
  10998. }
  10999. this._depthFunc = value;
  11000. this._isDepthFuncDirty = true;
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11006. get: function () {
  11007. return this._depthMask;
  11008. },
  11009. set: function (value) {
  11010. if (this._depthMask === value) {
  11011. return;
  11012. }
  11013. this._depthMask = value;
  11014. this._isDepthMaskDirty = true;
  11015. },
  11016. enumerable: true,
  11017. configurable: true
  11018. });
  11019. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11020. get: function () {
  11021. return this._depthTest;
  11022. },
  11023. set: function (value) {
  11024. if (this._depthTest === value) {
  11025. return;
  11026. }
  11027. this._depthTest = value;
  11028. this._isDepthTestDirty = true;
  11029. },
  11030. enumerable: true,
  11031. configurable: true
  11032. });
  11033. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11034. get: function () {
  11035. return this._frontFace;
  11036. },
  11037. set: function (value) {
  11038. if (this._frontFace === value) {
  11039. return;
  11040. }
  11041. this._frontFace = value;
  11042. this._isFrontFaceDirty = true;
  11043. },
  11044. enumerable: true,
  11045. configurable: true
  11046. });
  11047. _DepthCullingState.prototype.reset = function () {
  11048. this._depthMask = true;
  11049. this._depthTest = true;
  11050. this._depthFunc = null;
  11051. this._cullFace = null;
  11052. this._cull = null;
  11053. this._zOffset = 0;
  11054. this._frontFace = null;
  11055. this._isDepthTestDirty = true;
  11056. this._isDepthMaskDirty = true;
  11057. this._isDepthFuncDirty = false;
  11058. this._isCullFaceDirty = false;
  11059. this._isCullDirty = false;
  11060. this._isZOffsetDirty = false;
  11061. this._isFrontFaceDirty = false;
  11062. };
  11063. _DepthCullingState.prototype.apply = function (gl) {
  11064. if (!this.isDirty) {
  11065. return;
  11066. }
  11067. // Cull
  11068. if (this._isCullDirty) {
  11069. if (this.cull) {
  11070. gl.enable(gl.CULL_FACE);
  11071. }
  11072. else {
  11073. gl.disable(gl.CULL_FACE);
  11074. }
  11075. this._isCullDirty = false;
  11076. }
  11077. // Cull face
  11078. if (this._isCullFaceDirty) {
  11079. gl.cullFace(this.cullFace);
  11080. this._isCullFaceDirty = false;
  11081. }
  11082. // Depth mask
  11083. if (this._isDepthMaskDirty) {
  11084. gl.depthMask(this.depthMask);
  11085. this._isDepthMaskDirty = false;
  11086. }
  11087. // Depth test
  11088. if (this._isDepthTestDirty) {
  11089. if (this.depthTest) {
  11090. gl.enable(gl.DEPTH_TEST);
  11091. }
  11092. else {
  11093. gl.disable(gl.DEPTH_TEST);
  11094. }
  11095. this._isDepthTestDirty = false;
  11096. }
  11097. // Depth func
  11098. if (this._isDepthFuncDirty) {
  11099. gl.depthFunc(this.depthFunc);
  11100. this._isDepthFuncDirty = false;
  11101. }
  11102. // zOffset
  11103. if (this._isZOffsetDirty) {
  11104. if (this.zOffset) {
  11105. gl.enable(gl.POLYGON_OFFSET_FILL);
  11106. gl.polygonOffset(this.zOffset, 0);
  11107. }
  11108. else {
  11109. gl.disable(gl.POLYGON_OFFSET_FILL);
  11110. }
  11111. this._isZOffsetDirty = false;
  11112. }
  11113. // Front face
  11114. if (this._isFrontFaceDirty) {
  11115. gl.frontFace(this.frontFace);
  11116. this._isFrontFaceDirty = false;
  11117. }
  11118. };
  11119. return _DepthCullingState;
  11120. }());
  11121. BABYLON._DepthCullingState = _DepthCullingState;
  11122. })(BABYLON || (BABYLON = {}));
  11123. //# sourceMappingURL=babylon.depthCullingState.js.map
  11124. var BABYLON;
  11125. (function (BABYLON) {
  11126. /**
  11127. * @hidden
  11128. **/
  11129. var _StencilState = /** @class */ (function () {
  11130. function _StencilState() {
  11131. this._isStencilTestDirty = false;
  11132. this._isStencilMaskDirty = false;
  11133. this._isStencilFuncDirty = false;
  11134. this._isStencilOpDirty = false;
  11135. this.reset();
  11136. }
  11137. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11138. get: function () {
  11139. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11145. get: function () {
  11146. return this._stencilFunc;
  11147. },
  11148. set: function (value) {
  11149. if (this._stencilFunc === value) {
  11150. return;
  11151. }
  11152. this._stencilFunc = value;
  11153. this._isStencilFuncDirty = true;
  11154. },
  11155. enumerable: true,
  11156. configurable: true
  11157. });
  11158. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11159. get: function () {
  11160. return this._stencilFuncRef;
  11161. },
  11162. set: function (value) {
  11163. if (this._stencilFuncRef === value) {
  11164. return;
  11165. }
  11166. this._stencilFuncRef = value;
  11167. this._isStencilFuncDirty = true;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11173. get: function () {
  11174. return this._stencilFuncMask;
  11175. },
  11176. set: function (value) {
  11177. if (this._stencilFuncMask === value) {
  11178. return;
  11179. }
  11180. this._stencilFuncMask = value;
  11181. this._isStencilFuncDirty = true;
  11182. },
  11183. enumerable: true,
  11184. configurable: true
  11185. });
  11186. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11187. get: function () {
  11188. return this._stencilOpStencilFail;
  11189. },
  11190. set: function (value) {
  11191. if (this._stencilOpStencilFail === value) {
  11192. return;
  11193. }
  11194. this._stencilOpStencilFail = value;
  11195. this._isStencilOpDirty = true;
  11196. },
  11197. enumerable: true,
  11198. configurable: true
  11199. });
  11200. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11201. get: function () {
  11202. return this._stencilOpDepthFail;
  11203. },
  11204. set: function (value) {
  11205. if (this._stencilOpDepthFail === value) {
  11206. return;
  11207. }
  11208. this._stencilOpDepthFail = value;
  11209. this._isStencilOpDirty = true;
  11210. },
  11211. enumerable: true,
  11212. configurable: true
  11213. });
  11214. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11215. get: function () {
  11216. return this._stencilOpStencilDepthPass;
  11217. },
  11218. set: function (value) {
  11219. if (this._stencilOpStencilDepthPass === value) {
  11220. return;
  11221. }
  11222. this._stencilOpStencilDepthPass = value;
  11223. this._isStencilOpDirty = true;
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11229. get: function () {
  11230. return this._stencilMask;
  11231. },
  11232. set: function (value) {
  11233. if (this._stencilMask === value) {
  11234. return;
  11235. }
  11236. this._stencilMask = value;
  11237. this._isStencilMaskDirty = true;
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11243. get: function () {
  11244. return this._stencilTest;
  11245. },
  11246. set: function (value) {
  11247. if (this._stencilTest === value) {
  11248. return;
  11249. }
  11250. this._stencilTest = value;
  11251. this._isStencilTestDirty = true;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. _StencilState.prototype.reset = function () {
  11257. this._stencilTest = false;
  11258. this._stencilMask = 0xFF;
  11259. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11260. this._stencilFuncRef = 1;
  11261. this._stencilFuncMask = 0xFF;
  11262. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11263. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11264. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11265. this._isStencilTestDirty = true;
  11266. this._isStencilMaskDirty = true;
  11267. this._isStencilFuncDirty = true;
  11268. this._isStencilOpDirty = true;
  11269. };
  11270. _StencilState.prototype.apply = function (gl) {
  11271. if (!this.isDirty) {
  11272. return;
  11273. }
  11274. // Stencil test
  11275. if (this._isStencilTestDirty) {
  11276. if (this.stencilTest) {
  11277. gl.enable(gl.STENCIL_TEST);
  11278. }
  11279. else {
  11280. gl.disable(gl.STENCIL_TEST);
  11281. }
  11282. this._isStencilTestDirty = false;
  11283. }
  11284. // Stencil mask
  11285. if (this._isStencilMaskDirty) {
  11286. gl.stencilMask(this.stencilMask);
  11287. this._isStencilMaskDirty = false;
  11288. }
  11289. // Stencil func
  11290. if (this._isStencilFuncDirty) {
  11291. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11292. this._isStencilFuncDirty = false;
  11293. }
  11294. // Stencil op
  11295. if (this._isStencilOpDirty) {
  11296. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11297. this._isStencilOpDirty = false;
  11298. }
  11299. };
  11300. return _StencilState;
  11301. }());
  11302. BABYLON._StencilState = _StencilState;
  11303. })(BABYLON || (BABYLON = {}));
  11304. //# sourceMappingURL=babylon.stencilState.js.map
  11305. var __assign = (this && this.__assign) || function () {
  11306. __assign = Object.assign || function(t) {
  11307. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11308. s = arguments[i];
  11309. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11310. t[p] = s[p];
  11311. }
  11312. return t;
  11313. };
  11314. return __assign.apply(this, arguments);
  11315. };
  11316. var BABYLON;
  11317. (function (BABYLON) {
  11318. /**
  11319. * Keeps track of all the buffer info used in engine.
  11320. */
  11321. var BufferPointer = /** @class */ (function () {
  11322. function BufferPointer() {
  11323. }
  11324. return BufferPointer;
  11325. }());
  11326. /**
  11327. * Interface for attribute information associated with buffer instanciation
  11328. */
  11329. var InstancingAttributeInfo = /** @class */ (function () {
  11330. function InstancingAttributeInfo() {
  11331. }
  11332. return InstancingAttributeInfo;
  11333. }());
  11334. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11335. /**
  11336. * Define options used to create a render target texture
  11337. */
  11338. var RenderTargetCreationOptions = /** @class */ (function () {
  11339. function RenderTargetCreationOptions() {
  11340. }
  11341. return RenderTargetCreationOptions;
  11342. }());
  11343. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11344. /**
  11345. * Define options used to create a depth texture
  11346. */
  11347. var DepthTextureCreationOptions = /** @class */ (function () {
  11348. function DepthTextureCreationOptions() {
  11349. }
  11350. return DepthTextureCreationOptions;
  11351. }());
  11352. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11353. /**
  11354. * Class used to describe the capabilities of the engine relatively to the current browser
  11355. */
  11356. var EngineCapabilities = /** @class */ (function () {
  11357. function EngineCapabilities() {
  11358. }
  11359. return EngineCapabilities;
  11360. }());
  11361. BABYLON.EngineCapabilities = EngineCapabilities;
  11362. /**
  11363. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11364. */
  11365. var Engine = /** @class */ (function () {
  11366. /**
  11367. * Creates a new engine
  11368. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11369. * @param antialias defines enable antialiasing (default: false)
  11370. * @param options defines further options to be sent to the getContext() function
  11371. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11372. */
  11373. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11374. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11375. var _this = this;
  11376. // Public members
  11377. /**
  11378. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11379. */
  11380. this.forcePOTTextures = false;
  11381. /**
  11382. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11383. */
  11384. this.isFullscreen = false;
  11385. /**
  11386. * Gets a boolean indicating if the pointer is currently locked
  11387. */
  11388. this.isPointerLock = false;
  11389. /**
  11390. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11391. */
  11392. this.cullBackFaces = true;
  11393. /**
  11394. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11395. */
  11396. this.renderEvenInBackground = true;
  11397. /**
  11398. * Gets or sets a boolean indicating that cache can be kept between frames
  11399. */
  11400. this.preventCacheWipeBetweenFrames = false;
  11401. /**
  11402. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11403. **/
  11404. this.enableOfflineSupport = false;
  11405. /**
  11406. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11407. **/
  11408. this.disableManifestCheck = false;
  11409. /**
  11410. * Gets the list of created scenes
  11411. */
  11412. this.scenes = new Array();
  11413. /**
  11414. * Gets the list of created postprocesses
  11415. */
  11416. this.postProcesses = new Array();
  11417. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11418. this.validateShaderPrograms = false;
  11419. // Observables
  11420. /**
  11421. * Observable event triggered each time the rendering canvas is resized
  11422. */
  11423. this.onResizeObservable = new BABYLON.Observable();
  11424. /**
  11425. * Observable event triggered each time the canvas loses focus
  11426. */
  11427. this.onCanvasBlurObservable = new BABYLON.Observable();
  11428. /**
  11429. * Observable event triggered each time the canvas gains focus
  11430. */
  11431. this.onCanvasFocusObservable = new BABYLON.Observable();
  11432. /**
  11433. * Observable event triggered each time the canvas receives pointerout event
  11434. */
  11435. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11436. /**
  11437. * Observable event triggered before each texture is initialized
  11438. */
  11439. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11440. //WebVR
  11441. this._vrDisplay = undefined;
  11442. this._vrSupported = false;
  11443. this._vrExclusivePointerMode = false;
  11444. // Uniform buffers list
  11445. /**
  11446. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11447. */
  11448. this.disableUniformBuffers = false;
  11449. /** @hidden */
  11450. this._uniformBuffers = new Array();
  11451. // Observables
  11452. /**
  11453. * Observable raised when the engine begins a new frame
  11454. */
  11455. this.onBeginFrameObservable = new BABYLON.Observable();
  11456. /**
  11457. * Observable raised when the engine ends the current frame
  11458. */
  11459. this.onEndFrameObservable = new BABYLON.Observable();
  11460. /**
  11461. * Observable raised when the engine is about to compile a shader
  11462. */
  11463. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11464. /**
  11465. * Observable raised when the engine has jsut compiled a shader
  11466. */
  11467. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11468. this._windowIsBackground = false;
  11469. this._webGLVersion = 1.0;
  11470. /** @hidden */
  11471. this._badOS = false;
  11472. /** @hidden */
  11473. this._badDesktopOS = false;
  11474. /**
  11475. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11476. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11477. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11478. */
  11479. this.disableTextureBindingOptimization = false;
  11480. /**
  11481. * Observable signaled when VR display mode changes
  11482. */
  11483. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11484. /**
  11485. * Observable signaled when VR request present is complete
  11486. */
  11487. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11488. /**
  11489. * Observable signaled when VR request present starts
  11490. */
  11491. this.onVRRequestPresentStart = new BABYLON.Observable();
  11492. this._colorWrite = true;
  11493. /** @hidden */
  11494. this._drawCalls = new BABYLON.PerfCounter();
  11495. /** @hidden */
  11496. this._textureCollisions = new BABYLON.PerfCounter();
  11497. this._renderingQueueLaunched = false;
  11498. this._activeRenderLoops = new Array();
  11499. // Deterministic lockstepMaxSteps
  11500. this._deterministicLockstep = false;
  11501. this._lockstepMaxSteps = 4;
  11502. // Lost context
  11503. /**
  11504. * Observable signaled when a context lost event is raised
  11505. */
  11506. this.onContextLostObservable = new BABYLON.Observable();
  11507. /**
  11508. * Observable signaled when a context restored event is raised
  11509. */
  11510. this.onContextRestoredObservable = new BABYLON.Observable();
  11511. this._contextWasLost = false;
  11512. this._doNotHandleContextLost = false;
  11513. // FPS
  11514. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11515. this._fps = 60;
  11516. this._deltaTime = 0;
  11517. /**
  11518. * Turn this value on if you want to pause FPS computation when in background
  11519. */
  11520. this.disablePerformanceMonitorInBackground = false;
  11521. // States
  11522. /** @hidden */
  11523. this._depthCullingState = new BABYLON._DepthCullingState();
  11524. /** @hidden */
  11525. this._stencilState = new BABYLON._StencilState();
  11526. /** @hidden */
  11527. this._alphaState = new BABYLON._AlphaState();
  11528. /** @hidden */
  11529. this._alphaMode = Engine.ALPHA_DISABLE;
  11530. // Cache
  11531. this._internalTexturesCache = new Array();
  11532. /** @hidden */
  11533. this._activeChannel = 0;
  11534. this._currentTextureChannel = -1;
  11535. /** @hidden */
  11536. this._boundTexturesCache = {};
  11537. this._compiledEffects = {};
  11538. this._vertexAttribArraysEnabled = [];
  11539. this._uintIndicesCurrentlySet = false;
  11540. this._currentBoundBuffer = new Array();
  11541. /** @hidden */
  11542. this._currentFramebuffer = null;
  11543. this._currentBufferPointers = new Array();
  11544. this._currentInstanceLocations = new Array();
  11545. this._currentInstanceBuffers = new Array();
  11546. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11547. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11548. this._vaoRecordInProgress = false;
  11549. this._mustWipeVertexAttributes = false;
  11550. this._nextFreeTextureSlots = new Array();
  11551. this._maxSimultaneousTextures = 0;
  11552. this._activeRequests = new Array();
  11553. // Hardware supported Compressed Textures
  11554. this._texturesSupported = new Array();
  11555. /**
  11556. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11557. */
  11558. this.premultipliedAlpha = true;
  11559. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11560. this._onVRFullScreenTriggered = function () {
  11561. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11562. //get the old size before we change
  11563. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11564. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11565. //get the width and height, change the render size
  11566. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11567. _this.setHardwareScalingLevel(1);
  11568. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11569. }
  11570. else {
  11571. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11572. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11573. }
  11574. };
  11575. this._unpackFlipYCached = null;
  11576. /**
  11577. * In case you are sharing the context with other applications, it might
  11578. * be interested to not cache the unpack flip y state to ensure a consistent
  11579. * value would be set.
  11580. */
  11581. this.enableUnpackFlipYCached = true;
  11582. this._boundUniforms = {};
  11583. // Register promises
  11584. BABYLON.PromisePolyfill.Apply();
  11585. var canvas = null;
  11586. Engine.Instances.push(this);
  11587. if (!canvasOrContext) {
  11588. return;
  11589. }
  11590. options = options || {};
  11591. if (canvasOrContext.getContext) {
  11592. canvas = canvasOrContext;
  11593. this._renderingCanvas = canvas;
  11594. if (antialias != null) {
  11595. options.antialias = antialias;
  11596. }
  11597. if (options.deterministicLockstep === undefined) {
  11598. options.deterministicLockstep = false;
  11599. }
  11600. if (options.lockstepMaxSteps === undefined) {
  11601. options.lockstepMaxSteps = 4;
  11602. }
  11603. if (options.preserveDrawingBuffer === undefined) {
  11604. options.preserveDrawingBuffer = false;
  11605. }
  11606. if (options.audioEngine === undefined) {
  11607. options.audioEngine = true;
  11608. }
  11609. if (options.stencil === undefined) {
  11610. options.stencil = true;
  11611. }
  11612. if (options.premultipliedAlpha === false) {
  11613. this.premultipliedAlpha = false;
  11614. }
  11615. this._deterministicLockstep = options.deterministicLockstep;
  11616. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11617. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11618. // Exceptions
  11619. if (navigator && navigator.userAgent) {
  11620. var ua = navigator.userAgent;
  11621. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11622. var exception = _a[_i];
  11623. var key = exception.key;
  11624. var targets = exception.targets;
  11625. if (ua.indexOf(key) > -1) {
  11626. if (exception.capture && exception.captureConstraint) {
  11627. var capture = exception.capture;
  11628. var constraint = exception.captureConstraint;
  11629. var regex = new RegExp(capture);
  11630. var matches = regex.exec(ua);
  11631. if (matches && matches.length > 0) {
  11632. var capturedValue = parseInt(matches[matches.length - 1]);
  11633. if (capturedValue >= constraint) {
  11634. continue;
  11635. }
  11636. }
  11637. }
  11638. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11639. var target = targets_1[_b];
  11640. switch (target) {
  11641. case "uniformBuffer":
  11642. this.disableUniformBuffers = true;
  11643. break;
  11644. case "textureBindingOptimization":
  11645. this.disableTextureBindingOptimization = true;
  11646. break;
  11647. }
  11648. }
  11649. }
  11650. }
  11651. }
  11652. // GL
  11653. if (!options.disableWebGL2Support) {
  11654. try {
  11655. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11656. if (this._gl) {
  11657. this._webGLVersion = 2.0;
  11658. }
  11659. }
  11660. catch (e) {
  11661. // Do nothing
  11662. }
  11663. }
  11664. if (!this._gl) {
  11665. if (!canvas) {
  11666. throw new Error("The provided canvas is null or undefined.");
  11667. }
  11668. try {
  11669. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11670. }
  11671. catch (e) {
  11672. throw new Error("WebGL not supported");
  11673. }
  11674. }
  11675. if (!this._gl) {
  11676. throw new Error("WebGL not supported");
  11677. }
  11678. this._onCanvasFocus = function () {
  11679. _this.onCanvasFocusObservable.notifyObservers(_this);
  11680. };
  11681. this._onCanvasBlur = function () {
  11682. _this.onCanvasBlurObservable.notifyObservers(_this);
  11683. };
  11684. canvas.addEventListener("focus", this._onCanvasFocus);
  11685. canvas.addEventListener("blur", this._onCanvasBlur);
  11686. this._onBlur = function () {
  11687. if (_this.disablePerformanceMonitorInBackground) {
  11688. _this._performanceMonitor.disable();
  11689. }
  11690. _this._windowIsBackground = true;
  11691. };
  11692. this._onFocus = function () {
  11693. if (_this.disablePerformanceMonitorInBackground) {
  11694. _this._performanceMonitor.enable();
  11695. }
  11696. _this._windowIsBackground = false;
  11697. };
  11698. this._onCanvasPointerOut = function (ev) {
  11699. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11700. };
  11701. window.addEventListener("blur", this._onBlur);
  11702. window.addEventListener("focus", this._onFocus);
  11703. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11704. // Context lost
  11705. if (!this._doNotHandleContextLost) {
  11706. this._onContextLost = function (evt) {
  11707. evt.preventDefault();
  11708. _this._contextWasLost = true;
  11709. BABYLON.Tools.Warn("WebGL context lost.");
  11710. _this.onContextLostObservable.notifyObservers(_this);
  11711. };
  11712. this._onContextRestored = function (evt) {
  11713. // Adding a timeout to avoid race condition at browser level
  11714. setTimeout(function () {
  11715. // Rebuild gl context
  11716. _this._initGLContext();
  11717. // Rebuild effects
  11718. _this._rebuildEffects();
  11719. // Rebuild textures
  11720. _this._rebuildInternalTextures();
  11721. // Rebuild buffers
  11722. _this._rebuildBuffers();
  11723. // Cache
  11724. _this.wipeCaches(true);
  11725. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11726. _this.onContextRestoredObservable.notifyObservers(_this);
  11727. _this._contextWasLost = false;
  11728. }, 0);
  11729. };
  11730. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11731. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11732. }
  11733. }
  11734. else {
  11735. this._gl = canvasOrContext;
  11736. this._renderingCanvas = this._gl.canvas;
  11737. if (this._gl.renderbufferStorageMultisample) {
  11738. this._webGLVersion = 2.0;
  11739. }
  11740. options.stencil = this._gl.getContextAttributes().stencil;
  11741. }
  11742. // Viewport
  11743. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11744. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11745. this.resize();
  11746. this._isStencilEnable = options.stencil ? true : false;
  11747. this._initGLContext();
  11748. if (canvas) {
  11749. // Fullscreen
  11750. this._onFullscreenChange = function () {
  11751. if (document.fullscreen !== undefined) {
  11752. _this.isFullscreen = document.fullscreen;
  11753. }
  11754. else if (document.mozFullScreen !== undefined) {
  11755. _this.isFullscreen = document.mozFullScreen;
  11756. }
  11757. else if (document.webkitIsFullScreen !== undefined) {
  11758. _this.isFullscreen = document.webkitIsFullScreen;
  11759. }
  11760. else if (document.msIsFullScreen !== undefined) {
  11761. _this.isFullscreen = document.msIsFullScreen;
  11762. }
  11763. // Pointer lock
  11764. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11765. canvas.requestPointerLock = canvas.requestPointerLock ||
  11766. canvas.msRequestPointerLock ||
  11767. canvas.mozRequestPointerLock ||
  11768. canvas.webkitRequestPointerLock;
  11769. if (canvas.requestPointerLock) {
  11770. canvas.requestPointerLock();
  11771. }
  11772. }
  11773. };
  11774. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11775. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11776. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11777. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11778. // Pointer lock
  11779. this._onPointerLockChange = function () {
  11780. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11781. document.webkitPointerLockElement === canvas ||
  11782. document.msPointerLockElement === canvas ||
  11783. document.pointerLockElement === canvas);
  11784. };
  11785. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11786. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11787. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11788. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11789. this._onVRDisplayPointerRestricted = function () {
  11790. if (canvas) {
  11791. canvas.requestPointerLock();
  11792. }
  11793. };
  11794. this._onVRDisplayPointerUnrestricted = function () {
  11795. document.exitPointerLock();
  11796. };
  11797. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11798. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11799. }
  11800. // Create Audio Engine if needed.
  11801. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  11802. Engine.audioEngine = Engine.AudioEngineFactory(this);
  11803. }
  11804. // Prepare buffer pointers
  11805. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11806. this._currentBufferPointers[i] = new BufferPointer();
  11807. }
  11808. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11809. // Load WebVR Devices
  11810. if (options.autoEnableWebVR) {
  11811. this.initWebVR();
  11812. }
  11813. // Detect if we are running on a faulty buggy OS.
  11814. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11815. // Detect if we are running on a faulty buggy desktop OS.
  11816. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11817. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11818. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11819. }
  11820. Object.defineProperty(Engine, "LastCreatedEngine", {
  11821. /**
  11822. * Gets the latest created engine
  11823. */
  11824. get: function () {
  11825. if (Engine.Instances.length === 0) {
  11826. return null;
  11827. }
  11828. return Engine.Instances[Engine.Instances.length - 1];
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. Object.defineProperty(Engine, "LastCreatedScene", {
  11834. /**
  11835. * Gets the latest created scene
  11836. */
  11837. get: function () {
  11838. var lastCreatedEngine = Engine.LastCreatedEngine;
  11839. if (!lastCreatedEngine) {
  11840. return null;
  11841. }
  11842. if (lastCreatedEngine.scenes.length === 0) {
  11843. return null;
  11844. }
  11845. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. /**
  11851. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11852. * @param flag defines which part of the materials must be marked as dirty
  11853. * @param predicate defines a predicate used to filter which materials should be affected
  11854. */
  11855. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11856. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11857. var engine = Engine.Instances[engineIndex];
  11858. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11859. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11860. }
  11861. }
  11862. };
  11863. Object.defineProperty(Engine, "Version", {
  11864. /**
  11865. * Returns the current version of the framework
  11866. */
  11867. get: function () {
  11868. return "3.3.0-beta.5";
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11874. /**
  11875. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11876. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11877. */
  11878. get: function () {
  11879. return this._vrExclusivePointerMode;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11885. /**
  11886. * Gets a boolean indicating that the engine supports uniform buffers
  11887. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11888. */
  11889. get: function () {
  11890. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11896. /**
  11897. * Gets a boolean indicating that only power of 2 textures are supported
  11898. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11899. */
  11900. get: function () {
  11901. return this._webGLVersion < 2 || this.forcePOTTextures;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11907. /**
  11908. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11909. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11910. */
  11911. get: function () {
  11912. return this._doNotHandleContextLost;
  11913. },
  11914. set: function (value) {
  11915. this._doNotHandleContextLost = value;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11921. /**
  11922. * Gets the performance monitor attached to this engine
  11923. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11924. */
  11925. get: function () {
  11926. return this._performanceMonitor;
  11927. },
  11928. enumerable: true,
  11929. configurable: true
  11930. });
  11931. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11932. /**
  11933. * Gets the list of texture formats supported
  11934. */
  11935. get: function () {
  11936. return this._texturesSupported;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11942. /**
  11943. * Gets the list of texture formats in use
  11944. */
  11945. get: function () {
  11946. return this._textureFormatInUse;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine.prototype, "currentViewport", {
  11952. /**
  11953. * Gets the current viewport
  11954. */
  11955. get: function () {
  11956. return this._cachedViewport;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11962. /**
  11963. * Gets the default empty texture
  11964. */
  11965. get: function () {
  11966. if (!this._emptyTexture) {
  11967. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11968. }
  11969. return this._emptyTexture;
  11970. },
  11971. enumerable: true,
  11972. configurable: true
  11973. });
  11974. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11975. /**
  11976. * Gets the default empty 3D texture
  11977. */
  11978. get: function () {
  11979. if (!this._emptyTexture3D) {
  11980. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11981. }
  11982. return this._emptyTexture3D;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11988. /**
  11989. * Gets the default empty cube texture
  11990. */
  11991. get: function () {
  11992. if (!this._emptyCubeTexture) {
  11993. var faceData = new Uint8Array(4);
  11994. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11995. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11996. }
  11997. return this._emptyCubeTexture;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Engine.prototype._rebuildInternalTextures = function () {
  12003. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12004. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12005. var internalTexture = currentState_1[_i];
  12006. internalTexture._rebuild();
  12007. }
  12008. };
  12009. Engine.prototype._rebuildEffects = function () {
  12010. for (var key in this._compiledEffects) {
  12011. var effect = this._compiledEffects[key];
  12012. effect._prepareEffect();
  12013. }
  12014. BABYLON.Effect.ResetCache();
  12015. };
  12016. Engine.prototype._rebuildBuffers = function () {
  12017. // Index / Vertex
  12018. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12019. var scene = _a[_i];
  12020. scene.resetCachedMaterial();
  12021. scene._rebuildGeometries();
  12022. scene._rebuildTextures();
  12023. }
  12024. // Uniforms
  12025. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12026. var uniformBuffer = _c[_b];
  12027. uniformBuffer._rebuild();
  12028. }
  12029. };
  12030. Engine.prototype._initGLContext = function () {
  12031. // Caps
  12032. this._caps = new EngineCapabilities();
  12033. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12034. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12035. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12036. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12037. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12038. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12039. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12040. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12041. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12042. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12043. // Infos
  12044. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12045. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12046. if (rendererInfo != null) {
  12047. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12048. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12049. }
  12050. if (!this._glVendor) {
  12051. this._glVendor = "Unknown vendor";
  12052. }
  12053. if (!this._glRenderer) {
  12054. this._glRenderer = "Unknown renderer";
  12055. }
  12056. // Constants
  12057. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12058. if (this._gl.RGBA16F !== 0x881A) {
  12059. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12060. }
  12061. if (this._gl.RGBA32F !== 0x8814) {
  12062. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12063. }
  12064. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12065. this._gl.DEPTH24_STENCIL8 = 35056;
  12066. }
  12067. // Extensions
  12068. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12069. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12070. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12071. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12072. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12073. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12074. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12075. 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');
  12076. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12077. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12078. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12079. this._caps.highPrecisionShaderSupported = true;
  12080. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12081. if (this._caps.timerQuery) {
  12082. if (this._webGLVersion === 1) {
  12083. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12084. }
  12085. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12086. }
  12087. // Checks if some of the format renders first to allow the use of webgl inspector.
  12088. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12089. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12090. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12091. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12092. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12093. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12094. if (this._webGLVersion > 1) {
  12095. this._gl.HALF_FLOAT_OES = 0x140B;
  12096. }
  12097. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12098. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12099. // Draw buffers
  12100. if (this._webGLVersion > 1) {
  12101. this._caps.drawBuffersExtension = true;
  12102. }
  12103. else {
  12104. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12105. if (drawBuffersExtension !== null) {
  12106. this._caps.drawBuffersExtension = true;
  12107. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12108. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12109. for (var i = 0; i < 16; i++) {
  12110. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12111. }
  12112. }
  12113. else {
  12114. this._caps.drawBuffersExtension = false;
  12115. }
  12116. }
  12117. // Depth Texture
  12118. if (this._webGLVersion > 1) {
  12119. this._caps.depthTextureExtension = true;
  12120. }
  12121. else {
  12122. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12123. if (depthTextureExtension != null) {
  12124. this._caps.depthTextureExtension = true;
  12125. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12126. }
  12127. }
  12128. // Vertex array object
  12129. if (this._webGLVersion > 1) {
  12130. this._caps.vertexArrayObject = true;
  12131. }
  12132. else {
  12133. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12134. if (vertexArrayObjectExtension != null) {
  12135. this._caps.vertexArrayObject = true;
  12136. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12137. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12138. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12139. }
  12140. else {
  12141. this._caps.vertexArrayObject = false;
  12142. }
  12143. }
  12144. // Instances count
  12145. if (this._webGLVersion > 1) {
  12146. this._caps.instancedArrays = true;
  12147. }
  12148. else {
  12149. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12150. if (instanceExtension != null) {
  12151. this._caps.instancedArrays = true;
  12152. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12153. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12154. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12155. }
  12156. else {
  12157. this._caps.instancedArrays = false;
  12158. }
  12159. }
  12160. // Intelligently add supported compressed formats in order to check for.
  12161. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12162. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12163. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12164. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12165. if (this._caps.astc)
  12166. this.texturesSupported.push('-astc.ktx');
  12167. if (this._caps.s3tc)
  12168. this.texturesSupported.push('-dxt.ktx');
  12169. if (this._caps.pvrtc)
  12170. this.texturesSupported.push('-pvrtc.ktx');
  12171. if (this._caps.etc2)
  12172. this.texturesSupported.push('-etc2.ktx');
  12173. if (this._caps.etc1)
  12174. this.texturesSupported.push('-etc1.ktx');
  12175. if (this._gl.getShaderPrecisionFormat) {
  12176. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12177. if (highp) {
  12178. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12179. }
  12180. }
  12181. // Depth buffer
  12182. this.setDepthBuffer(true);
  12183. this.setDepthFunctionToLessOrEqual();
  12184. this.setDepthWrite(true);
  12185. // Texture maps
  12186. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12187. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12188. this._nextFreeTextureSlots.push(slot);
  12189. }
  12190. };
  12191. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12192. /**
  12193. * Gets version of the current webGL context
  12194. */
  12195. get: function () {
  12196. return this._webGLVersion;
  12197. },
  12198. enumerable: true,
  12199. configurable: true
  12200. });
  12201. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12202. /**
  12203. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12204. */
  12205. get: function () {
  12206. return this._isStencilEnable;
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Engine.prototype._prepareWorkingCanvas = function () {
  12212. if (this._workingCanvas) {
  12213. return;
  12214. }
  12215. this._workingCanvas = document.createElement("canvas");
  12216. var context = this._workingCanvas.getContext("2d");
  12217. if (context) {
  12218. this._workingContext = context;
  12219. }
  12220. };
  12221. /**
  12222. * Reset the texture cache to empty state
  12223. */
  12224. Engine.prototype.resetTextureCache = function () {
  12225. for (var key in this._boundTexturesCache) {
  12226. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12227. continue;
  12228. }
  12229. var boundTexture = this._boundTexturesCache[key];
  12230. if (boundTexture) {
  12231. this._removeDesignatedSlot(boundTexture);
  12232. }
  12233. this._boundTexturesCache[key] = null;
  12234. }
  12235. if (!this.disableTextureBindingOptimization) {
  12236. this._nextFreeTextureSlots = [];
  12237. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12238. this._nextFreeTextureSlots.push(slot);
  12239. }
  12240. }
  12241. this._currentTextureChannel = -1;
  12242. };
  12243. /**
  12244. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12245. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12246. * @returns true if engine is in deterministic lock step mode
  12247. */
  12248. Engine.prototype.isDeterministicLockStep = function () {
  12249. return this._deterministicLockstep;
  12250. };
  12251. /**
  12252. * Gets the max steps when engine is running in deterministic lock step
  12253. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12254. * @returns the max steps
  12255. */
  12256. Engine.prototype.getLockstepMaxSteps = function () {
  12257. return this._lockstepMaxSteps;
  12258. };
  12259. /**
  12260. * Gets an object containing information about the current webGL context
  12261. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12262. */
  12263. Engine.prototype.getGlInfo = function () {
  12264. return {
  12265. vendor: this._glVendor,
  12266. renderer: this._glRenderer,
  12267. version: this._glVersion
  12268. };
  12269. };
  12270. /**
  12271. * Gets current aspect ratio
  12272. * @param camera defines the camera to use to get the aspect ratio
  12273. * @param useScreen defines if screen size must be used (or the current render target if any)
  12274. * @returns a number defining the aspect ratio
  12275. */
  12276. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12277. if (useScreen === void 0) { useScreen = false; }
  12278. var viewport = camera.viewport;
  12279. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12280. };
  12281. /**
  12282. * Gets current screen aspect ratio
  12283. * @returns a number defining the aspect ratio
  12284. */
  12285. Engine.prototype.getScreenAspectRatio = function () {
  12286. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12287. };
  12288. /**
  12289. * Gets the current render width
  12290. * @param useScreen defines if screen size must be used (or the current render target if any)
  12291. * @returns a number defining the current render width
  12292. */
  12293. Engine.prototype.getRenderWidth = function (useScreen) {
  12294. if (useScreen === void 0) { useScreen = false; }
  12295. if (!useScreen && this._currentRenderTarget) {
  12296. return this._currentRenderTarget.width;
  12297. }
  12298. return this._gl.drawingBufferWidth;
  12299. };
  12300. /**
  12301. * Gets the current render height
  12302. * @param useScreen defines if screen size must be used (or the current render target if any)
  12303. * @returns a number defining the current render height
  12304. */
  12305. Engine.prototype.getRenderHeight = function (useScreen) {
  12306. if (useScreen === void 0) { useScreen = false; }
  12307. if (!useScreen && this._currentRenderTarget) {
  12308. return this._currentRenderTarget.height;
  12309. }
  12310. return this._gl.drawingBufferHeight;
  12311. };
  12312. /**
  12313. * Gets the HTML canvas attached with the current webGL context
  12314. * @returns a HTML canvas
  12315. */
  12316. Engine.prototype.getRenderingCanvas = function () {
  12317. return this._renderingCanvas;
  12318. };
  12319. /**
  12320. * Gets the client rect of the HTML canvas attached with the current webGL context
  12321. * @returns a client rectanglee
  12322. */
  12323. Engine.prototype.getRenderingCanvasClientRect = function () {
  12324. if (!this._renderingCanvas) {
  12325. return null;
  12326. }
  12327. return this._renderingCanvas.getBoundingClientRect();
  12328. };
  12329. /**
  12330. * Defines the hardware scaling level.
  12331. * By default the hardware scaling level is computed from the window device ratio.
  12332. * 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.
  12333. * @param level defines the level to use
  12334. */
  12335. Engine.prototype.setHardwareScalingLevel = function (level) {
  12336. this._hardwareScalingLevel = level;
  12337. this.resize();
  12338. };
  12339. /**
  12340. * Gets the current hardware scaling level.
  12341. * By default the hardware scaling level is computed from the window device ratio.
  12342. * 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.
  12343. * @returns a number indicating the current hardware scaling level
  12344. */
  12345. Engine.prototype.getHardwareScalingLevel = function () {
  12346. return this._hardwareScalingLevel;
  12347. };
  12348. /**
  12349. * Gets the list of loaded textures
  12350. * @returns an array containing all loaded textures
  12351. */
  12352. Engine.prototype.getLoadedTexturesCache = function () {
  12353. return this._internalTexturesCache;
  12354. };
  12355. /**
  12356. * Gets the object containing all engine capabilities
  12357. * @returns the EngineCapabilities object
  12358. */
  12359. Engine.prototype.getCaps = function () {
  12360. return this._caps;
  12361. };
  12362. Object.defineProperty(Engine.prototype, "drawCalls", {
  12363. /** @hidden */
  12364. get: function () {
  12365. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12366. return 0;
  12367. },
  12368. enumerable: true,
  12369. configurable: true
  12370. });
  12371. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12372. /** @hidden */
  12373. get: function () {
  12374. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12375. return null;
  12376. },
  12377. enumerable: true,
  12378. configurable: true
  12379. });
  12380. /**
  12381. * Gets the current depth function
  12382. * @returns a number defining the depth function
  12383. */
  12384. Engine.prototype.getDepthFunction = function () {
  12385. return this._depthCullingState.depthFunc;
  12386. };
  12387. /**
  12388. * Sets the current depth function
  12389. * @param depthFunc defines the function to use
  12390. */
  12391. Engine.prototype.setDepthFunction = function (depthFunc) {
  12392. this._depthCullingState.depthFunc = depthFunc;
  12393. };
  12394. /**
  12395. * Sets the current depth function to GREATER
  12396. */
  12397. Engine.prototype.setDepthFunctionToGreater = function () {
  12398. this._depthCullingState.depthFunc = this._gl.GREATER;
  12399. };
  12400. /**
  12401. * Sets the current depth function to GEQUAL
  12402. */
  12403. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12404. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12405. };
  12406. /**
  12407. * Sets the current depth function to LESS
  12408. */
  12409. Engine.prototype.setDepthFunctionToLess = function () {
  12410. this._depthCullingState.depthFunc = this._gl.LESS;
  12411. };
  12412. /**
  12413. * Sets the current depth function to LEQUAL
  12414. */
  12415. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12416. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12417. };
  12418. /**
  12419. * Gets a boolean indicating if stencil buffer is enabled
  12420. * @returns the current stencil buffer state
  12421. */
  12422. Engine.prototype.getStencilBuffer = function () {
  12423. return this._stencilState.stencilTest;
  12424. };
  12425. /**
  12426. * Enable or disable the stencil buffer
  12427. * @param enable defines if the stencil buffer must be enabled or disabled
  12428. */
  12429. Engine.prototype.setStencilBuffer = function (enable) {
  12430. this._stencilState.stencilTest = enable;
  12431. };
  12432. /**
  12433. * Gets the current stencil mask
  12434. * @returns a number defining the new stencil mask to use
  12435. */
  12436. Engine.prototype.getStencilMask = function () {
  12437. return this._stencilState.stencilMask;
  12438. };
  12439. /**
  12440. * Sets the current stencil mask
  12441. * @param mask defines the new stencil mask to use
  12442. */
  12443. Engine.prototype.setStencilMask = function (mask) {
  12444. this._stencilState.stencilMask = mask;
  12445. };
  12446. /**
  12447. * Gets the current stencil function
  12448. * @returns a number defining the stencil function to use
  12449. */
  12450. Engine.prototype.getStencilFunction = function () {
  12451. return this._stencilState.stencilFunc;
  12452. };
  12453. /**
  12454. * Gets the current stencil reference value
  12455. * @returns a number defining the stencil reference value to use
  12456. */
  12457. Engine.prototype.getStencilFunctionReference = function () {
  12458. return this._stencilState.stencilFuncRef;
  12459. };
  12460. /**
  12461. * Gets the current stencil mask
  12462. * @returns a number defining the stencil mask to use
  12463. */
  12464. Engine.prototype.getStencilFunctionMask = function () {
  12465. return this._stencilState.stencilFuncMask;
  12466. };
  12467. /**
  12468. * Sets the current stencil function
  12469. * @param stencilFunc defines the new stencil function to use
  12470. */
  12471. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12472. this._stencilState.stencilFunc = stencilFunc;
  12473. };
  12474. /**
  12475. * Sets the current stencil reference
  12476. * @param reference defines the new stencil reference to use
  12477. */
  12478. Engine.prototype.setStencilFunctionReference = function (reference) {
  12479. this._stencilState.stencilFuncRef = reference;
  12480. };
  12481. /**
  12482. * Sets the current stencil mask
  12483. * @param mask defines the new stencil mask to use
  12484. */
  12485. Engine.prototype.setStencilFunctionMask = function (mask) {
  12486. this._stencilState.stencilFuncMask = mask;
  12487. };
  12488. /**
  12489. * Gets the current stencil operation when stencil fails
  12490. * @returns a number defining stencil operation to use when stencil fails
  12491. */
  12492. Engine.prototype.getStencilOperationFail = function () {
  12493. return this._stencilState.stencilOpStencilFail;
  12494. };
  12495. /**
  12496. * Gets the current stencil operation when depth fails
  12497. * @returns a number defining stencil operation to use when depth fails
  12498. */
  12499. Engine.prototype.getStencilOperationDepthFail = function () {
  12500. return this._stencilState.stencilOpDepthFail;
  12501. };
  12502. /**
  12503. * Gets the current stencil operation when stencil passes
  12504. * @returns a number defining stencil operation to use when stencil passes
  12505. */
  12506. Engine.prototype.getStencilOperationPass = function () {
  12507. return this._stencilState.stencilOpStencilDepthPass;
  12508. };
  12509. /**
  12510. * Sets the stencil operation to use when stencil fails
  12511. * @param operation defines the stencil operation to use when stencil fails
  12512. */
  12513. Engine.prototype.setStencilOperationFail = function (operation) {
  12514. this._stencilState.stencilOpStencilFail = operation;
  12515. };
  12516. /**
  12517. * Sets the stencil operation to use when depth fails
  12518. * @param operation defines the stencil operation to use when depth fails
  12519. */
  12520. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12521. this._stencilState.stencilOpDepthFail = operation;
  12522. };
  12523. /**
  12524. * Sets the stencil operation to use when stencil passes
  12525. * @param operation defines the stencil operation to use when stencil passes
  12526. */
  12527. Engine.prototype.setStencilOperationPass = function (operation) {
  12528. this._stencilState.stencilOpStencilDepthPass = operation;
  12529. };
  12530. /**
  12531. * Sets a boolean indicating if the dithering state is enabled or disabled
  12532. * @param value defines the dithering state
  12533. */
  12534. Engine.prototype.setDitheringState = function (value) {
  12535. if (value) {
  12536. this._gl.enable(this._gl.DITHER);
  12537. }
  12538. else {
  12539. this._gl.disable(this._gl.DITHER);
  12540. }
  12541. };
  12542. /**
  12543. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12544. * @param value defines the rasterizer state
  12545. */
  12546. Engine.prototype.setRasterizerState = function (value) {
  12547. if (value) {
  12548. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12549. }
  12550. else {
  12551. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12552. }
  12553. };
  12554. /**
  12555. * stop executing a render loop function and remove it from the execution array
  12556. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12557. */
  12558. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12559. if (!renderFunction) {
  12560. this._activeRenderLoops = [];
  12561. return;
  12562. }
  12563. var index = this._activeRenderLoops.indexOf(renderFunction);
  12564. if (index >= 0) {
  12565. this._activeRenderLoops.splice(index, 1);
  12566. }
  12567. };
  12568. /** @hidden */
  12569. Engine.prototype._renderLoop = function () {
  12570. if (!this._contextWasLost) {
  12571. var shouldRender = true;
  12572. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12573. shouldRender = false;
  12574. }
  12575. if (shouldRender) {
  12576. // Start new frame
  12577. this.beginFrame();
  12578. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12579. var renderFunction = this._activeRenderLoops[index];
  12580. renderFunction();
  12581. }
  12582. // Present
  12583. this.endFrame();
  12584. }
  12585. }
  12586. if (this._activeRenderLoops.length > 0) {
  12587. // Register new frame
  12588. var requester = null;
  12589. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12590. requester = this._vrDisplay;
  12591. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12592. }
  12593. else {
  12594. this._renderingQueueLaunched = false;
  12595. }
  12596. };
  12597. /**
  12598. * Register and execute a render loop. The engine can have more than one render function
  12599. * @param renderFunction defines the function to continuously execute
  12600. */
  12601. Engine.prototype.runRenderLoop = function (renderFunction) {
  12602. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12603. return;
  12604. }
  12605. this._activeRenderLoops.push(renderFunction);
  12606. if (!this._renderingQueueLaunched) {
  12607. this._renderingQueueLaunched = true;
  12608. this._bindedRenderFunction = this._renderLoop.bind(this);
  12609. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12610. }
  12611. };
  12612. /**
  12613. * Toggle full screen mode
  12614. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12615. * @param options defines an option object to be sent to the requestFullscreen function
  12616. */
  12617. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12618. if (this.isFullscreen) {
  12619. BABYLON.Tools.ExitFullscreen();
  12620. }
  12621. else {
  12622. this._pointerLockRequested = requestPointerLock;
  12623. if (this._renderingCanvas) {
  12624. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12625. }
  12626. }
  12627. };
  12628. /**
  12629. * Clear the current render buffer or the current render target (if any is set up)
  12630. * @param color defines the color to use
  12631. * @param backBuffer defines if the back buffer must be cleared
  12632. * @param depth defines if the depth buffer must be cleared
  12633. * @param stencil defines if the stencil buffer must be cleared
  12634. */
  12635. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12636. if (stencil === void 0) { stencil = false; }
  12637. this.applyStates();
  12638. var mode = 0;
  12639. if (backBuffer && color) {
  12640. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12641. mode |= this._gl.COLOR_BUFFER_BIT;
  12642. }
  12643. if (depth) {
  12644. this._gl.clearDepth(1.0);
  12645. mode |= this._gl.DEPTH_BUFFER_BIT;
  12646. }
  12647. if (stencil) {
  12648. this._gl.clearStencil(0);
  12649. mode |= this._gl.STENCIL_BUFFER_BIT;
  12650. }
  12651. this._gl.clear(mode);
  12652. };
  12653. /**
  12654. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12655. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12656. * @param y defines the y-coordinate of the corner of the clear rectangle
  12657. * @param width defines the width of the clear rectangle
  12658. * @param height defines the height of the clear rectangle
  12659. * @param clearColor defines the clear color
  12660. */
  12661. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12662. var gl = this._gl;
  12663. // Save state
  12664. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12665. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12666. // Change state
  12667. gl.enable(gl.SCISSOR_TEST);
  12668. gl.scissor(x, y, width, height);
  12669. // Clear
  12670. this.clear(clearColor, true, true, true);
  12671. // Restore state
  12672. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12673. if (curScissor === true) {
  12674. gl.enable(gl.SCISSOR_TEST);
  12675. }
  12676. else {
  12677. gl.disable(gl.SCISSOR_TEST);
  12678. }
  12679. };
  12680. /** @hidden */
  12681. Engine.prototype._viewport = function (x, y, width, height) {
  12682. if (x !== this._viewportCached.x ||
  12683. y !== this._viewportCached.y ||
  12684. width !== this._viewportCached.z ||
  12685. height !== this._viewportCached.w) {
  12686. this._viewportCached.x = x;
  12687. this._viewportCached.y = y;
  12688. this._viewportCached.z = width;
  12689. this._viewportCached.w = height;
  12690. this._gl.viewport(x, y, width, height);
  12691. }
  12692. };
  12693. /**
  12694. * Set the WebGL's viewport
  12695. * @param viewport defines the viewport element to be used
  12696. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12697. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12698. */
  12699. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12700. var width = requiredWidth || this.getRenderWidth();
  12701. var height = requiredHeight || this.getRenderHeight();
  12702. var x = viewport.x || 0;
  12703. var y = viewport.y || 0;
  12704. this._cachedViewport = viewport;
  12705. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12706. };
  12707. /**
  12708. * Directly set the WebGL Viewport
  12709. * @param x defines the x coordinate of the viewport (in screen space)
  12710. * @param y defines the y coordinate of the viewport (in screen space)
  12711. * @param width defines the width of the viewport (in screen space)
  12712. * @param height defines the height of the viewport (in screen space)
  12713. * @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
  12714. */
  12715. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12716. var currentViewport = this._cachedViewport;
  12717. this._cachedViewport = null;
  12718. this._viewport(x, y, width, height);
  12719. return currentViewport;
  12720. };
  12721. /**
  12722. * Begin a new frame
  12723. */
  12724. Engine.prototype.beginFrame = function () {
  12725. this.onBeginFrameObservable.notifyObservers(this);
  12726. this._measureFps();
  12727. };
  12728. /**
  12729. * Enf the current frame
  12730. */
  12731. Engine.prototype.endFrame = function () {
  12732. // Force a flush in case we are using a bad OS.
  12733. if (this._badOS) {
  12734. this.flushFramebuffer();
  12735. }
  12736. // Submit frame to the vr device, if enabled
  12737. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12738. // TODO: We should only submit the frame if we read frameData successfully.
  12739. this._vrDisplay.submitFrame();
  12740. }
  12741. this.onEndFrameObservable.notifyObservers(this);
  12742. };
  12743. /**
  12744. * Resize the view according to the canvas' size
  12745. */
  12746. Engine.prototype.resize = function () {
  12747. // We're not resizing the size of the canvas while in VR mode & presenting
  12748. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12749. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12750. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12751. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12752. }
  12753. };
  12754. /**
  12755. * Force a specific size of the canvas
  12756. * @param width defines the new canvas' width
  12757. * @param height defines the new canvas' height
  12758. */
  12759. Engine.prototype.setSize = function (width, height) {
  12760. if (!this._renderingCanvas) {
  12761. return;
  12762. }
  12763. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12764. return;
  12765. }
  12766. this._renderingCanvas.width = width;
  12767. this._renderingCanvas.height = height;
  12768. for (var index = 0; index < this.scenes.length; index++) {
  12769. var scene = this.scenes[index];
  12770. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12771. var cam = scene.cameras[camIndex];
  12772. cam._currentRenderId = 0;
  12773. }
  12774. }
  12775. if (this.onResizeObservable.hasObservers) {
  12776. this.onResizeObservable.notifyObservers(this);
  12777. }
  12778. };
  12779. // WebVR functions
  12780. /**
  12781. * Gets a boolean indicating if a webVR device was detected
  12782. * @returns true if a webVR device was detected
  12783. */
  12784. Engine.prototype.isVRDevicePresent = function () {
  12785. return !!this._vrDisplay;
  12786. };
  12787. /**
  12788. * Gets the current webVR device
  12789. * @returns the current webVR device (or null)
  12790. */
  12791. Engine.prototype.getVRDevice = function () {
  12792. return this._vrDisplay;
  12793. };
  12794. /**
  12795. * Initializes a webVR display and starts listening to display change events
  12796. * The onVRDisplayChangedObservable will be notified upon these changes
  12797. * @returns The onVRDisplayChangedObservable
  12798. */
  12799. Engine.prototype.initWebVR = function () {
  12800. this.initWebVRAsync();
  12801. return this.onVRDisplayChangedObservable;
  12802. };
  12803. /**
  12804. * Initializes a webVR display and starts listening to display change events
  12805. * The onVRDisplayChangedObservable will be notified upon these changes
  12806. * @returns A promise containing a VRDisplay and if vr is supported
  12807. */
  12808. Engine.prototype.initWebVRAsync = function () {
  12809. var _this = this;
  12810. var notifyObservers = function () {
  12811. var eventArgs = {
  12812. vrDisplay: _this._vrDisplay,
  12813. vrSupported: _this._vrSupported
  12814. };
  12815. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12816. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12817. };
  12818. if (!this._onVrDisplayConnect) {
  12819. this._onVrDisplayConnect = function (event) {
  12820. _this._vrDisplay = event.display;
  12821. notifyObservers();
  12822. };
  12823. this._onVrDisplayDisconnect = function () {
  12824. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12825. _this._vrDisplay = undefined;
  12826. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12827. notifyObservers();
  12828. };
  12829. this._onVrDisplayPresentChange = function () {
  12830. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12831. };
  12832. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12833. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12834. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12835. }
  12836. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12837. this._webVRInitPromise.then(notifyObservers);
  12838. return this._webVRInitPromise;
  12839. };
  12840. /**
  12841. * Call this function to switch to webVR mode
  12842. * Will do nothing if webVR is not supported or if there is no webVR device
  12843. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12844. */
  12845. Engine.prototype.enableVR = function () {
  12846. var _this = this;
  12847. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12848. var onResolved = function () {
  12849. _this.onVRRequestPresentComplete.notifyObservers(true);
  12850. _this._onVRFullScreenTriggered();
  12851. };
  12852. var onRejected = function () {
  12853. _this.onVRRequestPresentComplete.notifyObservers(false);
  12854. };
  12855. this.onVRRequestPresentStart.notifyObservers(this);
  12856. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12857. }
  12858. };
  12859. /**
  12860. * Call this function to leave webVR mode
  12861. * Will do nothing if webVR is not supported or if there is no webVR device
  12862. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12863. */
  12864. Engine.prototype.disableVR = function () {
  12865. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12866. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12867. }
  12868. };
  12869. Engine.prototype._getVRDisplaysAsync = function () {
  12870. var _this = this;
  12871. return new Promise(function (res, rej) {
  12872. if (navigator.getVRDisplays) {
  12873. navigator.getVRDisplays().then(function (devices) {
  12874. _this._vrSupported = true;
  12875. // note that devices may actually be an empty array. This is fine;
  12876. // we expect this._vrDisplay to be undefined in this case.
  12877. _this._vrDisplay = devices[0];
  12878. res({
  12879. vrDisplay: _this._vrDisplay,
  12880. vrSupported: _this._vrSupported
  12881. });
  12882. });
  12883. }
  12884. else {
  12885. _this._vrDisplay = undefined;
  12886. _this._vrSupported = false;
  12887. res({
  12888. vrDisplay: _this._vrDisplay,
  12889. vrSupported: _this._vrSupported
  12890. });
  12891. }
  12892. });
  12893. };
  12894. /**
  12895. * Binds the frame buffer to the specified texture.
  12896. * @param texture The texture to render to or null for the default canvas
  12897. * @param faceIndex The face of the texture to render to in case of cube texture
  12898. * @param requiredWidth The width of the target to render to
  12899. * @param requiredHeight The height of the target to render to
  12900. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12901. * @param depthStencilTexture The depth stencil texture to use to render
  12902. * @param lodLevel defines le lod level to bind to the frame buffer
  12903. */
  12904. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12905. if (lodLevel === void 0) { lodLevel = 0; }
  12906. if (this._currentRenderTarget) {
  12907. this.unBindFramebuffer(this._currentRenderTarget);
  12908. }
  12909. this._currentRenderTarget = texture;
  12910. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12911. var gl = this._gl;
  12912. if (texture.isCube) {
  12913. if (faceIndex === undefined) {
  12914. faceIndex = 0;
  12915. }
  12916. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12917. if (depthStencilTexture) {
  12918. if (depthStencilTexture._generateStencilBuffer) {
  12919. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12920. }
  12921. else {
  12922. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12923. }
  12924. }
  12925. }
  12926. if (this._cachedViewport && !forceFullscreenViewport) {
  12927. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12928. }
  12929. else {
  12930. if (!requiredWidth) {
  12931. requiredWidth = texture.width;
  12932. if (lodLevel) {
  12933. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12934. }
  12935. }
  12936. if (!requiredHeight) {
  12937. requiredHeight = texture.height;
  12938. if (lodLevel) {
  12939. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12940. }
  12941. }
  12942. this._viewport(0, 0, requiredWidth, requiredHeight);
  12943. }
  12944. this.wipeCaches();
  12945. };
  12946. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12947. if (this._currentFramebuffer !== framebuffer) {
  12948. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12949. this._currentFramebuffer = framebuffer;
  12950. }
  12951. };
  12952. /**
  12953. * Unbind the current render target texture from the webGL context
  12954. * @param texture defines the render target texture to unbind
  12955. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12956. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12957. */
  12958. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12959. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12960. this._currentRenderTarget = null;
  12961. // If MSAA, we need to bitblt back to main texture
  12962. var gl = this._gl;
  12963. if (texture._MSAAFramebuffer) {
  12964. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12965. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12966. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12967. }
  12968. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12969. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12970. gl.generateMipmap(gl.TEXTURE_2D);
  12971. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12972. }
  12973. if (onBeforeUnbind) {
  12974. if (texture._MSAAFramebuffer) {
  12975. // Bind the correct framebuffer
  12976. this.bindUnboundFramebuffer(texture._framebuffer);
  12977. }
  12978. onBeforeUnbind();
  12979. }
  12980. this.bindUnboundFramebuffer(null);
  12981. };
  12982. /**
  12983. * Unbind a list of render target textures from the webGL context
  12984. * This is used only when drawBuffer extension or webGL2 are active
  12985. * @param textures defines the render target textures to unbind
  12986. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12987. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12988. */
  12989. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12990. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12991. this._currentRenderTarget = null;
  12992. // If MSAA, we need to bitblt back to main texture
  12993. var gl = this._gl;
  12994. if (textures[0]._MSAAFramebuffer) {
  12995. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12996. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12997. var attachments = textures[0]._attachments;
  12998. if (!attachments) {
  12999. attachments = new Array(textures.length);
  13000. textures[0]._attachments = attachments;
  13001. }
  13002. for (var i = 0; i < textures.length; i++) {
  13003. var texture = textures[i];
  13004. for (var j = 0; j < attachments.length; j++) {
  13005. attachments[j] = gl.NONE;
  13006. }
  13007. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13008. gl.readBuffer(attachments[i]);
  13009. gl.drawBuffers(attachments);
  13010. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13011. }
  13012. for (var i = 0; i < attachments.length; i++) {
  13013. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13014. }
  13015. gl.drawBuffers(attachments);
  13016. }
  13017. for (var i = 0; i < textures.length; i++) {
  13018. var texture = textures[i];
  13019. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13020. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13021. gl.generateMipmap(gl.TEXTURE_2D);
  13022. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13023. }
  13024. }
  13025. if (onBeforeUnbind) {
  13026. if (textures[0]._MSAAFramebuffer) {
  13027. // Bind the correct framebuffer
  13028. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13029. }
  13030. onBeforeUnbind();
  13031. }
  13032. this.bindUnboundFramebuffer(null);
  13033. };
  13034. /**
  13035. * Force the mipmap generation for the given render target texture
  13036. * @param texture defines the render target texture to use
  13037. */
  13038. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13039. if (texture.generateMipMaps) {
  13040. var gl = this._gl;
  13041. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13042. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13043. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13044. }
  13045. };
  13046. /**
  13047. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13048. */
  13049. Engine.prototype.flushFramebuffer = function () {
  13050. this._gl.flush();
  13051. };
  13052. /**
  13053. * Unbind the current render target and bind the default framebuffer
  13054. */
  13055. Engine.prototype.restoreDefaultFramebuffer = function () {
  13056. if (this._currentRenderTarget) {
  13057. this.unBindFramebuffer(this._currentRenderTarget);
  13058. }
  13059. else {
  13060. this.bindUnboundFramebuffer(null);
  13061. }
  13062. if (this._cachedViewport) {
  13063. this.setViewport(this._cachedViewport);
  13064. }
  13065. this.wipeCaches();
  13066. };
  13067. // UBOs
  13068. /**
  13069. * Create an uniform buffer
  13070. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13071. * @param elements defines the content of the uniform buffer
  13072. * @returns the webGL uniform buffer
  13073. */
  13074. Engine.prototype.createUniformBuffer = function (elements) {
  13075. var ubo = this._gl.createBuffer();
  13076. if (!ubo) {
  13077. throw new Error("Unable to create uniform buffer");
  13078. }
  13079. this.bindUniformBuffer(ubo);
  13080. if (elements instanceof Float32Array) {
  13081. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13082. }
  13083. else {
  13084. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13085. }
  13086. this.bindUniformBuffer(null);
  13087. ubo.references = 1;
  13088. return ubo;
  13089. };
  13090. /**
  13091. * Create a dynamic uniform buffer
  13092. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13093. * @param elements defines the content of the uniform buffer
  13094. * @returns the webGL uniform buffer
  13095. */
  13096. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13097. var ubo = this._gl.createBuffer();
  13098. if (!ubo) {
  13099. throw new Error("Unable to create dynamic uniform buffer");
  13100. }
  13101. this.bindUniformBuffer(ubo);
  13102. if (elements instanceof Float32Array) {
  13103. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13104. }
  13105. else {
  13106. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13107. }
  13108. this.bindUniformBuffer(null);
  13109. ubo.references = 1;
  13110. return ubo;
  13111. };
  13112. /**
  13113. * Update an existing uniform buffer
  13114. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13115. * @param uniformBuffer defines the target uniform buffer
  13116. * @param elements defines the content to update
  13117. * @param offset defines the offset in the uniform buffer where update should start
  13118. * @param count defines the size of the data to update
  13119. */
  13120. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13121. this.bindUniformBuffer(uniformBuffer);
  13122. if (offset === undefined) {
  13123. offset = 0;
  13124. }
  13125. if (count === undefined) {
  13126. if (elements instanceof Float32Array) {
  13127. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13128. }
  13129. else {
  13130. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13131. }
  13132. }
  13133. else {
  13134. if (elements instanceof Float32Array) {
  13135. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13136. }
  13137. else {
  13138. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13139. }
  13140. }
  13141. this.bindUniformBuffer(null);
  13142. };
  13143. // VBOs
  13144. Engine.prototype._resetVertexBufferBinding = function () {
  13145. this.bindArrayBuffer(null);
  13146. this._cachedVertexBuffers = null;
  13147. };
  13148. /**
  13149. * Creates a vertex buffer
  13150. * @param data the data for the vertex buffer
  13151. * @returns the new WebGL static buffer
  13152. */
  13153. Engine.prototype.createVertexBuffer = function (data) {
  13154. var vbo = this._gl.createBuffer();
  13155. if (!vbo) {
  13156. throw new Error("Unable to create vertex buffer");
  13157. }
  13158. this.bindArrayBuffer(vbo);
  13159. if (data instanceof Array) {
  13160. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13161. }
  13162. else {
  13163. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13164. }
  13165. this._resetVertexBufferBinding();
  13166. vbo.references = 1;
  13167. return vbo;
  13168. };
  13169. /**
  13170. * Creates a dynamic vertex buffer
  13171. * @param data the data for the dynamic vertex buffer
  13172. * @returns the new WebGL dynamic buffer
  13173. */
  13174. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13175. var vbo = this._gl.createBuffer();
  13176. if (!vbo) {
  13177. throw new Error("Unable to create dynamic vertex buffer");
  13178. }
  13179. this.bindArrayBuffer(vbo);
  13180. if (data instanceof Array) {
  13181. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13182. }
  13183. else {
  13184. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13185. }
  13186. this._resetVertexBufferBinding();
  13187. vbo.references = 1;
  13188. return vbo;
  13189. };
  13190. /**
  13191. * Update a dynamic index buffer
  13192. * @param indexBuffer defines the target index buffer
  13193. * @param indices defines the data to update
  13194. * @param offset defines the offset in the target index buffer where update should start
  13195. */
  13196. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13197. if (offset === void 0) { offset = 0; }
  13198. // Force cache update
  13199. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13200. this.bindIndexBuffer(indexBuffer);
  13201. var arrayBuffer;
  13202. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13203. arrayBuffer = indices;
  13204. }
  13205. else {
  13206. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13207. }
  13208. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13209. this._resetIndexBufferBinding();
  13210. };
  13211. /**
  13212. * Updates a dynamic vertex buffer.
  13213. * @param vertexBuffer the vertex buffer to update
  13214. * @param data the data used to update the vertex buffer
  13215. * @param byteOffset the byte offset of the data
  13216. * @param byteLength the byte length of the data
  13217. */
  13218. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13219. this.bindArrayBuffer(vertexBuffer);
  13220. if (byteOffset === undefined) {
  13221. byteOffset = 0;
  13222. }
  13223. if (byteLength === undefined) {
  13224. if (data instanceof Array) {
  13225. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13226. }
  13227. else {
  13228. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13229. }
  13230. }
  13231. else {
  13232. if (data instanceof Array) {
  13233. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13234. }
  13235. else {
  13236. if (data instanceof ArrayBuffer) {
  13237. data = new Uint8Array(data, byteOffset, byteLength);
  13238. }
  13239. else {
  13240. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13241. }
  13242. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13243. }
  13244. }
  13245. this._resetVertexBufferBinding();
  13246. };
  13247. Engine.prototype._resetIndexBufferBinding = function () {
  13248. this.bindIndexBuffer(null);
  13249. this._cachedIndexBuffer = null;
  13250. };
  13251. /**
  13252. * Creates a new index buffer
  13253. * @param indices defines the content of the index buffer
  13254. * @param updatable defines if the index buffer must be updatable
  13255. * @returns a new webGL buffer
  13256. */
  13257. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13258. var vbo = this._gl.createBuffer();
  13259. if (!vbo) {
  13260. throw new Error("Unable to create index buffer");
  13261. }
  13262. this.bindIndexBuffer(vbo);
  13263. // Check for 32 bits indices
  13264. var arrayBuffer;
  13265. var need32Bits = false;
  13266. if (indices instanceof Uint16Array) {
  13267. arrayBuffer = indices;
  13268. }
  13269. else {
  13270. //check 32 bit support
  13271. if (this._caps.uintIndices) {
  13272. if (indices instanceof Uint32Array) {
  13273. arrayBuffer = indices;
  13274. need32Bits = true;
  13275. }
  13276. else {
  13277. //number[] or Int32Array, check if 32 bit is necessary
  13278. for (var index = 0; index < indices.length; index++) {
  13279. if (indices[index] > 65535) {
  13280. need32Bits = true;
  13281. break;
  13282. }
  13283. }
  13284. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13285. }
  13286. }
  13287. else {
  13288. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13289. arrayBuffer = new Uint16Array(indices);
  13290. }
  13291. }
  13292. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13293. this._resetIndexBufferBinding();
  13294. vbo.references = 1;
  13295. vbo.is32Bits = need32Bits;
  13296. return vbo;
  13297. };
  13298. /**
  13299. * Bind a webGL buffer to the webGL context
  13300. * @param buffer defines the buffer to bind
  13301. */
  13302. Engine.prototype.bindArrayBuffer = function (buffer) {
  13303. if (!this._vaoRecordInProgress) {
  13304. this._unbindVertexArrayObject();
  13305. }
  13306. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13307. };
  13308. /**
  13309. * Bind an uniform buffer to the current webGL context
  13310. * @param buffer defines the buffer to bind
  13311. */
  13312. Engine.prototype.bindUniformBuffer = function (buffer) {
  13313. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13314. };
  13315. /**
  13316. * Bind a buffer to the current webGL context at a given location
  13317. * @param buffer defines the buffer to bind
  13318. * @param location defines the index where to bind the buffer
  13319. */
  13320. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13321. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13322. };
  13323. /**
  13324. * Bind a specific block at a given index in a specific shader program
  13325. * @param shaderProgram defines the shader program
  13326. * @param blockName defines the block name
  13327. * @param index defines the index where to bind the block
  13328. */
  13329. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13330. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13331. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13332. };
  13333. ;
  13334. Engine.prototype.bindIndexBuffer = function (buffer) {
  13335. if (!this._vaoRecordInProgress) {
  13336. this._unbindVertexArrayObject();
  13337. }
  13338. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13339. };
  13340. Engine.prototype.bindBuffer = function (buffer, target) {
  13341. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13342. this._gl.bindBuffer(target, buffer);
  13343. this._currentBoundBuffer[target] = buffer;
  13344. }
  13345. };
  13346. /**
  13347. * update the bound buffer with the given data
  13348. * @param data defines the data to update
  13349. */
  13350. Engine.prototype.updateArrayBuffer = function (data) {
  13351. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13352. };
  13353. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13354. var pointer = this._currentBufferPointers[indx];
  13355. var changed = false;
  13356. if (!pointer.active) {
  13357. changed = true;
  13358. pointer.active = true;
  13359. pointer.index = indx;
  13360. pointer.size = size;
  13361. pointer.type = type;
  13362. pointer.normalized = normalized;
  13363. pointer.stride = stride;
  13364. pointer.offset = offset;
  13365. pointer.buffer = buffer;
  13366. }
  13367. else {
  13368. if (pointer.buffer !== buffer) {
  13369. pointer.buffer = buffer;
  13370. changed = true;
  13371. }
  13372. if (pointer.size !== size) {
  13373. pointer.size = size;
  13374. changed = true;
  13375. }
  13376. if (pointer.type !== type) {
  13377. pointer.type = type;
  13378. changed = true;
  13379. }
  13380. if (pointer.normalized !== normalized) {
  13381. pointer.normalized = normalized;
  13382. changed = true;
  13383. }
  13384. if (pointer.stride !== stride) {
  13385. pointer.stride = stride;
  13386. changed = true;
  13387. }
  13388. if (pointer.offset !== offset) {
  13389. pointer.offset = offset;
  13390. changed = true;
  13391. }
  13392. }
  13393. if (changed || this._vaoRecordInProgress) {
  13394. this.bindArrayBuffer(buffer);
  13395. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13396. }
  13397. };
  13398. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13399. if (indexBuffer == null) {
  13400. return;
  13401. }
  13402. if (this._cachedIndexBuffer !== indexBuffer) {
  13403. this._cachedIndexBuffer = indexBuffer;
  13404. this.bindIndexBuffer(indexBuffer);
  13405. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13406. }
  13407. };
  13408. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13409. var attributes = effect.getAttributesNames();
  13410. if (!this._vaoRecordInProgress) {
  13411. this._unbindVertexArrayObject();
  13412. }
  13413. this.unbindAllAttributes();
  13414. for (var index = 0; index < attributes.length; index++) {
  13415. var order = effect.getAttributeLocation(index);
  13416. if (order >= 0) {
  13417. var vertexBuffer = vertexBuffers[attributes[index]];
  13418. if (!vertexBuffer) {
  13419. continue;
  13420. }
  13421. this._gl.enableVertexAttribArray(order);
  13422. if (!this._vaoRecordInProgress) {
  13423. this._vertexAttribArraysEnabled[order] = true;
  13424. }
  13425. var buffer = vertexBuffer.getBuffer();
  13426. if (buffer) {
  13427. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13428. if (vertexBuffer.getIsInstanced()) {
  13429. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13430. if (!this._vaoRecordInProgress) {
  13431. this._currentInstanceLocations.push(order);
  13432. this._currentInstanceBuffers.push(buffer);
  13433. }
  13434. }
  13435. }
  13436. }
  13437. }
  13438. };
  13439. /**
  13440. * Records a vertex array object
  13441. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13442. * @param vertexBuffers defines the list of vertex buffers to store
  13443. * @param indexBuffer defines the index buffer to store
  13444. * @param effect defines the effect to store
  13445. * @returns the new vertex array object
  13446. */
  13447. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13448. var vao = this._gl.createVertexArray();
  13449. this._vaoRecordInProgress = true;
  13450. this._gl.bindVertexArray(vao);
  13451. this._mustWipeVertexAttributes = true;
  13452. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13453. this.bindIndexBuffer(indexBuffer);
  13454. this._vaoRecordInProgress = false;
  13455. this._gl.bindVertexArray(null);
  13456. return vao;
  13457. };
  13458. /**
  13459. * Bind a specific vertex array object
  13460. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13461. * @param vertexArrayObject defines the vertex array object to bind
  13462. * @param indexBuffer defines the index buffer to bind
  13463. */
  13464. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13465. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13466. this._cachedVertexArrayObject = vertexArrayObject;
  13467. this._gl.bindVertexArray(vertexArrayObject);
  13468. this._cachedVertexBuffers = null;
  13469. this._cachedIndexBuffer = null;
  13470. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13471. this._mustWipeVertexAttributes = true;
  13472. }
  13473. };
  13474. /**
  13475. * Bind webGl buffers directly to the webGL context
  13476. * @param vertexBuffer defines the vertex buffer to bind
  13477. * @param indexBuffer defines the index buffer to bind
  13478. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13479. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13480. * @param effect defines the effect associated with the vertex buffer
  13481. */
  13482. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13483. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13484. this._cachedVertexBuffers = vertexBuffer;
  13485. this._cachedEffectForVertexBuffers = effect;
  13486. var attributesCount = effect.getAttributesCount();
  13487. this._unbindVertexArrayObject();
  13488. this.unbindAllAttributes();
  13489. var offset = 0;
  13490. for (var index = 0; index < attributesCount; index++) {
  13491. if (index < vertexDeclaration.length) {
  13492. var order = effect.getAttributeLocation(index);
  13493. if (order >= 0) {
  13494. this._gl.enableVertexAttribArray(order);
  13495. this._vertexAttribArraysEnabled[order] = true;
  13496. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13497. }
  13498. offset += vertexDeclaration[index] * 4;
  13499. }
  13500. }
  13501. }
  13502. this._bindIndexBufferWithCache(indexBuffer);
  13503. };
  13504. Engine.prototype._unbindVertexArrayObject = function () {
  13505. if (!this._cachedVertexArrayObject) {
  13506. return;
  13507. }
  13508. this._cachedVertexArrayObject = null;
  13509. this._gl.bindVertexArray(null);
  13510. };
  13511. /**
  13512. * Bind a list of vertex buffers to the webGL context
  13513. * @param vertexBuffers defines the list of vertex buffers to bind
  13514. * @param indexBuffer defines the index buffer to bind
  13515. * @param effect defines the effect associated with the vertex buffers
  13516. */
  13517. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13518. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13519. this._cachedVertexBuffers = vertexBuffers;
  13520. this._cachedEffectForVertexBuffers = effect;
  13521. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13522. }
  13523. this._bindIndexBufferWithCache(indexBuffer);
  13524. };
  13525. /**
  13526. * Unbind all instance attributes
  13527. */
  13528. Engine.prototype.unbindInstanceAttributes = function () {
  13529. var boundBuffer;
  13530. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13531. var instancesBuffer = this._currentInstanceBuffers[i];
  13532. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13533. boundBuffer = instancesBuffer;
  13534. this.bindArrayBuffer(instancesBuffer);
  13535. }
  13536. var offsetLocation = this._currentInstanceLocations[i];
  13537. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13538. }
  13539. this._currentInstanceBuffers.length = 0;
  13540. this._currentInstanceLocations.length = 0;
  13541. };
  13542. /**
  13543. * Release and free the memory of a vertex array object
  13544. * @param vao defines the vertex array object to delete
  13545. */
  13546. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13547. this._gl.deleteVertexArray(vao);
  13548. };
  13549. /** @hidden */
  13550. Engine.prototype._releaseBuffer = function (buffer) {
  13551. buffer.references--;
  13552. if (buffer.references === 0) {
  13553. this._gl.deleteBuffer(buffer);
  13554. return true;
  13555. }
  13556. return false;
  13557. };
  13558. /**
  13559. * Creates a webGL buffer to use with instanciation
  13560. * @param capacity defines the size of the buffer
  13561. * @returns the webGL buffer
  13562. */
  13563. Engine.prototype.createInstancesBuffer = function (capacity) {
  13564. var buffer = this._gl.createBuffer();
  13565. if (!buffer) {
  13566. throw new Error("Unable to create instance buffer");
  13567. }
  13568. buffer.capacity = capacity;
  13569. this.bindArrayBuffer(buffer);
  13570. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13571. return buffer;
  13572. };
  13573. /**
  13574. * Delete a webGL buffer used with instanciation
  13575. * @param buffer defines the webGL buffer to delete
  13576. */
  13577. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13578. this._gl.deleteBuffer(buffer);
  13579. };
  13580. /**
  13581. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13582. * @param instancesBuffer defines the webGL buffer to update and bind
  13583. * @param data defines the data to store in the buffer
  13584. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13585. */
  13586. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13587. this.bindArrayBuffer(instancesBuffer);
  13588. if (data) {
  13589. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13590. }
  13591. if (offsetLocations[0].index !== undefined) {
  13592. var stride = 0;
  13593. for (var i = 0; i < offsetLocations.length; i++) {
  13594. var ai = offsetLocations[i];
  13595. stride += ai.attributeSize * 4;
  13596. }
  13597. for (var i = 0; i < offsetLocations.length; i++) {
  13598. var ai = offsetLocations[i];
  13599. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13600. this._gl.enableVertexAttribArray(ai.index);
  13601. this._vertexAttribArraysEnabled[ai.index] = true;
  13602. }
  13603. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13604. this._gl.vertexAttribDivisor(ai.index, 1);
  13605. this._currentInstanceLocations.push(ai.index);
  13606. this._currentInstanceBuffers.push(instancesBuffer);
  13607. }
  13608. }
  13609. else {
  13610. for (var index = 0; index < 4; index++) {
  13611. var offsetLocation = offsetLocations[index];
  13612. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13613. this._gl.enableVertexAttribArray(offsetLocation);
  13614. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13615. }
  13616. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13617. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13618. this._currentInstanceLocations.push(offsetLocation);
  13619. this._currentInstanceBuffers.push(instancesBuffer);
  13620. }
  13621. }
  13622. };
  13623. /**
  13624. * Apply all cached states (depth, culling, stencil and alpha)
  13625. */
  13626. Engine.prototype.applyStates = function () {
  13627. this._depthCullingState.apply(this._gl);
  13628. this._stencilState.apply(this._gl);
  13629. this._alphaState.apply(this._gl);
  13630. };
  13631. /**
  13632. * Send a draw order
  13633. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13634. * @param indexStart defines the starting index
  13635. * @param indexCount defines the number of index to draw
  13636. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13637. */
  13638. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13639. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13640. };
  13641. /**
  13642. * Draw a list of points
  13643. * @param verticesStart defines the index of first vertex to draw
  13644. * @param verticesCount defines the count of vertices to draw
  13645. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13646. */
  13647. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13648. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13649. };
  13650. /**
  13651. * Draw a list of unindexed primitives
  13652. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13653. * @param verticesStart defines the index of first vertex to draw
  13654. * @param verticesCount defines the count of vertices to draw
  13655. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13656. */
  13657. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13658. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13659. };
  13660. /**
  13661. * Draw a list of indexed primitives
  13662. * @param fillMode defines the primitive to use
  13663. * @param indexStart defines the starting index
  13664. * @param indexCount defines the number of index to draw
  13665. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13666. */
  13667. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13668. // Apply states
  13669. this.applyStates();
  13670. this._drawCalls.addCount(1, false);
  13671. // Render
  13672. var drawMode = this._drawMode(fillMode);
  13673. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13674. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13675. if (instancesCount) {
  13676. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13677. }
  13678. else {
  13679. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13680. }
  13681. };
  13682. /**
  13683. * Draw a list of unindexed primitives
  13684. * @param fillMode defines the primitive to use
  13685. * @param verticesStart defines the index of first vertex to draw
  13686. * @param verticesCount defines the count of vertices to draw
  13687. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13688. */
  13689. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13690. // Apply states
  13691. this.applyStates();
  13692. this._drawCalls.addCount(1, false);
  13693. var drawMode = this._drawMode(fillMode);
  13694. if (instancesCount) {
  13695. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13696. }
  13697. else {
  13698. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13699. }
  13700. };
  13701. Engine.prototype._drawMode = function (fillMode) {
  13702. switch (fillMode) {
  13703. // Triangle views
  13704. case BABYLON.Material.TriangleFillMode:
  13705. return this._gl.TRIANGLES;
  13706. case BABYLON.Material.PointFillMode:
  13707. return this._gl.POINTS;
  13708. case BABYLON.Material.WireFrameFillMode:
  13709. return this._gl.LINES;
  13710. // Draw modes
  13711. case BABYLON.Material.PointListDrawMode:
  13712. return this._gl.POINTS;
  13713. case BABYLON.Material.LineListDrawMode:
  13714. return this._gl.LINES;
  13715. case BABYLON.Material.LineLoopDrawMode:
  13716. return this._gl.LINE_LOOP;
  13717. case BABYLON.Material.LineStripDrawMode:
  13718. return this._gl.LINE_STRIP;
  13719. case BABYLON.Material.TriangleStripDrawMode:
  13720. return this._gl.TRIANGLE_STRIP;
  13721. case BABYLON.Material.TriangleFanDrawMode:
  13722. return this._gl.TRIANGLE_FAN;
  13723. default:
  13724. return this._gl.TRIANGLES;
  13725. }
  13726. };
  13727. // Shaders
  13728. /** @hidden */
  13729. Engine.prototype._releaseEffect = function (effect) {
  13730. if (this._compiledEffects[effect._key]) {
  13731. delete this._compiledEffects[effect._key];
  13732. this._deleteProgram(effect.getProgram());
  13733. }
  13734. };
  13735. /** @hidden */
  13736. Engine.prototype._deleteProgram = function (program) {
  13737. if (program) {
  13738. program.__SPECTOR_rebuildProgram = null;
  13739. if (program.transformFeedback) {
  13740. this.deleteTransformFeedback(program.transformFeedback);
  13741. program.transformFeedback = null;
  13742. }
  13743. this._gl.deleteProgram(program);
  13744. }
  13745. };
  13746. /**
  13747. * Create a new effect (used to store vertex/fragment shaders)
  13748. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13749. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13750. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13751. * @param samplers defines an array of string used to represent textures
  13752. * @param defines defines the string containing the defines to use to compile the shaders
  13753. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13754. * @param onCompiled defines a function to call when the effect creation is successful
  13755. * @param onError defines a function to call when the effect creation has failed
  13756. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13757. * @returns the new Effect
  13758. */
  13759. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13760. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13761. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13762. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13763. if (this._compiledEffects[name]) {
  13764. var compiledEffect = this._compiledEffects[name];
  13765. if (onCompiled && compiledEffect.isReady()) {
  13766. onCompiled(compiledEffect);
  13767. }
  13768. return compiledEffect;
  13769. }
  13770. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13771. effect._key = name;
  13772. this._compiledEffects[name] = effect;
  13773. return effect;
  13774. };
  13775. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13776. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13777. };
  13778. ;
  13779. Engine.prototype._compileRawShader = function (source, type) {
  13780. var gl = this._gl;
  13781. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13782. gl.shaderSource(shader, source);
  13783. gl.compileShader(shader);
  13784. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13785. var log = gl.getShaderInfoLog(shader);
  13786. if (log) {
  13787. throw new Error(log);
  13788. }
  13789. }
  13790. if (!shader) {
  13791. throw new Error("Something went wrong while compile the shader.");
  13792. }
  13793. return shader;
  13794. };
  13795. ;
  13796. /**
  13797. * Directly creates a webGL program
  13798. * @param vertexCode defines the vertex shader code to use
  13799. * @param fragmentCode defines the fragment shader code to use
  13800. * @param context defines the webGL context to use (if not set, the current one will be used)
  13801. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13802. * @returns the new webGL program
  13803. */
  13804. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13805. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13806. context = context || this._gl;
  13807. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13808. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13809. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13810. };
  13811. /**
  13812. * Creates a webGL program
  13813. * @param vertexCode defines the vertex shader code to use
  13814. * @param fragmentCode defines the fragment shader code to use
  13815. * @param defines defines the string containing the defines to use to compile the shaders
  13816. * @param context defines the webGL context to use (if not set, the current one will be used)
  13817. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13818. * @returns the new webGL program
  13819. */
  13820. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13821. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13822. context = context || this._gl;
  13823. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13824. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13825. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13826. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13827. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13828. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13829. return program;
  13830. };
  13831. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13832. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13833. var shaderProgram = context.createProgram();
  13834. if (!shaderProgram) {
  13835. throw new Error("Unable to create program");
  13836. }
  13837. context.attachShader(shaderProgram, vertexShader);
  13838. context.attachShader(shaderProgram, fragmentShader);
  13839. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13840. var transformFeedback = this.createTransformFeedback();
  13841. this.bindTransformFeedback(transformFeedback);
  13842. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13843. shaderProgram.transformFeedback = transformFeedback;
  13844. }
  13845. context.linkProgram(shaderProgram);
  13846. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13847. this.bindTransformFeedback(null);
  13848. }
  13849. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13850. if (!linked) {
  13851. var error = context.getProgramInfoLog(shaderProgram);
  13852. if (error) {
  13853. throw new Error(error);
  13854. }
  13855. }
  13856. if (this.validateShaderPrograms) {
  13857. context.validateProgram(shaderProgram);
  13858. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13859. if (!validated) {
  13860. var error = context.getProgramInfoLog(shaderProgram);
  13861. if (error) {
  13862. throw new Error(error);
  13863. }
  13864. }
  13865. }
  13866. context.deleteShader(vertexShader);
  13867. context.deleteShader(fragmentShader);
  13868. return shaderProgram;
  13869. };
  13870. /**
  13871. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13872. * @param shaderProgram defines the webGL program to use
  13873. * @param uniformsNames defines the list of uniform names
  13874. * @returns an array of webGL uniform locations
  13875. */
  13876. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13877. var results = new Array();
  13878. for (var index = 0; index < uniformsNames.length; index++) {
  13879. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13880. }
  13881. return results;
  13882. };
  13883. /**
  13884. * Gets the lsit of active attributes for a given webGL program
  13885. * @param shaderProgram defines the webGL program to use
  13886. * @param attributesNames defines the list of attribute names to get
  13887. * @returns an array of indices indicating the offset of each attribute
  13888. */
  13889. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13890. var results = [];
  13891. for (var index = 0; index < attributesNames.length; index++) {
  13892. try {
  13893. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13894. }
  13895. catch (e) {
  13896. results.push(-1);
  13897. }
  13898. }
  13899. return results;
  13900. };
  13901. /**
  13902. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13903. * @param effect defines the effect to activate
  13904. */
  13905. Engine.prototype.enableEffect = function (effect) {
  13906. if (!effect || effect === this._currentEffect) {
  13907. return;
  13908. }
  13909. // Use program
  13910. this.bindSamplers(effect);
  13911. this._currentEffect = effect;
  13912. if (effect.onBind) {
  13913. effect.onBind(effect);
  13914. }
  13915. if (effect._onBindObservable) {
  13916. effect._onBindObservable.notifyObservers(effect);
  13917. }
  13918. };
  13919. /**
  13920. * Set the value of an uniform to an array of int32
  13921. * @param uniform defines the webGL uniform location where to store the value
  13922. * @param array defines the array of int32 to store
  13923. */
  13924. Engine.prototype.setIntArray = function (uniform, array) {
  13925. if (!uniform)
  13926. return;
  13927. this._gl.uniform1iv(uniform, array);
  13928. };
  13929. /**
  13930. * Set the value of an uniform to an array of int32 (stored as vec2)
  13931. * @param uniform defines the webGL uniform location where to store the value
  13932. * @param array defines the array of int32 to store
  13933. */
  13934. Engine.prototype.setIntArray2 = function (uniform, array) {
  13935. if (!uniform || array.length % 2 !== 0)
  13936. return;
  13937. this._gl.uniform2iv(uniform, array);
  13938. };
  13939. /**
  13940. * Set the value of an uniform to an array of int32 (stored as vec3)
  13941. * @param uniform defines the webGL uniform location where to store the value
  13942. * @param array defines the array of int32 to store
  13943. */
  13944. Engine.prototype.setIntArray3 = function (uniform, array) {
  13945. if (!uniform || array.length % 3 !== 0)
  13946. return;
  13947. this._gl.uniform3iv(uniform, array);
  13948. };
  13949. /**
  13950. * Set the value of an uniform to an array of int32 (stored as vec4)
  13951. * @param uniform defines the webGL uniform location where to store the value
  13952. * @param array defines the array of int32 to store
  13953. */
  13954. Engine.prototype.setIntArray4 = function (uniform, array) {
  13955. if (!uniform || array.length % 4 !== 0)
  13956. return;
  13957. this._gl.uniform4iv(uniform, array);
  13958. };
  13959. /**
  13960. * Set the value of an uniform to an array of float32
  13961. * @param uniform defines the webGL uniform location where to store the value
  13962. * @param array defines the array of float32 to store
  13963. */
  13964. Engine.prototype.setFloatArray = function (uniform, array) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform1fv(uniform, array);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to an array of float32 (stored as vec2)
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param array defines the array of float32 to store
  13973. */
  13974. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13975. if (!uniform || array.length % 2 !== 0)
  13976. return;
  13977. this._gl.uniform2fv(uniform, array);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to an array of float32 (stored as vec3)
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param array defines the array of float32 to store
  13983. */
  13984. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13985. if (!uniform || array.length % 3 !== 0)
  13986. return;
  13987. this._gl.uniform3fv(uniform, array);
  13988. };
  13989. /**
  13990. * Set the value of an uniform to an array of float32 (stored as vec4)
  13991. * @param uniform defines the webGL uniform location where to store the value
  13992. * @param array defines the array of float32 to store
  13993. */
  13994. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13995. if (!uniform || array.length % 4 !== 0)
  13996. return;
  13997. this._gl.uniform4fv(uniform, array);
  13998. };
  13999. /**
  14000. * Set the value of an uniform to an array of number
  14001. * @param uniform defines the webGL uniform location where to store the value
  14002. * @param array defines the array of number to store
  14003. */
  14004. Engine.prototype.setArray = function (uniform, array) {
  14005. if (!uniform)
  14006. return;
  14007. this._gl.uniform1fv(uniform, array);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to an array of number (stored as vec2)
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param array defines the array of number to store
  14013. */
  14014. Engine.prototype.setArray2 = function (uniform, array) {
  14015. if (!uniform || array.length % 2 !== 0)
  14016. return;
  14017. this._gl.uniform2fv(uniform, array);
  14018. };
  14019. /**
  14020. * Set the value of an uniform to an array of number (stored as vec3)
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param array defines the array of number to store
  14023. */
  14024. Engine.prototype.setArray3 = function (uniform, array) {
  14025. if (!uniform || array.length % 3 !== 0)
  14026. return;
  14027. this._gl.uniform3fv(uniform, array);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to an array of number (stored as vec4)
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param array defines the array of number to store
  14033. */
  14034. Engine.prototype.setArray4 = function (uniform, array) {
  14035. if (!uniform || array.length % 4 !== 0)
  14036. return;
  14037. this._gl.uniform4fv(uniform, array);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of float32 (stored as matrices)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param matrices defines the array of float32 to store
  14043. */
  14044. Engine.prototype.setMatrices = function (uniform, matrices) {
  14045. if (!uniform)
  14046. return;
  14047. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to a matrix
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param matrix defines the matrix to store
  14053. */
  14054. Engine.prototype.setMatrix = function (uniform, matrix) {
  14055. if (!uniform)
  14056. return;
  14057. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14058. };
  14059. /**
  14060. * Set the value of an uniform to a matrix (3x3)
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14063. */
  14064. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14065. if (!uniform)
  14066. return;
  14067. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to a matrix (2x2)
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14073. */
  14074. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14075. if (!uniform)
  14076. return;
  14077. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to a number (int)
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param value defines the int number to store
  14083. */
  14084. Engine.prototype.setInt = function (uniform, value) {
  14085. if (!uniform)
  14086. return;
  14087. this._gl.uniform1i(uniform, value);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to a number (float)
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param value defines the float number to store
  14093. */
  14094. Engine.prototype.setFloat = function (uniform, value) {
  14095. if (!uniform)
  14096. return;
  14097. this._gl.uniform1f(uniform, value);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to a vec2
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param x defines the 1st component of the value
  14103. * @param y defines the 2nd component of the value
  14104. */
  14105. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14106. if (!uniform)
  14107. return;
  14108. this._gl.uniform2f(uniform, x, y);
  14109. };
  14110. /**
  14111. * Set the value of an uniform to a vec3
  14112. * @param uniform defines the webGL uniform location where to store the value
  14113. * @param x defines the 1st component of the value
  14114. * @param y defines the 2nd component of the value
  14115. * @param z defines the 3rd component of the value
  14116. */
  14117. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14118. if (!uniform)
  14119. return;
  14120. this._gl.uniform3f(uniform, x, y, z);
  14121. };
  14122. /**
  14123. * Set the value of an uniform to a boolean
  14124. * @param uniform defines the webGL uniform location where to store the value
  14125. * @param bool defines the boolean to store
  14126. */
  14127. Engine.prototype.setBool = function (uniform, bool) {
  14128. if (!uniform)
  14129. return;
  14130. this._gl.uniform1i(uniform, bool);
  14131. };
  14132. /**
  14133. * Set the value of an uniform to a vec4
  14134. * @param uniform defines the webGL uniform location where to store the value
  14135. * @param x defines the 1st component of the value
  14136. * @param y defines the 2nd component of the value
  14137. * @param z defines the 3rd component of the value
  14138. * @param w defines the 4th component of the value
  14139. */
  14140. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14141. if (!uniform)
  14142. return;
  14143. this._gl.uniform4f(uniform, x, y, z, w);
  14144. };
  14145. /**
  14146. * Set the value of an uniform to a Color3
  14147. * @param uniform defines the webGL uniform location where to store the value
  14148. * @param color3 defines the color to store
  14149. */
  14150. Engine.prototype.setColor3 = function (uniform, color3) {
  14151. if (!uniform)
  14152. return;
  14153. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14154. };
  14155. /**
  14156. * Set the value of an uniform to a Color3 and an alpha value
  14157. * @param uniform defines the webGL uniform location where to store the value
  14158. * @param color3 defines the color to store
  14159. * @param alpha defines the alpha component to store
  14160. */
  14161. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14162. if (!uniform)
  14163. return;
  14164. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14165. };
  14166. /**
  14167. * Sets a Color4 on a uniform variable
  14168. * @param uniform defines the uniform location
  14169. * @param color4 defines the value to be set
  14170. */
  14171. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14172. if (!uniform)
  14173. return;
  14174. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14175. };
  14176. // States
  14177. /**
  14178. * Set various states to the webGL context
  14179. * @param culling defines backface culling state
  14180. * @param zOffset defines the value to apply to zOffset (0 by default)
  14181. * @param force defines if states must be applied even if cache is up to date
  14182. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14183. */
  14184. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14185. if (zOffset === void 0) { zOffset = 0; }
  14186. if (reverseSide === void 0) { reverseSide = false; }
  14187. // Culling
  14188. if (this._depthCullingState.cull !== culling || force) {
  14189. this._depthCullingState.cull = culling;
  14190. }
  14191. // Cull face
  14192. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14193. if (this._depthCullingState.cullFace !== cullFace || force) {
  14194. this._depthCullingState.cullFace = cullFace;
  14195. }
  14196. // Z offset
  14197. this.setZOffset(zOffset);
  14198. // Front face
  14199. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14200. if (this._depthCullingState.frontFace !== frontFace || force) {
  14201. this._depthCullingState.frontFace = frontFace;
  14202. }
  14203. };
  14204. /**
  14205. * Set the z offset to apply to current rendering
  14206. * @param value defines the offset to apply
  14207. */
  14208. Engine.prototype.setZOffset = function (value) {
  14209. this._depthCullingState.zOffset = value;
  14210. };
  14211. /**
  14212. * Gets the current value of the zOffset
  14213. * @returns the current zOffset state
  14214. */
  14215. Engine.prototype.getZOffset = function () {
  14216. return this._depthCullingState.zOffset;
  14217. };
  14218. /**
  14219. * Enable or disable depth buffering
  14220. * @param enable defines the state to set
  14221. */
  14222. Engine.prototype.setDepthBuffer = function (enable) {
  14223. this._depthCullingState.depthTest = enable;
  14224. };
  14225. /**
  14226. * Gets a boolean indicating if depth writing is enabled
  14227. * @returns the current depth writing state
  14228. */
  14229. Engine.prototype.getDepthWrite = function () {
  14230. return this._depthCullingState.depthMask;
  14231. };
  14232. /**
  14233. * Enable or disable depth writing
  14234. * @param enable defines the state to set
  14235. */
  14236. Engine.prototype.setDepthWrite = function (enable) {
  14237. this._depthCullingState.depthMask = enable;
  14238. };
  14239. /**
  14240. * Enable or disable color writing
  14241. * @param enable defines the state to set
  14242. */
  14243. Engine.prototype.setColorWrite = function (enable) {
  14244. this._gl.colorMask(enable, enable, enable, enable);
  14245. this._colorWrite = enable;
  14246. };
  14247. /**
  14248. * Gets a boolean indicating if color writing is enabled
  14249. * @returns the current color writing state
  14250. */
  14251. Engine.prototype.getColorWrite = function () {
  14252. return this._colorWrite;
  14253. };
  14254. /**
  14255. * Sets alpha constants used by some alpha blending modes
  14256. * @param r defines the red component
  14257. * @param g defines the green component
  14258. * @param b defines the blue component
  14259. * @param a defines the alpha component
  14260. */
  14261. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14262. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14263. };
  14264. /**
  14265. * Sets the current alpha mode
  14266. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14267. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14268. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14269. */
  14270. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14271. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14272. if (this._alphaMode === mode) {
  14273. return;
  14274. }
  14275. switch (mode) {
  14276. case Engine.ALPHA_DISABLE:
  14277. this._alphaState.alphaBlend = false;
  14278. break;
  14279. case Engine.ALPHA_PREMULTIPLIED:
  14280. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14281. this._alphaState.alphaBlend = true;
  14282. break;
  14283. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14284. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14285. this._alphaState.alphaBlend = true;
  14286. break;
  14287. case Engine.ALPHA_COMBINE:
  14288. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14289. this._alphaState.alphaBlend = true;
  14290. break;
  14291. case Engine.ALPHA_ONEONE:
  14292. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14293. this._alphaState.alphaBlend = true;
  14294. break;
  14295. case Engine.ALPHA_ADD:
  14296. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14297. this._alphaState.alphaBlend = true;
  14298. break;
  14299. case Engine.ALPHA_SUBTRACT:
  14300. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14301. this._alphaState.alphaBlend = true;
  14302. break;
  14303. case Engine.ALPHA_MULTIPLY:
  14304. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14305. this._alphaState.alphaBlend = true;
  14306. break;
  14307. case Engine.ALPHA_MAXIMIZED:
  14308. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14309. this._alphaState.alphaBlend = true;
  14310. break;
  14311. case Engine.ALPHA_INTERPOLATE:
  14312. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14313. this._alphaState.alphaBlend = true;
  14314. break;
  14315. case Engine.ALPHA_SCREENMODE:
  14316. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14317. this._alphaState.alphaBlend = true;
  14318. break;
  14319. }
  14320. if (!noDepthWriteChange) {
  14321. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14322. }
  14323. this._alphaMode = mode;
  14324. };
  14325. /**
  14326. * Gets the current alpha mode
  14327. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14328. * @returns the current alpha mode
  14329. */
  14330. Engine.prototype.getAlphaMode = function () {
  14331. return this._alphaMode;
  14332. };
  14333. // Textures
  14334. /**
  14335. * Clears the list of texture accessible through engine.
  14336. * This can help preventing texture load conflict due to name collision.
  14337. */
  14338. Engine.prototype.clearInternalTexturesCache = function () {
  14339. this._internalTexturesCache = [];
  14340. };
  14341. /**
  14342. * Force the entire cache to be cleared
  14343. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14344. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14345. */
  14346. Engine.prototype.wipeCaches = function (bruteForce) {
  14347. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14348. return;
  14349. }
  14350. this._currentEffect = null;
  14351. this._viewportCached.x = 0;
  14352. this._viewportCached.y = 0;
  14353. this._viewportCached.z = 0;
  14354. this._viewportCached.w = 0;
  14355. if (bruteForce) {
  14356. this.resetTextureCache();
  14357. this._currentProgram = null;
  14358. this._stencilState.reset();
  14359. this._depthCullingState.reset();
  14360. this.setDepthFunctionToLessOrEqual();
  14361. this._alphaState.reset();
  14362. this._unpackFlipYCached = null;
  14363. }
  14364. this._resetVertexBufferBinding();
  14365. this._cachedIndexBuffer = null;
  14366. this._cachedEffectForVertexBuffers = null;
  14367. this._unbindVertexArrayObject();
  14368. this.bindIndexBuffer(null);
  14369. };
  14370. /**
  14371. * Set the compressed texture format to use, based on the formats you have, and the formats
  14372. * supported by the hardware / browser.
  14373. *
  14374. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14375. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14376. * to API arguments needed to compressed textures. This puts the burden on the container
  14377. * generator to house the arcane code for determining these for current & future formats.
  14378. *
  14379. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14380. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14381. *
  14382. * Note: The result of this call is not taken into account when a texture is base64.
  14383. *
  14384. * @param formatsAvailable defines the list of those format families you have created
  14385. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14386. *
  14387. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14388. * @returns The extension selected.
  14389. */
  14390. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14391. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14392. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14393. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14394. return this._textureFormatInUse = this._texturesSupported[i];
  14395. }
  14396. }
  14397. }
  14398. // actively set format to nothing, to allow this to be called more than once
  14399. // and possibly fail the 2nd time
  14400. this._textureFormatInUse = null;
  14401. return null;
  14402. };
  14403. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14404. var gl = this._gl;
  14405. var magFilter = gl.NEAREST;
  14406. var minFilter = gl.NEAREST;
  14407. switch (samplingMode) {
  14408. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14409. magFilter = gl.LINEAR;
  14410. if (generateMipMaps) {
  14411. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14412. }
  14413. else {
  14414. minFilter = gl.LINEAR;
  14415. }
  14416. break;
  14417. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14418. magFilter = gl.LINEAR;
  14419. if (generateMipMaps) {
  14420. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14421. }
  14422. else {
  14423. minFilter = gl.LINEAR;
  14424. }
  14425. break;
  14426. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14427. magFilter = gl.NEAREST;
  14428. if (generateMipMaps) {
  14429. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14430. }
  14431. else {
  14432. minFilter = gl.NEAREST;
  14433. }
  14434. break;
  14435. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14436. magFilter = gl.NEAREST;
  14437. if (generateMipMaps) {
  14438. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14439. }
  14440. else {
  14441. minFilter = gl.NEAREST;
  14442. }
  14443. break;
  14444. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14445. magFilter = gl.NEAREST;
  14446. if (generateMipMaps) {
  14447. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14448. }
  14449. else {
  14450. minFilter = gl.LINEAR;
  14451. }
  14452. break;
  14453. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14454. magFilter = gl.NEAREST;
  14455. if (generateMipMaps) {
  14456. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14457. }
  14458. else {
  14459. minFilter = gl.LINEAR;
  14460. }
  14461. break;
  14462. case Engine.TEXTURE_NEAREST_LINEAR:
  14463. magFilter = gl.NEAREST;
  14464. minFilter = gl.LINEAR;
  14465. break;
  14466. case Engine.TEXTURE_NEAREST_NEAREST:
  14467. magFilter = gl.NEAREST;
  14468. minFilter = gl.NEAREST;
  14469. break;
  14470. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14471. magFilter = gl.LINEAR;
  14472. if (generateMipMaps) {
  14473. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14474. }
  14475. else {
  14476. minFilter = gl.NEAREST;
  14477. }
  14478. break;
  14479. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14480. magFilter = gl.LINEAR;
  14481. if (generateMipMaps) {
  14482. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14483. }
  14484. else {
  14485. minFilter = gl.NEAREST;
  14486. }
  14487. break;
  14488. case Engine.TEXTURE_LINEAR_LINEAR:
  14489. magFilter = gl.LINEAR;
  14490. minFilter = gl.LINEAR;
  14491. break;
  14492. case Engine.TEXTURE_LINEAR_NEAREST:
  14493. magFilter = gl.LINEAR;
  14494. minFilter = gl.NEAREST;
  14495. break;
  14496. }
  14497. return {
  14498. min: minFilter,
  14499. mag: magFilter
  14500. };
  14501. };
  14502. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14503. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14504. var img;
  14505. var onload = function () {
  14506. loadedImages[index] = img;
  14507. loadedImages._internalCount++;
  14508. if (scene) {
  14509. scene._removePendingData(img);
  14510. }
  14511. if (loadedImages._internalCount === 6) {
  14512. onfinish(loadedImages);
  14513. }
  14514. };
  14515. var onerror = function (message, exception) {
  14516. if (scene) {
  14517. scene._removePendingData(img);
  14518. }
  14519. if (onErrorCallBack) {
  14520. onErrorCallBack(message, exception);
  14521. }
  14522. };
  14523. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14524. if (scene) {
  14525. scene._addPendingData(img);
  14526. }
  14527. };
  14528. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14529. if (onError === void 0) { onError = null; }
  14530. var loadedImages = [];
  14531. loadedImages._internalCount = 0;
  14532. for (var index = 0; index < 6; index++) {
  14533. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14534. }
  14535. };
  14536. ;
  14537. /** @hidden */
  14538. Engine.prototype._createTexture = function () {
  14539. var texture = this._gl.createTexture();
  14540. if (!texture) {
  14541. throw new Error("Unable to create texture");
  14542. }
  14543. return texture;
  14544. };
  14545. /**
  14546. * Usually called from BABYLON.Texture.ts.
  14547. * Passed information to create a WebGLTexture
  14548. * @param urlArg defines a value which contains one of the following:
  14549. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14550. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14551. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14552. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14553. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14554. * @param scene needed for loading to the correct scene
  14555. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14556. * @param onLoad optional callback to be called upon successful completion
  14557. * @param onError optional callback to be called upon failure
  14558. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14559. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14560. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14561. * @param forcedExtension defines the extension to use to pick the right loader
  14562. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14563. */
  14564. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14565. var _this = this;
  14566. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14567. if (onLoad === void 0) { onLoad = null; }
  14568. if (onError === void 0) { onError = null; }
  14569. if (buffer === void 0) { buffer = null; }
  14570. if (fallback === void 0) { fallback = null; }
  14571. if (format === void 0) { format = null; }
  14572. if (forcedExtension === void 0) { forcedExtension = null; }
  14573. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14574. var fromData = url.substr(0, 5) === "data:";
  14575. var fromBlob = url.substr(0, 5) === "blob:";
  14576. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14577. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14578. // establish the file extension, if possible
  14579. var lastDot = url.lastIndexOf('.');
  14580. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14581. var loader = null;
  14582. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14583. var availableLoader = _a[_i];
  14584. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14585. loader = availableLoader;
  14586. break;
  14587. }
  14588. }
  14589. if (loader) {
  14590. url = loader.transformUrl(url, this._textureFormatInUse);
  14591. }
  14592. if (scene) {
  14593. scene._addPendingData(texture);
  14594. }
  14595. texture.url = url;
  14596. texture.generateMipMaps = !noMipmap;
  14597. texture.samplingMode = samplingMode;
  14598. texture.invertY = invertY;
  14599. if (!this._doNotHandleContextLost) {
  14600. // Keep a link to the buffer only if we plan to handle context lost
  14601. texture._buffer = buffer;
  14602. }
  14603. var onLoadObserver = null;
  14604. if (onLoad && !fallback) {
  14605. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14606. }
  14607. if (!fallback)
  14608. this._internalTexturesCache.push(texture);
  14609. var onInternalError = function (message, exception) {
  14610. if (scene) {
  14611. scene._removePendingData(texture);
  14612. }
  14613. var customFallback = false;
  14614. if (loader) {
  14615. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14616. if (fallbackUrl) {
  14617. // Add Back
  14618. customFallback = true;
  14619. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14620. }
  14621. }
  14622. if (!customFallback) {
  14623. if (onLoadObserver) {
  14624. texture.onLoadedObservable.remove(onLoadObserver);
  14625. }
  14626. if (BABYLON.Tools.UseFallbackTexture) {
  14627. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14628. }
  14629. }
  14630. if (onError) {
  14631. onError(message || "Unknown error", exception);
  14632. }
  14633. };
  14634. // processing for non-image formats
  14635. if (loader) {
  14636. var callback = function (data) {
  14637. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14638. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14639. done();
  14640. return false;
  14641. }, samplingMode);
  14642. });
  14643. };
  14644. if (!buffer) {
  14645. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14646. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14647. });
  14648. }
  14649. else {
  14650. callback(buffer);
  14651. }
  14652. }
  14653. else {
  14654. var onload = function (img) {
  14655. if (fromBlob && !_this._doNotHandleContextLost) {
  14656. // We need to store the image if we need to rebuild the texture
  14657. // in case of a webgl context lost
  14658. texture._buffer = img;
  14659. }
  14660. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14661. var gl = _this._gl;
  14662. var isPot = (img.width === potWidth && img.height === potHeight);
  14663. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14664. if (isPot) {
  14665. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14666. return false;
  14667. }
  14668. var maxTextureSize = _this._caps.maxTextureSize;
  14669. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14670. _this._prepareWorkingCanvas();
  14671. if (!_this._workingCanvas || !_this._workingContext) {
  14672. return false;
  14673. }
  14674. _this._workingCanvas.width = potWidth;
  14675. _this._workingCanvas.height = potHeight;
  14676. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14677. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14678. texture.width = potWidth;
  14679. texture.height = potHeight;
  14680. return false;
  14681. }
  14682. else {
  14683. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14684. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14685. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14686. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14687. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14688. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14691. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14692. _this._releaseTexture(source_1);
  14693. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14694. continuationCallback();
  14695. });
  14696. }
  14697. return true;
  14698. }, samplingMode);
  14699. };
  14700. if (!fromData || isBase64) {
  14701. if (buffer instanceof HTMLImageElement) {
  14702. onload(buffer);
  14703. }
  14704. else {
  14705. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14706. }
  14707. }
  14708. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14709. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14710. }
  14711. else {
  14712. onload(buffer);
  14713. }
  14714. }
  14715. return texture;
  14716. };
  14717. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14718. var _this = this;
  14719. var rtt = this.createRenderTargetTexture({
  14720. width: destination.width,
  14721. height: destination.height,
  14722. }, {
  14723. generateMipMaps: false,
  14724. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14725. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14726. generateDepthBuffer: false,
  14727. generateStencilBuffer: false
  14728. });
  14729. if (!this._rescalePostProcess) {
  14730. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14731. }
  14732. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14733. _this._rescalePostProcess.onApply = function (effect) {
  14734. effect._bindTexture("textureSampler", source);
  14735. };
  14736. var hostingScene = scene;
  14737. if (!hostingScene) {
  14738. hostingScene = _this.scenes[_this.scenes.length - 1];
  14739. }
  14740. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14741. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14742. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14743. _this.unBindFramebuffer(rtt);
  14744. _this._releaseTexture(rtt);
  14745. if (onComplete) {
  14746. onComplete();
  14747. }
  14748. });
  14749. };
  14750. /**
  14751. * Update a raw texture
  14752. * @param texture defines the texture to update
  14753. * @param data defines the data to store in the texture
  14754. * @param format defines the format of the data
  14755. * @param invertY defines if data must be stored with Y axis inverted
  14756. * @param compression defines the compression used (null by default)
  14757. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14758. */
  14759. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14760. if (compression === void 0) { compression = null; }
  14761. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14762. if (!texture) {
  14763. return;
  14764. }
  14765. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14766. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14767. // babylon's internalFormat but gl's texImage2D format
  14768. var internalFormat = this._getInternalFormat(format);
  14769. var textureType = this._getWebGLTextureType(type);
  14770. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14771. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14772. if (!this._doNotHandleContextLost) {
  14773. texture._bufferView = data;
  14774. texture.format = format;
  14775. texture.type = type;
  14776. texture.invertY = invertY;
  14777. texture._compression = compression;
  14778. }
  14779. if (texture.width % 4 !== 0) {
  14780. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14781. }
  14782. if (compression && data) {
  14783. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14784. }
  14785. else {
  14786. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14787. }
  14788. if (texture.generateMipMaps) {
  14789. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14790. }
  14791. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14792. // this.resetTextureCache();
  14793. texture.isReady = true;
  14794. };
  14795. /**
  14796. * Creates a raw texture
  14797. * @param data defines the data to store in the texture
  14798. * @param width defines the width of the texture
  14799. * @param height defines the height of the texture
  14800. * @param format defines the format of the data
  14801. * @param generateMipMaps defines if the engine should generate the mip levels
  14802. * @param invertY defines if data must be stored with Y axis inverted
  14803. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14804. * @param compression defines the compression used (null by default)
  14805. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14806. * @returns the raw texture inside an InternalTexture
  14807. */
  14808. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14809. if (compression === void 0) { compression = null; }
  14810. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14811. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14812. texture.baseWidth = width;
  14813. texture.baseHeight = height;
  14814. texture.width = width;
  14815. texture.height = height;
  14816. texture.format = format;
  14817. texture.generateMipMaps = generateMipMaps;
  14818. texture.samplingMode = samplingMode;
  14819. texture.invertY = invertY;
  14820. texture._compression = compression;
  14821. texture.type = type;
  14822. if (!this._doNotHandleContextLost) {
  14823. texture._bufferView = data;
  14824. }
  14825. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14826. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14827. // Filters
  14828. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14829. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14831. if (generateMipMaps) {
  14832. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14833. }
  14834. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14835. this._internalTexturesCache.push(texture);
  14836. return texture;
  14837. };
  14838. /** @hidden */
  14839. Engine.prototype._unpackFlipY = function (value) {
  14840. if (this._unpackFlipYCached !== value) {
  14841. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14842. if (this.enableUnpackFlipYCached) {
  14843. this._unpackFlipYCached = value;
  14844. }
  14845. }
  14846. };
  14847. /** @hidden */
  14848. Engine.prototype._getUnpackAlignement = function () {
  14849. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14850. };
  14851. /**
  14852. * Creates a dynamic texture
  14853. * @param width defines the width of the texture
  14854. * @param height defines the height of the texture
  14855. * @param generateMipMaps defines if the engine should generate the mip levels
  14856. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14857. * @returns the dynamic texture inside an InternalTexture
  14858. */
  14859. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14860. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14861. texture.baseWidth = width;
  14862. texture.baseHeight = height;
  14863. if (generateMipMaps) {
  14864. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14865. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14866. }
  14867. // this.resetTextureCache();
  14868. texture.width = width;
  14869. texture.height = height;
  14870. texture.isReady = false;
  14871. texture.generateMipMaps = generateMipMaps;
  14872. texture.samplingMode = samplingMode;
  14873. this.updateTextureSamplingMode(samplingMode, texture);
  14874. this._internalTexturesCache.push(texture);
  14875. return texture;
  14876. };
  14877. /**
  14878. * Update the sampling mode of a given texture
  14879. * @param samplingMode defines the required sampling mode
  14880. * @param texture defines the texture to update
  14881. */
  14882. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14883. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14884. if (texture.isCube) {
  14885. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14886. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14887. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14888. }
  14889. else if (texture.is3D) {
  14890. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14891. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14892. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14893. }
  14894. else {
  14895. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14896. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14897. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14898. }
  14899. texture.samplingMode = samplingMode;
  14900. };
  14901. /**
  14902. * Update the content of a dynamic texture
  14903. * @param texture defines the texture to update
  14904. * @param canvas defines the canvas containing the source
  14905. * @param invertY defines if data must be stored with Y axis inverted
  14906. * @param premulAlpha defines if alpha is stored as premultiplied
  14907. * @param format defines the format of the data
  14908. */
  14909. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14910. if (premulAlpha === void 0) { premulAlpha = false; }
  14911. if (!texture) {
  14912. return;
  14913. }
  14914. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14915. this._unpackFlipY(invertY);
  14916. if (premulAlpha) {
  14917. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14918. }
  14919. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14920. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14921. if (texture.generateMipMaps) {
  14922. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14923. }
  14924. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14925. if (premulAlpha) {
  14926. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14927. }
  14928. texture.isReady = true;
  14929. };
  14930. /**
  14931. * Update a video texture
  14932. * @param texture defines the texture to update
  14933. * @param video defines the video element to use
  14934. * @param invertY defines if data must be stored with Y axis inverted
  14935. */
  14936. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14937. if (!texture || texture._isDisabled) {
  14938. return;
  14939. }
  14940. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14941. this._unpackFlipY(!invertY); // Video are upside down by default
  14942. try {
  14943. // Testing video texture support
  14944. if (this._videoTextureSupported === undefined) {
  14945. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14946. if (this._gl.getError() !== 0) {
  14947. this._videoTextureSupported = false;
  14948. }
  14949. else {
  14950. this._videoTextureSupported = true;
  14951. }
  14952. }
  14953. // Copy video through the current working canvas if video texture is not supported
  14954. if (!this._videoTextureSupported) {
  14955. if (!texture._workingCanvas) {
  14956. texture._workingCanvas = document.createElement("canvas");
  14957. var context = texture._workingCanvas.getContext("2d");
  14958. if (!context) {
  14959. throw new Error("Unable to get 2d context");
  14960. }
  14961. texture._workingContext = context;
  14962. texture._workingCanvas.width = texture.width;
  14963. texture._workingCanvas.height = texture.height;
  14964. }
  14965. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14966. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14967. }
  14968. else {
  14969. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14970. }
  14971. if (texture.generateMipMaps) {
  14972. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14973. }
  14974. if (!wasPreviouslyBound) {
  14975. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14976. }
  14977. // this.resetTextureCache();
  14978. texture.isReady = true;
  14979. }
  14980. catch (ex) {
  14981. // Something unexpected
  14982. // Let's disable the texture
  14983. texture._isDisabled = true;
  14984. }
  14985. };
  14986. /**
  14987. * Updates a depth texture Comparison Mode and Function.
  14988. * If the comparison Function is equal to 0, the mode will be set to none.
  14989. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14990. * @param texture The texture to set the comparison function for
  14991. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14992. */
  14993. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14994. if (this.webGLVersion === 1) {
  14995. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14996. return;
  14997. }
  14998. var gl = this._gl;
  14999. if (texture.isCube) {
  15000. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15001. if (comparisonFunction === 0) {
  15002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15004. }
  15005. else {
  15006. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15007. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15008. }
  15009. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15010. }
  15011. else {
  15012. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15013. if (comparisonFunction === 0) {
  15014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15016. }
  15017. else {
  15018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15020. }
  15021. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15022. }
  15023. texture._comparisonFunction = comparisonFunction;
  15024. };
  15025. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15026. var width = size.width || size;
  15027. var height = size.height || size;
  15028. internalTexture.baseWidth = width;
  15029. internalTexture.baseHeight = height;
  15030. internalTexture.width = width;
  15031. internalTexture.height = height;
  15032. internalTexture.isReady = true;
  15033. internalTexture.samples = 1;
  15034. internalTexture.generateMipMaps = false;
  15035. internalTexture._generateDepthBuffer = true;
  15036. internalTexture._generateStencilBuffer = generateStencil;
  15037. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15038. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15039. internalTexture._comparisonFunction = comparisonFunction;
  15040. var gl = this._gl;
  15041. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15042. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15043. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15044. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15045. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15046. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15047. if (comparisonFunction === 0) {
  15048. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15049. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15050. }
  15051. else {
  15052. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15053. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15054. }
  15055. };
  15056. /**
  15057. * Creates a depth stencil texture.
  15058. * This is only available in WebGL 2 or with the depth texture extension available.
  15059. * @param size The size of face edge in the texture.
  15060. * @param options The options defining the texture.
  15061. * @returns The texture
  15062. */
  15063. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15064. if (options.isCube) {
  15065. var width = size.width || size;
  15066. return this._createDepthStencilCubeTexture(width, options);
  15067. }
  15068. else {
  15069. return this._createDepthStencilTexture(size, options);
  15070. }
  15071. };
  15072. /**
  15073. * Creates a depth stencil texture.
  15074. * This is only available in WebGL 2 or with the depth texture extension available.
  15075. * @param size The size of face edge in the texture.
  15076. * @param options The options defining the texture.
  15077. * @returns The texture
  15078. */
  15079. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15080. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15081. if (!this._caps.depthTextureExtension) {
  15082. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15083. return internalTexture;
  15084. }
  15085. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15086. var gl = this._gl;
  15087. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15088. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15089. if (this.webGLVersion > 1) {
  15090. if (internalOptions.generateStencil) {
  15091. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15092. }
  15093. else {
  15094. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15095. }
  15096. }
  15097. else {
  15098. if (internalOptions.generateStencil) {
  15099. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15100. }
  15101. else {
  15102. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15103. }
  15104. }
  15105. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15106. return internalTexture;
  15107. };
  15108. /**
  15109. * Creates a depth stencil cube texture.
  15110. * This is only available in WebGL 2.
  15111. * @param size The size of face edge in the cube texture.
  15112. * @param options The options defining the cube texture.
  15113. * @returns The cube texture
  15114. */
  15115. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15116. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15117. internalTexture.isCube = true;
  15118. if (this.webGLVersion === 1) {
  15119. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15120. return internalTexture;
  15121. }
  15122. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15123. var gl = this._gl;
  15124. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15125. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15126. // Create the depth/stencil buffer
  15127. for (var face = 0; face < 6; face++) {
  15128. if (internalOptions.generateStencil) {
  15129. 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);
  15130. }
  15131. else {
  15132. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15133. }
  15134. }
  15135. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15136. return internalTexture;
  15137. };
  15138. /**
  15139. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15140. * @param renderTarget The render target to set the frame buffer for
  15141. */
  15142. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15143. // Create the framebuffer
  15144. var internalTexture = renderTarget.getInternalTexture();
  15145. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15146. return;
  15147. }
  15148. var gl = this._gl;
  15149. var depthStencilTexture = renderTarget.depthStencilTexture;
  15150. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15151. if (depthStencilTexture.isCube) {
  15152. if (depthStencilTexture._generateStencilBuffer) {
  15153. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15154. }
  15155. else {
  15156. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15157. }
  15158. }
  15159. else {
  15160. if (depthStencilTexture._generateStencilBuffer) {
  15161. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15162. }
  15163. else {
  15164. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15165. }
  15166. }
  15167. this.bindUnboundFramebuffer(null);
  15168. };
  15169. /**
  15170. * Creates a new render target texture
  15171. * @param size defines the size of the texture
  15172. * @param options defines the options used to create the texture
  15173. * @returns a new render target texture stored in an InternalTexture
  15174. */
  15175. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15176. var fullOptions = new RenderTargetCreationOptions();
  15177. if (options !== undefined && typeof options === "object") {
  15178. fullOptions.generateMipMaps = options.generateMipMaps;
  15179. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15180. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15181. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15182. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15183. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15184. }
  15185. else {
  15186. fullOptions.generateMipMaps = options;
  15187. fullOptions.generateDepthBuffer = true;
  15188. fullOptions.generateStencilBuffer = false;
  15189. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15190. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15191. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15192. }
  15193. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15194. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15195. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15196. }
  15197. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15198. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15199. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15200. }
  15201. var gl = this._gl;
  15202. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15203. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15204. var width = size.width || size;
  15205. var height = size.height || size;
  15206. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15207. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15208. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15209. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15210. }
  15211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15215. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15216. // Create the framebuffer
  15217. var currentFrameBuffer = this._currentFramebuffer;
  15218. var framebuffer = gl.createFramebuffer();
  15219. this.bindUnboundFramebuffer(framebuffer);
  15220. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15221. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15222. if (fullOptions.generateMipMaps) {
  15223. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15224. }
  15225. // Unbind
  15226. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15227. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15228. this.bindUnboundFramebuffer(currentFrameBuffer);
  15229. texture._framebuffer = framebuffer;
  15230. texture.baseWidth = width;
  15231. texture.baseHeight = height;
  15232. texture.width = width;
  15233. texture.height = height;
  15234. texture.isReady = true;
  15235. texture.samples = 1;
  15236. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15237. texture.samplingMode = fullOptions.samplingMode;
  15238. texture.type = fullOptions.type;
  15239. texture.format = fullOptions.format;
  15240. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15241. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15242. // this.resetTextureCache();
  15243. this._internalTexturesCache.push(texture);
  15244. return texture;
  15245. };
  15246. /**
  15247. * Create a multi render target texture
  15248. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15249. * @param size defines the size of the texture
  15250. * @param options defines the creation options
  15251. * @returns the cube texture as an InternalTexture
  15252. */
  15253. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15254. var generateMipMaps = false;
  15255. var generateDepthBuffer = true;
  15256. var generateStencilBuffer = false;
  15257. var generateDepthTexture = false;
  15258. var textureCount = 1;
  15259. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15260. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15261. var types = new Array();
  15262. var samplingModes = new Array();
  15263. if (options !== undefined) {
  15264. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15265. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15266. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15267. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15268. textureCount = options.textureCount || 1;
  15269. if (options.types) {
  15270. types = options.types;
  15271. }
  15272. if (options.samplingModes) {
  15273. samplingModes = options.samplingModes;
  15274. }
  15275. }
  15276. var gl = this._gl;
  15277. // Create the framebuffer
  15278. var framebuffer = gl.createFramebuffer();
  15279. this.bindUnboundFramebuffer(framebuffer);
  15280. var width = size.width || size;
  15281. var height = size.height || size;
  15282. var textures = [];
  15283. var attachments = [];
  15284. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15285. for (var i = 0; i < textureCount; i++) {
  15286. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15287. var type = types[i] || defaultType;
  15288. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15289. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15290. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15291. }
  15292. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15293. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15294. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15295. }
  15296. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15297. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15298. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15299. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15300. }
  15301. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15302. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15303. textures.push(texture);
  15304. attachments.push(attachment);
  15305. gl.activeTexture(gl["TEXTURE" + i]);
  15306. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15307. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15308. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15309. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15310. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15311. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15312. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15313. if (generateMipMaps) {
  15314. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15315. }
  15316. // Unbind
  15317. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15318. texture._framebuffer = framebuffer;
  15319. texture._depthStencilBuffer = depthStencilBuffer;
  15320. texture.baseWidth = width;
  15321. texture.baseHeight = height;
  15322. texture.width = width;
  15323. texture.height = height;
  15324. texture.isReady = true;
  15325. texture.samples = 1;
  15326. texture.generateMipMaps = generateMipMaps;
  15327. texture.samplingMode = samplingMode;
  15328. texture.type = type;
  15329. texture._generateDepthBuffer = generateDepthBuffer;
  15330. texture._generateStencilBuffer = generateStencilBuffer;
  15331. texture._attachments = attachments;
  15332. this._internalTexturesCache.push(texture);
  15333. }
  15334. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15335. // Depth texture
  15336. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15337. gl.activeTexture(gl.TEXTURE0);
  15338. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15343. 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);
  15344. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15345. depthTexture._framebuffer = framebuffer;
  15346. depthTexture.baseWidth = width;
  15347. depthTexture.baseHeight = height;
  15348. depthTexture.width = width;
  15349. depthTexture.height = height;
  15350. depthTexture.isReady = true;
  15351. depthTexture.samples = 1;
  15352. depthTexture.generateMipMaps = generateMipMaps;
  15353. depthTexture.samplingMode = gl.NEAREST;
  15354. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15355. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15356. textures.push(depthTexture);
  15357. this._internalTexturesCache.push(depthTexture);
  15358. }
  15359. gl.drawBuffers(attachments);
  15360. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15361. this.bindUnboundFramebuffer(null);
  15362. this.resetTextureCache();
  15363. return textures;
  15364. };
  15365. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15366. if (samples === void 0) { samples = 1; }
  15367. var depthStencilBuffer = null;
  15368. var gl = this._gl;
  15369. // Create the depth/stencil buffer
  15370. if (generateStencilBuffer) {
  15371. depthStencilBuffer = gl.createRenderbuffer();
  15372. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15373. if (samples > 1) {
  15374. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15375. }
  15376. else {
  15377. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15378. }
  15379. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15380. }
  15381. else if (generateDepthBuffer) {
  15382. depthStencilBuffer = gl.createRenderbuffer();
  15383. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15384. if (samples > 1) {
  15385. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15386. }
  15387. else {
  15388. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15389. }
  15390. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15391. }
  15392. return depthStencilBuffer;
  15393. };
  15394. /**
  15395. * Updates the sample count of a render target texture
  15396. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15397. * @param texture defines the texture to update
  15398. * @param samples defines the sample count to set
  15399. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15400. */
  15401. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15402. if (this.webGLVersion < 2 || !texture) {
  15403. return 1;
  15404. }
  15405. if (texture.samples === samples) {
  15406. return samples;
  15407. }
  15408. var gl = this._gl;
  15409. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15410. // Dispose previous render buffers
  15411. if (texture._depthStencilBuffer) {
  15412. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15413. texture._depthStencilBuffer = null;
  15414. }
  15415. if (texture._MSAAFramebuffer) {
  15416. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15417. texture._MSAAFramebuffer = null;
  15418. }
  15419. if (texture._MSAARenderBuffer) {
  15420. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15421. texture._MSAARenderBuffer = null;
  15422. }
  15423. if (samples > 1) {
  15424. var framebuffer = gl.createFramebuffer();
  15425. if (!framebuffer) {
  15426. throw new Error("Unable to create multi sampled framebuffer");
  15427. }
  15428. texture._MSAAFramebuffer = framebuffer;
  15429. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15430. var colorRenderbuffer = gl.createRenderbuffer();
  15431. if (!colorRenderbuffer) {
  15432. throw new Error("Unable to create multi sampled framebuffer");
  15433. }
  15434. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15435. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15436. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15437. texture._MSAARenderBuffer = colorRenderbuffer;
  15438. }
  15439. else {
  15440. this.bindUnboundFramebuffer(texture._framebuffer);
  15441. }
  15442. texture.samples = samples;
  15443. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15444. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15445. this.bindUnboundFramebuffer(null);
  15446. return samples;
  15447. };
  15448. /**
  15449. * Update the sample count for a given multiple render target texture
  15450. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15451. * @param textures defines the textures to update
  15452. * @param samples defines the sample count to set
  15453. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15454. */
  15455. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15456. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15457. return 1;
  15458. }
  15459. if (textures[0].samples === samples) {
  15460. return samples;
  15461. }
  15462. var gl = this._gl;
  15463. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15464. // Dispose previous render buffers
  15465. if (textures[0]._depthStencilBuffer) {
  15466. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15467. textures[0]._depthStencilBuffer = null;
  15468. }
  15469. if (textures[0]._MSAAFramebuffer) {
  15470. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15471. textures[0]._MSAAFramebuffer = null;
  15472. }
  15473. for (var i = 0; i < textures.length; i++) {
  15474. if (textures[i]._MSAARenderBuffer) {
  15475. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15476. textures[i]._MSAARenderBuffer = null;
  15477. }
  15478. }
  15479. if (samples > 1) {
  15480. var framebuffer = gl.createFramebuffer();
  15481. if (!framebuffer) {
  15482. throw new Error("Unable to create multi sampled framebuffer");
  15483. }
  15484. this.bindUnboundFramebuffer(framebuffer);
  15485. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15486. var attachments = [];
  15487. for (var i = 0; i < textures.length; i++) {
  15488. var texture = textures[i];
  15489. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15490. var colorRenderbuffer = gl.createRenderbuffer();
  15491. if (!colorRenderbuffer) {
  15492. throw new Error("Unable to create multi sampled framebuffer");
  15493. }
  15494. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15495. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15496. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15497. texture._MSAAFramebuffer = framebuffer;
  15498. texture._MSAARenderBuffer = colorRenderbuffer;
  15499. texture.samples = samples;
  15500. texture._depthStencilBuffer = depthStencilBuffer;
  15501. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15502. attachments.push(attachment);
  15503. }
  15504. gl.drawBuffers(attachments);
  15505. }
  15506. else {
  15507. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15508. }
  15509. this.bindUnboundFramebuffer(null);
  15510. return samples;
  15511. };
  15512. /** @hidden */
  15513. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15514. if (faceIndex === void 0) { faceIndex = 0; }
  15515. if (lod === void 0) { lod = 0; }
  15516. var gl = this._gl;
  15517. var target = gl.TEXTURE_2D;
  15518. if (texture.isCube) {
  15519. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15520. }
  15521. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15522. };
  15523. /** @hidden */
  15524. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15525. if (faceIndex === void 0) { faceIndex = 0; }
  15526. if (lod === void 0) { lod = 0; }
  15527. var gl = this._gl;
  15528. var textureType = this._getWebGLTextureType(texture.type);
  15529. var format = this._getInternalFormat(texture.format);
  15530. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15531. this._unpackFlipY(texture.invertY);
  15532. var target = gl.TEXTURE_2D;
  15533. if (texture.isCube) {
  15534. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15535. }
  15536. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15537. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15538. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15539. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15540. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15541. };
  15542. /** @hidden */
  15543. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15544. if (faceIndex === void 0) { faceIndex = 0; }
  15545. if (lod === void 0) { lod = 0; }
  15546. var gl = this._gl;
  15547. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15548. this._bindTextureDirectly(bindTarget, texture, true);
  15549. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15550. this._bindTextureDirectly(bindTarget, null, true);
  15551. };
  15552. /** @hidden */
  15553. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15554. if (faceIndex === void 0) { faceIndex = 0; }
  15555. if (lod === void 0) { lod = 0; }
  15556. var gl = this._gl;
  15557. var textureType = this._getWebGLTextureType(texture.type);
  15558. var format = this._getInternalFormat(texture.format);
  15559. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15560. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15561. this._bindTextureDirectly(bindTarget, texture, true);
  15562. this._unpackFlipY(texture.invertY);
  15563. var target = gl.TEXTURE_2D;
  15564. if (texture.isCube) {
  15565. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15566. }
  15567. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15568. this._bindTextureDirectly(bindTarget, null, true);
  15569. };
  15570. /**
  15571. * Creates a new render target cube texture
  15572. * @param size defines the size of the texture
  15573. * @param options defines the options used to create the texture
  15574. * @returns a new render target cube texture stored in an InternalTexture
  15575. */
  15576. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15577. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15578. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15579. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15580. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15581. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15582. }
  15583. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15584. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15585. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15586. }
  15587. var gl = this._gl;
  15588. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15589. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15590. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15591. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15592. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15593. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15594. }
  15595. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15597. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15599. for (var face = 0; face < 6; face++) {
  15600. 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);
  15601. }
  15602. // Create the framebuffer
  15603. var framebuffer = gl.createFramebuffer();
  15604. this.bindUnboundFramebuffer(framebuffer);
  15605. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15606. // MipMaps
  15607. if (fullOptions.generateMipMaps) {
  15608. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15609. }
  15610. // Unbind
  15611. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15612. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15613. this.bindUnboundFramebuffer(null);
  15614. texture._framebuffer = framebuffer;
  15615. texture.width = size;
  15616. texture.height = size;
  15617. texture.isReady = true;
  15618. texture.isCube = true;
  15619. texture.samples = 1;
  15620. texture.generateMipMaps = fullOptions.generateMipMaps;
  15621. texture.samplingMode = fullOptions.samplingMode;
  15622. texture.type = fullOptions.type;
  15623. texture.format = fullOptions.format;
  15624. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15625. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15626. this._internalTexturesCache.push(texture);
  15627. return texture;
  15628. };
  15629. /**
  15630. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15631. * @param rootUrl defines the url where the file to load is located
  15632. * @param scene defines the current scene
  15633. * @param lodScale defines scale to apply to the mip map selection
  15634. * @param lodOffset defines offset to apply to the mip map selection
  15635. * @param onLoad defines an optional callback raised when the texture is loaded
  15636. * @param onError defines an optional callback raised if there is an issue to load the texture
  15637. * @param format defines the format of the data
  15638. * @param forcedExtension defines the extension to use to pick the right loader
  15639. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15640. * @returns the cube texture as an InternalTexture
  15641. */
  15642. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15643. var _this = this;
  15644. if (onLoad === void 0) { onLoad = null; }
  15645. if (onError === void 0) { onError = null; }
  15646. if (forcedExtension === void 0) { forcedExtension = null; }
  15647. if (createPolynomials === void 0) { createPolynomials = true; }
  15648. var callback = function (loadData) {
  15649. if (!loadData) {
  15650. if (onLoad) {
  15651. onLoad(null);
  15652. }
  15653. return;
  15654. }
  15655. var texture = loadData.texture;
  15656. if (!createPolynomials) {
  15657. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15658. }
  15659. else if (loadData.info.sphericalPolynomial) {
  15660. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15661. }
  15662. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15663. if (_this._caps.textureLOD) {
  15664. // Do not add extra process if texture lod is supported.
  15665. if (onLoad) {
  15666. onLoad(texture);
  15667. }
  15668. return;
  15669. }
  15670. var mipSlices = 3;
  15671. var gl = _this._gl;
  15672. var width = loadData.width;
  15673. if (!width) {
  15674. return;
  15675. }
  15676. var textures = [];
  15677. for (var i = 0; i < mipSlices; i++) {
  15678. //compute LOD from even spacing in smoothness (matching shader calculation)
  15679. var smoothness = i / (mipSlices - 1);
  15680. var roughness = 1 - smoothness;
  15681. var minLODIndex = lodOffset; // roughness = 0
  15682. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15683. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15684. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15685. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15686. glTextureFromLod.type = texture.type;
  15687. glTextureFromLod.format = texture.format;
  15688. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15689. glTextureFromLod.height = glTextureFromLod.width;
  15690. glTextureFromLod.isCube = true;
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15696. if (loadData.isDDS) {
  15697. var info = loadData.info;
  15698. var data = loadData.data;
  15699. _this._unpackFlipY(info.isCompressed);
  15700. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15701. }
  15702. else {
  15703. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15704. }
  15705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15706. // Wrap in a base texture for easy binding.
  15707. var lodTexture = new BABYLON.BaseTexture(scene);
  15708. lodTexture.isCube = true;
  15709. lodTexture._texture = glTextureFromLod;
  15710. glTextureFromLod.isReady = true;
  15711. textures.push(lodTexture);
  15712. }
  15713. texture._lodTextureHigh = textures[2];
  15714. texture._lodTextureMid = textures[1];
  15715. texture._lodTextureLow = textures[0];
  15716. if (onLoad) {
  15717. onLoad(texture);
  15718. }
  15719. };
  15720. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15721. };
  15722. /**
  15723. * Creates a cube texture
  15724. * @param rootUrl defines the url where the files to load is located
  15725. * @param scene defines the current scene
  15726. * @param files defines the list of files to load (1 per face)
  15727. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15728. * @param onLoad defines an optional callback raised when the texture is loaded
  15729. * @param onError defines an optional callback raised if there is an issue to load the texture
  15730. * @param format defines the format of the data
  15731. * @param forcedExtension defines the extension to use to pick the right loader
  15732. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15733. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15734. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15735. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15736. * @returns the cube texture as an InternalTexture
  15737. */
  15738. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15739. var _this = this;
  15740. if (onLoad === void 0) { onLoad = null; }
  15741. if (onError === void 0) { onError = null; }
  15742. if (forcedExtension === void 0) { forcedExtension = null; }
  15743. if (createPolynomials === void 0) { createPolynomials = false; }
  15744. if (lodScale === void 0) { lodScale = 0; }
  15745. if (lodOffset === void 0) { lodOffset = 0; }
  15746. if (fallback === void 0) { fallback = null; }
  15747. var gl = this._gl;
  15748. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15749. texture.isCube = true;
  15750. texture.url = rootUrl;
  15751. texture.generateMipMaps = !noMipmap;
  15752. texture._lodGenerationScale = lodScale;
  15753. texture._lodGenerationOffset = lodOffset;
  15754. if (!this._doNotHandleContextLost) {
  15755. texture._extension = forcedExtension;
  15756. texture._files = files;
  15757. }
  15758. var lastDot = rootUrl.lastIndexOf('.');
  15759. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15760. var loader = null;
  15761. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15762. var availableLoader = _a[_i];
  15763. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15764. loader = availableLoader;
  15765. break;
  15766. }
  15767. }
  15768. var onInternalError = function (request, exception) {
  15769. if (loader) {
  15770. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15771. if (fallbackUrl) {
  15772. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15773. }
  15774. }
  15775. if (onError && request) {
  15776. onError(request.status + " " + request.statusText, exception);
  15777. }
  15778. };
  15779. if (loader) {
  15780. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15781. var onloaddata = function (data) {
  15782. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15783. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15784. };
  15785. if (files && files.length === 6) {
  15786. if (loader.supportCascades) {
  15787. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15788. }
  15789. else if (onError) {
  15790. onError("Textures type does not support cascades.");
  15791. }
  15792. }
  15793. else {
  15794. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15795. }
  15796. }
  15797. else {
  15798. if (!files) {
  15799. throw new Error("Cannot load cubemap because files were not defined");
  15800. }
  15801. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15802. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15803. var height = width;
  15804. _this._prepareWorkingCanvas();
  15805. if (!_this._workingCanvas || !_this._workingContext) {
  15806. return;
  15807. }
  15808. _this._workingCanvas.width = width;
  15809. _this._workingCanvas.height = height;
  15810. var faces = [
  15811. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15812. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15813. ];
  15814. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15815. _this._unpackFlipY(false);
  15816. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15817. for (var index = 0; index < faces.length; index++) {
  15818. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15819. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15820. }
  15821. if (!noMipmap) {
  15822. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15823. }
  15824. _this._setCubeMapTextureParams(!noMipmap);
  15825. texture.width = width;
  15826. texture.height = height;
  15827. texture.isReady = true;
  15828. if (format) {
  15829. texture.format = format;
  15830. }
  15831. texture.onLoadedObservable.notifyObservers(texture);
  15832. texture.onLoadedObservable.clear();
  15833. if (onLoad) {
  15834. onLoad();
  15835. }
  15836. }, files, onError);
  15837. }
  15838. this._internalTexturesCache.push(texture);
  15839. return texture;
  15840. };
  15841. /**
  15842. * @hidden
  15843. */
  15844. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15845. var gl = this._gl;
  15846. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15847. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15850. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15851. // this.resetTextureCache();
  15852. };
  15853. /**
  15854. * Update a raw cube texture
  15855. * @param texture defines the texture to udpdate
  15856. * @param data defines the data to store
  15857. * @param format defines the data format
  15858. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15859. * @param invertY defines if data must be stored with Y axis inverted
  15860. * @param compression defines the compression used (null by default)
  15861. * @param level defines which level of the texture to update
  15862. */
  15863. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15864. if (compression === void 0) { compression = null; }
  15865. if (level === void 0) { level = 0; }
  15866. texture._bufferViewArray = data;
  15867. texture.format = format;
  15868. texture.type = type;
  15869. texture.invertY = invertY;
  15870. texture._compression = compression;
  15871. var gl = this._gl;
  15872. var textureType = this._getWebGLTextureType(type);
  15873. var internalFormat = this._getInternalFormat(format);
  15874. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15875. var needConversion = false;
  15876. if (internalFormat === gl.RGB) {
  15877. internalFormat = gl.RGBA;
  15878. needConversion = true;
  15879. }
  15880. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15881. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15882. if (texture.width % 4 !== 0) {
  15883. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15884. }
  15885. // Data are known to be in +X +Y +Z -X -Y -Z
  15886. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15887. var faceData = data[faceIndex];
  15888. if (compression) {
  15889. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15890. }
  15891. else {
  15892. if (needConversion) {
  15893. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15894. }
  15895. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15896. }
  15897. }
  15898. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15899. if (isPot && texture.generateMipMaps && level === 0) {
  15900. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15901. }
  15902. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15903. // this.resetTextureCache();
  15904. texture.isReady = true;
  15905. };
  15906. /**
  15907. * Creates a new raw cube texture
  15908. * @param data defines the array of data to use to create each face
  15909. * @param size defines the size of the textures
  15910. * @param format defines the format of the data
  15911. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15912. * @param generateMipMaps defines if the engine should generate the mip levels
  15913. * @param invertY defines if data must be stored with Y axis inverted
  15914. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15915. * @param compression defines the compression used (null by default)
  15916. * @returns the cube texture as an InternalTexture
  15917. */
  15918. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15919. if (compression === void 0) { compression = null; }
  15920. var gl = this._gl;
  15921. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15922. texture.isCube = true;
  15923. texture.format = format;
  15924. texture.type = type;
  15925. if (!this._doNotHandleContextLost) {
  15926. texture._bufferViewArray = data;
  15927. }
  15928. var textureType = this._getWebGLTextureType(type);
  15929. var internalFormat = this._getInternalFormat(format);
  15930. if (internalFormat === gl.RGB) {
  15931. internalFormat = gl.RGBA;
  15932. }
  15933. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15934. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15935. generateMipMaps = false;
  15936. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15937. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15938. }
  15939. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15940. generateMipMaps = false;
  15941. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15942. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15943. }
  15944. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15945. generateMipMaps = false;
  15946. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15947. }
  15948. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15949. generateMipMaps = false;
  15950. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15951. }
  15952. var width = size;
  15953. var height = width;
  15954. texture.width = width;
  15955. texture.height = height;
  15956. // Double check on POT to generate Mips.
  15957. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15958. if (!isPot) {
  15959. generateMipMaps = false;
  15960. }
  15961. // Upload data if needed. The texture won't be ready until then.
  15962. if (data) {
  15963. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15964. }
  15965. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15966. // Filters
  15967. if (data && generateMipMaps) {
  15968. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15969. }
  15970. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15971. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15972. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15975. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15976. texture.generateMipMaps = generateMipMaps;
  15977. return texture;
  15978. };
  15979. /**
  15980. * Creates a new raw cube texture from a specified url
  15981. * @param url defines the url where the data is located
  15982. * @param scene defines the current scene
  15983. * @param size defines the size of the textures
  15984. * @param format defines the format of the data
  15985. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15986. * @param noMipmap defines if the engine should avoid generating the mip levels
  15987. * @param callback defines a callback used to extract texture data from loaded data
  15988. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15989. * @param onLoad defines a callback called when texture is loaded
  15990. * @param onError defines a callback called if there is an error
  15991. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15992. * @param invertY defines if data must be stored with Y axis inverted
  15993. * @returns the cube texture as an InternalTexture
  15994. */
  15995. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15996. var _this = this;
  15997. if (onLoad === void 0) { onLoad = null; }
  15998. if (onError === void 0) { onError = null; }
  15999. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16000. if (invertY === void 0) { invertY = false; }
  16001. var gl = this._gl;
  16002. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16003. scene._addPendingData(texture);
  16004. texture.url = url;
  16005. this._internalTexturesCache.push(texture);
  16006. var onerror = function (request, exception) {
  16007. scene._removePendingData(texture);
  16008. if (onError && request) {
  16009. onError(request.status + " " + request.statusText, exception);
  16010. }
  16011. };
  16012. var internalCallback = function (data) {
  16013. var width = texture.width;
  16014. var faceDataArrays = callback(data);
  16015. if (!faceDataArrays) {
  16016. return;
  16017. }
  16018. if (mipmapGenerator) {
  16019. var textureType = _this._getWebGLTextureType(type);
  16020. var internalFormat = _this._getInternalFormat(format);
  16021. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16022. var needConversion = false;
  16023. if (internalFormat === gl.RGB) {
  16024. internalFormat = gl.RGBA;
  16025. needConversion = true;
  16026. }
  16027. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16028. _this._unpackFlipY(false);
  16029. var mipData = mipmapGenerator(faceDataArrays);
  16030. for (var level = 0; level < mipData.length; level++) {
  16031. var mipSize = width >> level;
  16032. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16033. var mipFaceData = mipData[level][faceIndex];
  16034. if (needConversion) {
  16035. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16036. }
  16037. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16038. }
  16039. }
  16040. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16041. }
  16042. else {
  16043. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16044. }
  16045. texture.isReady = true;
  16046. // this.resetTextureCache();
  16047. scene._removePendingData(texture);
  16048. if (onLoad) {
  16049. onLoad();
  16050. }
  16051. };
  16052. this._loadFile(url, function (data) {
  16053. internalCallback(data);
  16054. }, undefined, scene.database, true, onerror);
  16055. return texture;
  16056. };
  16057. ;
  16058. /**
  16059. * Update a raw 3D texture
  16060. * @param texture defines the texture to update
  16061. * @param data defines the data to store
  16062. * @param format defines the data format
  16063. * @param invertY defines if data must be stored with Y axis inverted
  16064. * @param compression defines the used compression (can be null)
  16065. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16066. */
  16067. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16068. if (compression === void 0) { compression = null; }
  16069. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16070. var internalType = this._getWebGLTextureType(textureType);
  16071. var internalFormat = this._getInternalFormat(format);
  16072. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16073. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16074. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16075. if (!this._doNotHandleContextLost) {
  16076. texture._bufferView = data;
  16077. texture.format = format;
  16078. texture.invertY = invertY;
  16079. texture._compression = compression;
  16080. }
  16081. if (texture.width % 4 !== 0) {
  16082. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16083. }
  16084. if (compression && data) {
  16085. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16086. }
  16087. else {
  16088. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16089. }
  16090. if (texture.generateMipMaps) {
  16091. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16092. }
  16093. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16094. // this.resetTextureCache();
  16095. texture.isReady = true;
  16096. };
  16097. /**
  16098. * Creates a new raw 3D texture
  16099. * @param data defines the data used to create the texture
  16100. * @param width defines the width of the texture
  16101. * @param height defines the height of the texture
  16102. * @param depth defines the depth of the texture
  16103. * @param format defines the format of the texture
  16104. * @param generateMipMaps defines if the engine must generate mip levels
  16105. * @param invertY defines if data must be stored with Y axis inverted
  16106. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16107. * @param compression defines the compressed used (can be null)
  16108. * @param textureType defines the compressed used (can be null)
  16109. * @returns a new raw 3D texture (stored in an InternalTexture)
  16110. */
  16111. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16112. if (compression === void 0) { compression = null; }
  16113. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16114. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16115. texture.baseWidth = width;
  16116. texture.baseHeight = height;
  16117. texture.baseDepth = depth;
  16118. texture.width = width;
  16119. texture.height = height;
  16120. texture.depth = depth;
  16121. texture.format = format;
  16122. texture.type = textureType;
  16123. texture.generateMipMaps = generateMipMaps;
  16124. texture.samplingMode = samplingMode;
  16125. texture.is3D = true;
  16126. if (!this._doNotHandleContextLost) {
  16127. texture._bufferView = data;
  16128. }
  16129. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16130. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16131. // Filters
  16132. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16133. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16134. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16135. if (generateMipMaps) {
  16136. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16137. }
  16138. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16139. this._internalTexturesCache.push(texture);
  16140. return texture;
  16141. };
  16142. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16143. var gl = this._gl;
  16144. if (!gl) {
  16145. return;
  16146. }
  16147. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16148. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16149. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16150. if (!noMipmap && !isCompressed) {
  16151. gl.generateMipmap(gl.TEXTURE_2D);
  16152. }
  16153. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16154. // this.resetTextureCache();
  16155. if (scene) {
  16156. scene._removePendingData(texture);
  16157. }
  16158. texture.onLoadedObservable.notifyObservers(texture);
  16159. texture.onLoadedObservable.clear();
  16160. };
  16161. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16162. var _this = this;
  16163. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16164. var maxTextureSize = this.getCaps().maxTextureSize;
  16165. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16166. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16167. var gl = this._gl;
  16168. if (!gl) {
  16169. return;
  16170. }
  16171. if (!texture._webGLTexture) {
  16172. // this.resetTextureCache();
  16173. if (scene) {
  16174. scene._removePendingData(texture);
  16175. }
  16176. return;
  16177. }
  16178. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16179. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16180. texture.baseWidth = width;
  16181. texture.baseHeight = height;
  16182. texture.width = potWidth;
  16183. texture.height = potHeight;
  16184. texture.isReady = true;
  16185. if (processFunction(potWidth, potHeight, function () {
  16186. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16187. })) {
  16188. // Returning as texture needs extra async steps
  16189. return;
  16190. }
  16191. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16192. };
  16193. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16194. // Create new RGBA data container.
  16195. var rgbaData;
  16196. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16197. rgbaData = new Float32Array(width * height * 4);
  16198. }
  16199. else {
  16200. rgbaData = new Uint32Array(width * height * 4);
  16201. }
  16202. // Convert each pixel.
  16203. for (var x = 0; x < width; x++) {
  16204. for (var y = 0; y < height; y++) {
  16205. var index = (y * width + x) * 3;
  16206. var newIndex = (y * width + x) * 4;
  16207. // Map Old Value to new value.
  16208. rgbaData[newIndex + 0] = rgbData[index + 0];
  16209. rgbaData[newIndex + 1] = rgbData[index + 1];
  16210. rgbaData[newIndex + 2] = rgbData[index + 2];
  16211. // Add fully opaque alpha channel.
  16212. rgbaData[newIndex + 3] = 1;
  16213. }
  16214. }
  16215. return rgbaData;
  16216. };
  16217. /** @hidden */
  16218. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16219. var gl = this._gl;
  16220. if (texture._framebuffer) {
  16221. gl.deleteFramebuffer(texture._framebuffer);
  16222. texture._framebuffer = null;
  16223. }
  16224. if (texture._depthStencilBuffer) {
  16225. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16226. texture._depthStencilBuffer = null;
  16227. }
  16228. if (texture._MSAAFramebuffer) {
  16229. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16230. texture._MSAAFramebuffer = null;
  16231. }
  16232. if (texture._MSAARenderBuffer) {
  16233. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16234. texture._MSAARenderBuffer = null;
  16235. }
  16236. };
  16237. /** @hidden */
  16238. Engine.prototype._releaseTexture = function (texture) {
  16239. var gl = this._gl;
  16240. this._releaseFramebufferObjects(texture);
  16241. gl.deleteTexture(texture._webGLTexture);
  16242. // Unbind channels
  16243. this.unbindAllTextures();
  16244. var index = this._internalTexturesCache.indexOf(texture);
  16245. if (index !== -1) {
  16246. this._internalTexturesCache.splice(index, 1);
  16247. }
  16248. // Integrated fixed lod samplers.
  16249. if (texture._lodTextureHigh) {
  16250. texture._lodTextureHigh.dispose();
  16251. }
  16252. if (texture._lodTextureMid) {
  16253. texture._lodTextureMid.dispose();
  16254. }
  16255. if (texture._lodTextureLow) {
  16256. texture._lodTextureLow.dispose();
  16257. }
  16258. // Set output texture of post process to null if the texture has been released/disposed
  16259. this.scenes.forEach(function (scene) {
  16260. scene.postProcesses.forEach(function (postProcess) {
  16261. if (postProcess._outputTexture == texture) {
  16262. postProcess._outputTexture = null;
  16263. }
  16264. });
  16265. scene.cameras.forEach(function (camera) {
  16266. camera._postProcesses.forEach(function (postProcess) {
  16267. if (postProcess) {
  16268. if (postProcess._outputTexture == texture) {
  16269. postProcess._outputTexture = null;
  16270. }
  16271. }
  16272. });
  16273. });
  16274. });
  16275. };
  16276. Engine.prototype.setProgram = function (program) {
  16277. if (this._currentProgram !== program) {
  16278. this._gl.useProgram(program);
  16279. this._currentProgram = program;
  16280. }
  16281. };
  16282. /**
  16283. * Binds an effect to the webGL context
  16284. * @param effect defines the effect to bind
  16285. */
  16286. Engine.prototype.bindSamplers = function (effect) {
  16287. this.setProgram(effect.getProgram());
  16288. var samplers = effect.getSamplers();
  16289. for (var index = 0; index < samplers.length; index++) {
  16290. var uniform = effect.getUniform(samplers[index]);
  16291. if (uniform) {
  16292. this._boundUniforms[index] = uniform;
  16293. }
  16294. }
  16295. this._currentEffect = null;
  16296. };
  16297. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16298. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16299. return;
  16300. }
  16301. // Remove
  16302. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16303. // Bind last to it
  16304. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16305. // Bind to dummy
  16306. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16307. };
  16308. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16309. if (!internalTexture) {
  16310. return -1;
  16311. }
  16312. internalTexture._initialSlot = channel;
  16313. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16314. if (channel !== internalTexture._designatedSlot) {
  16315. this._textureCollisions.addCount(1, false);
  16316. }
  16317. }
  16318. else {
  16319. if (channel !== internalTexture._designatedSlot) {
  16320. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16321. return internalTexture._designatedSlot;
  16322. }
  16323. else {
  16324. // No slot for this texture, let's pick a new one (if we find a free slot)
  16325. if (this._nextFreeTextureSlots.length) {
  16326. return this._nextFreeTextureSlots[0];
  16327. }
  16328. // We need to recycle the oldest bound texture, sorry.
  16329. this._textureCollisions.addCount(1, false);
  16330. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16331. }
  16332. }
  16333. }
  16334. return channel;
  16335. };
  16336. Engine.prototype._linkTrackers = function (previous, next) {
  16337. previous.next = next;
  16338. next.previous = previous;
  16339. };
  16340. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16341. var currentSlot = internalTexture._designatedSlot;
  16342. if (currentSlot === -1) {
  16343. return -1;
  16344. }
  16345. internalTexture._designatedSlot = -1;
  16346. if (this.disableTextureBindingOptimization) {
  16347. return -1;
  16348. }
  16349. // Remove from bound list
  16350. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16351. // Free the slot
  16352. this._boundTexturesCache[currentSlot] = null;
  16353. this._nextFreeTextureSlots.push(currentSlot);
  16354. return currentSlot;
  16355. };
  16356. Engine.prototype._activateCurrentTexture = function () {
  16357. if (this._currentTextureChannel !== this._activeChannel) {
  16358. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16359. this._currentTextureChannel = this._activeChannel;
  16360. }
  16361. };
  16362. /** @hidden */
  16363. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16364. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16365. if (force === void 0) { force = false; }
  16366. var wasPreviouslyBound = false;
  16367. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16368. this._activeChannel = texture._designatedSlot;
  16369. }
  16370. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16371. var isTextureForRendering = texture && texture._initialSlot > -1;
  16372. if (currentTextureBound !== texture || force) {
  16373. if (currentTextureBound) {
  16374. this._removeDesignatedSlot(currentTextureBound);
  16375. }
  16376. this._activateCurrentTexture();
  16377. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16378. this._boundTexturesCache[this._activeChannel] = texture;
  16379. if (texture) {
  16380. if (!this.disableTextureBindingOptimization) {
  16381. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16382. if (slotIndex > -1) {
  16383. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16384. }
  16385. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16386. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16387. }
  16388. texture._designatedSlot = this._activeChannel;
  16389. }
  16390. }
  16391. else if (forTextureDataUpdate) {
  16392. wasPreviouslyBound = true;
  16393. this._activateCurrentTexture();
  16394. }
  16395. if (isTextureForRendering && !forTextureDataUpdate) {
  16396. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16397. }
  16398. return wasPreviouslyBound;
  16399. };
  16400. /** @hidden */
  16401. Engine.prototype._bindTexture = function (channel, texture) {
  16402. if (channel < 0) {
  16403. return;
  16404. }
  16405. if (texture) {
  16406. channel = this._getCorrectTextureChannel(channel, texture);
  16407. }
  16408. this._activeChannel = channel;
  16409. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16410. };
  16411. /**
  16412. * Sets a texture to the webGL context from a postprocess
  16413. * @param channel defines the channel to use
  16414. * @param postProcess defines the source postprocess
  16415. */
  16416. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16417. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16418. };
  16419. /**
  16420. * Binds the output of the passed in post process to the texture channel specified
  16421. * @param channel The channel the texture should be bound to
  16422. * @param postProcess The post process which's output should be bound
  16423. */
  16424. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16425. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16426. };
  16427. /**
  16428. * Unbind all textures from the webGL context
  16429. */
  16430. Engine.prototype.unbindAllTextures = function () {
  16431. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16432. this._activeChannel = channel;
  16433. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16434. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16435. if (this.webGLVersion > 1) {
  16436. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16437. }
  16438. }
  16439. };
  16440. /**
  16441. * Sets a texture to the according uniform.
  16442. * @param channel The texture channel
  16443. * @param uniform The uniform to set
  16444. * @param texture The texture to apply
  16445. */
  16446. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16447. if (channel < 0) {
  16448. return;
  16449. }
  16450. if (uniform) {
  16451. this._boundUniforms[channel] = uniform;
  16452. }
  16453. this._setTexture(channel, texture);
  16454. };
  16455. /**
  16456. * Sets a depth stencil texture from a render target to the according uniform.
  16457. * @param channel The texture channel
  16458. * @param uniform The uniform to set
  16459. * @param texture The render target texture containing the depth stencil texture to apply
  16460. */
  16461. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16462. if (channel < 0) {
  16463. return;
  16464. }
  16465. if (uniform) {
  16466. this._boundUniforms[channel] = uniform;
  16467. }
  16468. if (!texture || !texture.depthStencilTexture) {
  16469. this._setTexture(channel, null);
  16470. }
  16471. else {
  16472. this._setTexture(channel, texture, false, true);
  16473. }
  16474. };
  16475. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16476. var uniform = this._boundUniforms[sourceSlot];
  16477. if (uniform._currentState === destination) {
  16478. return;
  16479. }
  16480. this._gl.uniform1i(uniform, destination);
  16481. uniform._currentState = destination;
  16482. };
  16483. Engine.prototype._getTextureWrapMode = function (mode) {
  16484. switch (mode) {
  16485. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16486. return this._gl.REPEAT;
  16487. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16488. return this._gl.CLAMP_TO_EDGE;
  16489. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16490. return this._gl.MIRRORED_REPEAT;
  16491. }
  16492. return this._gl.REPEAT;
  16493. };
  16494. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16495. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16496. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16497. // Not ready?
  16498. if (!texture) {
  16499. if (this._boundTexturesCache[channel] != null) {
  16500. this._activeChannel = channel;
  16501. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16502. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16503. if (this.webGLVersion > 1) {
  16504. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16505. }
  16506. }
  16507. return false;
  16508. }
  16509. // Video
  16510. if (texture.video) {
  16511. this._activeChannel = channel;
  16512. texture.update();
  16513. }
  16514. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16515. texture.delayLoad();
  16516. return false;
  16517. }
  16518. var internalTexture;
  16519. if (depthStencilTexture) {
  16520. internalTexture = texture.depthStencilTexture;
  16521. }
  16522. else if (texture.isReady()) {
  16523. internalTexture = texture.getInternalTexture();
  16524. }
  16525. else if (texture.isCube) {
  16526. internalTexture = this.emptyCubeTexture;
  16527. }
  16528. else if (texture.is3D) {
  16529. internalTexture = this.emptyTexture3D;
  16530. }
  16531. else {
  16532. internalTexture = this.emptyTexture;
  16533. }
  16534. if (!isPartOfTextureArray) {
  16535. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16536. }
  16537. var needToBind = true;
  16538. if (this._boundTexturesCache[channel] === internalTexture) {
  16539. this._moveBoundTextureOnTop(internalTexture);
  16540. if (!isPartOfTextureArray) {
  16541. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16542. }
  16543. needToBind = false;
  16544. }
  16545. this._activeChannel = channel;
  16546. if (internalTexture && internalTexture.is3D) {
  16547. if (needToBind) {
  16548. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16549. }
  16550. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16551. internalTexture._cachedWrapU = texture.wrapU;
  16552. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16553. }
  16554. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16555. internalTexture._cachedWrapV = texture.wrapV;
  16556. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16557. }
  16558. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16559. internalTexture._cachedWrapR = texture.wrapR;
  16560. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16561. }
  16562. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16563. }
  16564. else if (internalTexture && internalTexture.isCube) {
  16565. if (needToBind) {
  16566. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16567. }
  16568. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16569. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16570. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16571. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16572. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16573. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16574. }
  16575. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16576. }
  16577. else {
  16578. if (needToBind) {
  16579. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16580. }
  16581. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16582. internalTexture._cachedWrapU = texture.wrapU;
  16583. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16584. }
  16585. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16586. internalTexture._cachedWrapV = texture.wrapV;
  16587. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16588. }
  16589. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16590. }
  16591. return true;
  16592. };
  16593. /**
  16594. * Sets an array of texture to the webGL context
  16595. * @param channel defines the channel where the texture array must be set
  16596. * @param uniform defines the associated uniform location
  16597. * @param textures defines the array of textures to bind
  16598. */
  16599. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16600. if (channel < 0 || !uniform) {
  16601. return;
  16602. }
  16603. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16604. this._textureUnits = new Int32Array(textures.length);
  16605. }
  16606. for (var i = 0; i < textures.length; i++) {
  16607. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16608. }
  16609. this._gl.uniform1iv(uniform, this._textureUnits);
  16610. for (var index = 0; index < textures.length; index++) {
  16611. this._setTexture(this._textureUnits[index], textures[index], true);
  16612. }
  16613. };
  16614. /** @hidden */
  16615. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16616. var internalTexture = texture.getInternalTexture();
  16617. if (!internalTexture) {
  16618. return;
  16619. }
  16620. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16621. var value = texture.anisotropicFilteringLevel;
  16622. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16623. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16624. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16625. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16626. }
  16627. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16628. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16629. internalTexture._cachedAnisotropicFilteringLevel = value;
  16630. }
  16631. };
  16632. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16633. this._bindTextureDirectly(target, texture, true, true);
  16634. this._gl.texParameterf(target, parameter, value);
  16635. };
  16636. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16637. if (texture) {
  16638. this._bindTextureDirectly(target, texture, true, true);
  16639. }
  16640. this._gl.texParameteri(target, parameter, value);
  16641. };
  16642. /**
  16643. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16644. * @param x defines the x coordinate of the rectangle where pixels must be read
  16645. * @param y defines the y coordinate of the rectangle where pixels must be read
  16646. * @param width defines the width of the rectangle where pixels must be read
  16647. * @param height defines the height of the rectangle where pixels must be read
  16648. * @returns a Uint8Array containing RGBA colors
  16649. */
  16650. Engine.prototype.readPixels = function (x, y, width, height) {
  16651. var data = new Uint8Array(height * width * 4);
  16652. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16653. return data;
  16654. };
  16655. /**
  16656. * Add an externaly attached data from its key.
  16657. * This method call will fail and return false, if such key already exists.
  16658. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16659. * @param key the unique key that identifies the data
  16660. * @param data the data object to associate to the key for this Engine instance
  16661. * @return true if no such key were already present and the data was added successfully, false otherwise
  16662. */
  16663. Engine.prototype.addExternalData = function (key, data) {
  16664. if (!this._externalData) {
  16665. this._externalData = new BABYLON.StringDictionary();
  16666. }
  16667. return this._externalData.add(key, data);
  16668. };
  16669. /**
  16670. * Get an externaly attached data from its key
  16671. * @param key the unique key that identifies the data
  16672. * @return the associated data, if present (can be null), or undefined if not present
  16673. */
  16674. Engine.prototype.getExternalData = function (key) {
  16675. if (!this._externalData) {
  16676. this._externalData = new BABYLON.StringDictionary();
  16677. }
  16678. return this._externalData.get(key);
  16679. };
  16680. /**
  16681. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16682. * @param key the unique key that identifies the data
  16683. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16684. * @return the associated data, can be null if the factory returned null.
  16685. */
  16686. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16687. if (!this._externalData) {
  16688. this._externalData = new BABYLON.StringDictionary();
  16689. }
  16690. return this._externalData.getOrAddWithFactory(key, factory);
  16691. };
  16692. /**
  16693. * Remove an externaly attached data from the Engine instance
  16694. * @param key the unique key that identifies the data
  16695. * @return true if the data was successfully removed, false if it doesn't exist
  16696. */
  16697. Engine.prototype.removeExternalData = function (key) {
  16698. if (!this._externalData) {
  16699. this._externalData = new BABYLON.StringDictionary();
  16700. }
  16701. return this._externalData.remove(key);
  16702. };
  16703. /**
  16704. * Unbind all vertex attributes from the webGL context
  16705. */
  16706. Engine.prototype.unbindAllAttributes = function () {
  16707. if (this._mustWipeVertexAttributes) {
  16708. this._mustWipeVertexAttributes = false;
  16709. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16710. this._gl.disableVertexAttribArray(i);
  16711. this._vertexAttribArraysEnabled[i] = false;
  16712. this._currentBufferPointers[i].active = false;
  16713. }
  16714. return;
  16715. }
  16716. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16717. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16718. continue;
  16719. }
  16720. this._gl.disableVertexAttribArray(i);
  16721. this._vertexAttribArraysEnabled[i] = false;
  16722. this._currentBufferPointers[i].active = false;
  16723. }
  16724. };
  16725. /**
  16726. * 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
  16727. */
  16728. Engine.prototype.releaseEffects = function () {
  16729. for (var name in this._compiledEffects) {
  16730. this._deleteProgram(this._compiledEffects[name]._program);
  16731. }
  16732. this._compiledEffects = {};
  16733. };
  16734. /**
  16735. * Dispose and release all associated resources
  16736. */
  16737. Engine.prototype.dispose = function () {
  16738. this.hideLoadingUI();
  16739. this.stopRenderLoop();
  16740. // Release postProcesses
  16741. while (this.postProcesses.length) {
  16742. this.postProcesses[0].dispose();
  16743. }
  16744. // Empty texture
  16745. if (this._emptyTexture) {
  16746. this._releaseTexture(this._emptyTexture);
  16747. this._emptyTexture = null;
  16748. }
  16749. if (this._emptyCubeTexture) {
  16750. this._releaseTexture(this._emptyCubeTexture);
  16751. this._emptyCubeTexture = null;
  16752. }
  16753. // Rescale PP
  16754. if (this._rescalePostProcess) {
  16755. this._rescalePostProcess.dispose();
  16756. }
  16757. // Release scenes
  16758. while (this.scenes.length) {
  16759. this.scenes[0].dispose();
  16760. }
  16761. // Release audio engine
  16762. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  16763. Engine.audioEngine.dispose();
  16764. }
  16765. // Release effects
  16766. this.releaseEffects();
  16767. // Unbind
  16768. this.unbindAllAttributes();
  16769. this._boundUniforms = [];
  16770. if (this._dummyFramebuffer) {
  16771. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16772. }
  16773. //WebVR
  16774. this.disableVR();
  16775. // Events
  16776. if (BABYLON.Tools.IsWindowObjectExist()) {
  16777. window.removeEventListener("blur", this._onBlur);
  16778. window.removeEventListener("focus", this._onFocus);
  16779. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16780. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16781. if (this._renderingCanvas) {
  16782. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16783. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16784. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16785. if (!this._doNotHandleContextLost) {
  16786. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16787. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16788. }
  16789. }
  16790. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16791. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16792. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16793. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16794. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16795. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16796. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16797. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16798. if (this._onVrDisplayConnect) {
  16799. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16800. if (this._onVrDisplayDisconnect) {
  16801. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16802. }
  16803. if (this._onVrDisplayPresentChange) {
  16804. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16805. }
  16806. this._onVrDisplayConnect = null;
  16807. this._onVrDisplayDisconnect = null;
  16808. }
  16809. }
  16810. // Remove from Instances
  16811. var index = Engine.Instances.indexOf(this);
  16812. if (index >= 0) {
  16813. Engine.Instances.splice(index, 1);
  16814. }
  16815. this._workingCanvas = null;
  16816. this._workingContext = null;
  16817. this._currentBufferPointers = [];
  16818. this._renderingCanvas = null;
  16819. this._currentProgram = null;
  16820. this._bindedRenderFunction = null;
  16821. this.onResizeObservable.clear();
  16822. this.onCanvasBlurObservable.clear();
  16823. this.onCanvasFocusObservable.clear();
  16824. this.onCanvasPointerOutObservable.clear();
  16825. this.onBeginFrameObservable.clear();
  16826. this.onEndFrameObservable.clear();
  16827. BABYLON.Effect.ResetCache();
  16828. // Abort active requests
  16829. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16830. var request = _a[_i];
  16831. request.abort();
  16832. }
  16833. };
  16834. // Loading screen
  16835. /**
  16836. * Display the loading screen
  16837. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16838. */
  16839. Engine.prototype.displayLoadingUI = function () {
  16840. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16841. return;
  16842. }
  16843. var loadingScreen = this.loadingScreen;
  16844. if (loadingScreen) {
  16845. loadingScreen.displayLoadingUI();
  16846. }
  16847. };
  16848. /**
  16849. * Hide the loading screen
  16850. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16851. */
  16852. Engine.prototype.hideLoadingUI = function () {
  16853. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16854. return;
  16855. }
  16856. var loadingScreen = this.loadingScreen;
  16857. if (loadingScreen) {
  16858. loadingScreen.hideLoadingUI();
  16859. }
  16860. };
  16861. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16862. /**
  16863. * Gets the current loading screen object
  16864. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16865. */
  16866. get: function () {
  16867. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16868. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16869. return this._loadingScreen;
  16870. },
  16871. /**
  16872. * Sets the current loading screen object
  16873. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16874. */
  16875. set: function (loadingScreen) {
  16876. this._loadingScreen = loadingScreen;
  16877. },
  16878. enumerable: true,
  16879. configurable: true
  16880. });
  16881. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16882. /**
  16883. * Sets the current loading screen text
  16884. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16885. */
  16886. set: function (text) {
  16887. this.loadingScreen.loadingUIText = text;
  16888. },
  16889. enumerable: true,
  16890. configurable: true
  16891. });
  16892. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16893. /**
  16894. * Sets the current loading screen background color
  16895. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16896. */
  16897. set: function (color) {
  16898. this.loadingScreen.loadingUIBackgroundColor = color;
  16899. },
  16900. enumerable: true,
  16901. configurable: true
  16902. });
  16903. /**
  16904. * Attach a new callback raised when context lost event is fired
  16905. * @param callback defines the callback to call
  16906. */
  16907. Engine.prototype.attachContextLostEvent = function (callback) {
  16908. if (this._renderingCanvas) {
  16909. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16910. }
  16911. };
  16912. /**
  16913. * Attach a new callback raised when context restored event is fired
  16914. * @param callback defines the callback to call
  16915. */
  16916. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16917. if (this._renderingCanvas) {
  16918. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16919. }
  16920. };
  16921. /**
  16922. * Gets the source code of the vertex shader associated with a specific webGL program
  16923. * @param program defines the program to use
  16924. * @returns a string containing the source code of the vertex shader associated with the program
  16925. */
  16926. Engine.prototype.getVertexShaderSource = function (program) {
  16927. var shaders = this._gl.getAttachedShaders(program);
  16928. if (!shaders) {
  16929. return null;
  16930. }
  16931. return this._gl.getShaderSource(shaders[0]);
  16932. };
  16933. /**
  16934. * Gets the source code of the fragment shader associated with a specific webGL program
  16935. * @param program defines the program to use
  16936. * @returns a string containing the source code of the fragment shader associated with the program
  16937. */
  16938. Engine.prototype.getFragmentShaderSource = function (program) {
  16939. var shaders = this._gl.getAttachedShaders(program);
  16940. if (!shaders) {
  16941. return null;
  16942. }
  16943. return this._gl.getShaderSource(shaders[1]);
  16944. };
  16945. /**
  16946. * Get the current error code of the webGL context
  16947. * @returns the error code
  16948. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16949. */
  16950. Engine.prototype.getError = function () {
  16951. return this._gl.getError();
  16952. };
  16953. // FPS
  16954. /**
  16955. * Gets the current framerate
  16956. * @returns a number representing the framerate
  16957. */
  16958. Engine.prototype.getFps = function () {
  16959. return this._fps;
  16960. };
  16961. /**
  16962. * Gets the time spent between current and previous frame
  16963. * @returns a number representing the delta time in ms
  16964. */
  16965. Engine.prototype.getDeltaTime = function () {
  16966. return this._deltaTime;
  16967. };
  16968. Engine.prototype._measureFps = function () {
  16969. this._performanceMonitor.sampleFrame();
  16970. this._fps = this._performanceMonitor.averageFPS;
  16971. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16972. };
  16973. /** @hidden */
  16974. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  16975. if (faceIndex === void 0) { faceIndex = -1; }
  16976. if (level === void 0) { level = 0; }
  16977. if (buffer === void 0) { buffer = null; }
  16978. var gl = this._gl;
  16979. if (!this._dummyFramebuffer) {
  16980. var dummy = gl.createFramebuffer();
  16981. if (!dummy) {
  16982. throw new Error("Unable to create dummy framebuffer");
  16983. }
  16984. this._dummyFramebuffer = dummy;
  16985. }
  16986. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16987. if (faceIndex > -1) {
  16988. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16989. }
  16990. else {
  16991. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16992. }
  16993. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16994. switch (readType) {
  16995. case gl.UNSIGNED_BYTE:
  16996. if (!buffer) {
  16997. buffer = new Uint8Array(4 * width * height);
  16998. }
  16999. readType = gl.UNSIGNED_BYTE;
  17000. break;
  17001. default:
  17002. if (!buffer) {
  17003. buffer = new Float32Array(4 * width * height);
  17004. }
  17005. readType = gl.FLOAT;
  17006. break;
  17007. }
  17008. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17009. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17010. return buffer;
  17011. };
  17012. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17013. if (this._webGLVersion > 1) {
  17014. return this._caps.colorBufferFloat;
  17015. }
  17016. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17017. };
  17018. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17019. if (this._webGLVersion > 1) {
  17020. return this._caps.colorBufferFloat;
  17021. }
  17022. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17023. };
  17024. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17025. Engine.prototype._canRenderToFramebuffer = function (type) {
  17026. var gl = this._gl;
  17027. //clear existing errors
  17028. while (gl.getError() !== gl.NO_ERROR) { }
  17029. var successful = true;
  17030. var texture = gl.createTexture();
  17031. gl.bindTexture(gl.TEXTURE_2D, texture);
  17032. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17033. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17034. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17035. var fb = gl.createFramebuffer();
  17036. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17037. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17038. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17039. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17040. successful = successful && (gl.getError() === gl.NO_ERROR);
  17041. //try render by clearing frame buffer's color buffer
  17042. if (successful) {
  17043. gl.clear(gl.COLOR_BUFFER_BIT);
  17044. successful = successful && (gl.getError() === gl.NO_ERROR);
  17045. }
  17046. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17047. if (successful) {
  17048. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17049. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17050. var readFormat = gl.RGBA;
  17051. var readType = gl.UNSIGNED_BYTE;
  17052. var buffer = new Uint8Array(4);
  17053. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17054. successful = successful && (gl.getError() === gl.NO_ERROR);
  17055. }
  17056. //clean up
  17057. gl.deleteTexture(texture);
  17058. gl.deleteFramebuffer(fb);
  17059. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17060. //clear accumulated errors
  17061. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17062. return successful;
  17063. };
  17064. /** @hidden */
  17065. Engine.prototype._getWebGLTextureType = function (type) {
  17066. if (this._webGLVersion === 1) {
  17067. switch (type) {
  17068. case Engine.TEXTURETYPE_FLOAT:
  17069. return this._gl.FLOAT;
  17070. case Engine.TEXTURETYPE_HALF_FLOAT:
  17071. return this._gl.HALF_FLOAT_OES;
  17072. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17073. return this._gl.UNSIGNED_BYTE;
  17074. }
  17075. return this._gl.UNSIGNED_BYTE;
  17076. }
  17077. switch (type) {
  17078. case Engine.TEXTURETYPE_BYTE:
  17079. return this._gl.BYTE;
  17080. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17081. return this._gl.UNSIGNED_BYTE;
  17082. case Engine.TEXTURETYPE_SHORT:
  17083. return this._gl.SHORT;
  17084. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17085. return this._gl.UNSIGNED_SHORT;
  17086. case Engine.TEXTURETYPE_INT:
  17087. return this._gl.INT;
  17088. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17089. return this._gl.UNSIGNED_INT;
  17090. case Engine.TEXTURETYPE_FLOAT:
  17091. return this._gl.FLOAT;
  17092. case Engine.TEXTURETYPE_HALF_FLOAT:
  17093. return this._gl.HALF_FLOAT;
  17094. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17095. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17096. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17097. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17098. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17099. return this._gl.UNSIGNED_SHORT_5_6_5;
  17100. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17101. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17102. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17103. return this._gl.UNSIGNED_INT_24_8;
  17104. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17105. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17106. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17107. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17108. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17109. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17110. }
  17111. return this._gl.UNSIGNED_BYTE;
  17112. };
  17113. ;
  17114. Engine.prototype._getInternalFormat = function (format) {
  17115. var internalFormat = this._gl.RGBA;
  17116. switch (format) {
  17117. case Engine.TEXTUREFORMAT_ALPHA:
  17118. internalFormat = this._gl.ALPHA;
  17119. break;
  17120. case Engine.TEXTUREFORMAT_LUMINANCE:
  17121. internalFormat = this._gl.LUMINANCE;
  17122. break;
  17123. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17124. internalFormat = this._gl.LUMINANCE_ALPHA;
  17125. break;
  17126. case Engine.TEXTUREFORMAT_RED:
  17127. internalFormat = this._gl.RED;
  17128. break;
  17129. case Engine.TEXTUREFORMAT_RG:
  17130. internalFormat = this._gl.RG;
  17131. break;
  17132. case Engine.TEXTUREFORMAT_RGB:
  17133. internalFormat = this._gl.RGB;
  17134. break;
  17135. case Engine.TEXTUREFORMAT_RGBA:
  17136. internalFormat = this._gl.RGBA;
  17137. break;
  17138. }
  17139. if (this._webGLVersion > 1) {
  17140. switch (format) {
  17141. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17142. internalFormat = this._gl.RED_INTEGER;
  17143. break;
  17144. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17145. internalFormat = this._gl.RG_INTEGER;
  17146. break;
  17147. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17148. internalFormat = this._gl.RGB_INTEGER;
  17149. break;
  17150. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17151. internalFormat = this._gl.RGBA_INTEGER;
  17152. break;
  17153. }
  17154. }
  17155. return internalFormat;
  17156. };
  17157. /** @hidden */
  17158. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17159. if (this._webGLVersion === 1) {
  17160. if (format !== undefined) {
  17161. switch (format) {
  17162. case Engine.TEXTUREFORMAT_ALPHA:
  17163. return this._gl.ALPHA;
  17164. case Engine.TEXTUREFORMAT_LUMINANCE:
  17165. return this._gl.LUMINANCE;
  17166. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17167. return this._gl.LUMINANCE_ALPHA;
  17168. }
  17169. }
  17170. return this._gl.RGBA;
  17171. }
  17172. switch (type) {
  17173. case Engine.TEXTURETYPE_BYTE:
  17174. switch (format) {
  17175. case Engine.TEXTUREFORMAT_RED:
  17176. return this._gl.R8_SNORM;
  17177. case Engine.TEXTUREFORMAT_RG:
  17178. return this._gl.RG8_SNORM;
  17179. case Engine.TEXTUREFORMAT_RGB:
  17180. return this._gl.RGB8_SNORM;
  17181. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17182. return this._gl.R8I;
  17183. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17184. return this._gl.RG8I;
  17185. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17186. return this._gl.RGB8I;
  17187. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17188. return this._gl.RGBA8I;
  17189. default:
  17190. return this._gl.RGBA8_SNORM;
  17191. }
  17192. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17193. switch (format) {
  17194. case Engine.TEXTUREFORMAT_RED:
  17195. return this._gl.R8;
  17196. case Engine.TEXTUREFORMAT_RG:
  17197. return this._gl.RG8;
  17198. case Engine.TEXTUREFORMAT_RGB:
  17199. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17200. case Engine.TEXTUREFORMAT_RGBA:
  17201. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17202. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17203. return this._gl.R8UI;
  17204. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17205. return this._gl.RG8UI;
  17206. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17207. return this._gl.RGB8UI;
  17208. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17209. return this._gl.RGBA8UI;
  17210. default:
  17211. return this._gl.RGBA8;
  17212. }
  17213. case Engine.TEXTURETYPE_SHORT:
  17214. switch (format) {
  17215. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17216. return this._gl.R16I;
  17217. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17218. return this._gl.RG16I;
  17219. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17220. return this._gl.RGB16I;
  17221. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17222. return this._gl.RGBA16I;
  17223. default:
  17224. return this._gl.RGBA16I;
  17225. }
  17226. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17227. switch (format) {
  17228. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17229. return this._gl.R16UI;
  17230. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17231. return this._gl.RG16UI;
  17232. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17233. return this._gl.RGB16UI;
  17234. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17235. return this._gl.RGBA16UI;
  17236. default:
  17237. return this._gl.RGBA16UI;
  17238. }
  17239. case Engine.TEXTURETYPE_INT:
  17240. switch (format) {
  17241. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17242. return this._gl.R32I;
  17243. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17244. return this._gl.RG32I;
  17245. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17246. return this._gl.RGB32I;
  17247. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17248. return this._gl.RGBA32I;
  17249. default:
  17250. return this._gl.RGBA32I;
  17251. }
  17252. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17253. switch (format) {
  17254. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17255. return this._gl.R32UI;
  17256. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17257. return this._gl.RG32UI;
  17258. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17259. return this._gl.RGB32UI;
  17260. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17261. return this._gl.RGBA32UI;
  17262. default:
  17263. return this._gl.RGBA32UI;
  17264. }
  17265. case Engine.TEXTURETYPE_FLOAT:
  17266. switch (format) {
  17267. case Engine.TEXTUREFORMAT_RED:
  17268. return this._gl.R32F; // By default. Other possibility is R16F.
  17269. case Engine.TEXTUREFORMAT_RG:
  17270. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17271. case Engine.TEXTUREFORMAT_RGB:
  17272. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17273. case Engine.TEXTUREFORMAT_RGBA:
  17274. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17275. default:
  17276. return this._gl.RGBA32F;
  17277. }
  17278. case Engine.TEXTURETYPE_HALF_FLOAT:
  17279. switch (format) {
  17280. case Engine.TEXTUREFORMAT_RED:
  17281. return this._gl.R16F;
  17282. case Engine.TEXTUREFORMAT_RG:
  17283. return this._gl.RG16F;
  17284. case Engine.TEXTUREFORMAT_RGB:
  17285. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17286. case Engine.TEXTUREFORMAT_RGBA:
  17287. return this._gl.RGBA16F;
  17288. default:
  17289. return this._gl.RGBA16F;
  17290. }
  17291. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17292. return this._gl.RGB565;
  17293. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17294. return this._gl.R11F_G11F_B10F;
  17295. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17296. return this._gl.RGB9_E5;
  17297. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17298. return this._gl.RGBA4;
  17299. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17300. return this._gl.RGB5_A1;
  17301. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17302. switch (format) {
  17303. case Engine.TEXTUREFORMAT_RGBA:
  17304. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17305. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17306. return this._gl.RGB10_A2UI;
  17307. default:
  17308. return this._gl.RGB10_A2;
  17309. }
  17310. }
  17311. return this._gl.RGBA8;
  17312. };
  17313. ;
  17314. /** @hidden */
  17315. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17316. if (type === Engine.TEXTURETYPE_FLOAT) {
  17317. return this._gl.RGBA32F;
  17318. }
  17319. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17320. return this._gl.RGBA16F;
  17321. }
  17322. return this._gl.RGBA8;
  17323. };
  17324. ;
  17325. /** @hidden */
  17326. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17327. var _this = this;
  17328. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17329. this._activeRequests.push(request);
  17330. request.onCompleteObservable.add(function (request) {
  17331. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17332. });
  17333. return request;
  17334. };
  17335. /** @hidden */
  17336. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17337. var _this = this;
  17338. return new Promise(function (resolve, reject) {
  17339. _this._loadFile(url, function (data) {
  17340. resolve(data);
  17341. }, undefined, database, useArrayBuffer, function (request, exception) {
  17342. reject(exception);
  17343. });
  17344. });
  17345. };
  17346. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17347. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17348. var onload = function (data) {
  17349. loadedFiles[index] = data;
  17350. loadedFiles._internalCount++;
  17351. if (loadedFiles._internalCount === 6) {
  17352. onfinish(loadedFiles);
  17353. }
  17354. };
  17355. var onerror = function (request, exception) {
  17356. if (onErrorCallBack && request) {
  17357. onErrorCallBack(request.status + " " + request.statusText, exception);
  17358. }
  17359. };
  17360. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17361. };
  17362. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17363. if (onError === void 0) { onError = null; }
  17364. var loadedFiles = [];
  17365. loadedFiles._internalCount = 0;
  17366. for (var index = 0; index < 6; index++) {
  17367. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17368. }
  17369. };
  17370. // Statics
  17371. /**
  17372. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17373. * @returns true if the engine can be created
  17374. * @ignorenaming
  17375. */
  17376. Engine.isSupported = function () {
  17377. try {
  17378. var tempcanvas = document.createElement("canvas");
  17379. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17380. return gl != null && !!window.WebGLRenderingContext;
  17381. }
  17382. catch (e) {
  17383. return false;
  17384. }
  17385. };
  17386. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17387. Engine.ExceptionList = [
  17388. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17389. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17390. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17391. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17392. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17393. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17394. ];
  17395. /** Gets the list of created engines */
  17396. Engine.Instances = new Array();
  17397. /**
  17398. * Hidden
  17399. */
  17400. Engine._TextureLoaders = [];
  17401. // Const statics
  17402. /** Defines that alpha blending is disabled */
  17403. Engine.ALPHA_DISABLE = 0;
  17404. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17405. Engine.ALPHA_ADD = 1;
  17406. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17407. Engine.ALPHA_COMBINE = 2;
  17408. /** Defines that alpha blending to DEST - SRC * DEST */
  17409. Engine.ALPHA_SUBTRACT = 3;
  17410. /** Defines that alpha blending to SRC * DEST */
  17411. Engine.ALPHA_MULTIPLY = 4;
  17412. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17413. Engine.ALPHA_MAXIMIZED = 5;
  17414. /** Defines that alpha blending to SRC + DEST */
  17415. Engine.ALPHA_ONEONE = 6;
  17416. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17417. Engine.ALPHA_PREMULTIPLIED = 7;
  17418. /**
  17419. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17420. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17421. */
  17422. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17423. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17424. Engine.ALPHA_INTERPOLATE = 9;
  17425. /**
  17426. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17427. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17428. */
  17429. Engine.ALPHA_SCREENMODE = 10;
  17430. /** Defines that the ressource is not delayed*/
  17431. Engine.DELAYLOADSTATE_NONE = 0;
  17432. /** Defines that the ressource was successfully delay loaded */
  17433. Engine.DELAYLOADSTATE_LOADED = 1;
  17434. /** Defines that the ressource is currently delay loading */
  17435. Engine.DELAYLOADSTATE_LOADING = 2;
  17436. /** Defines that the ressource is delayed and has not started loading */
  17437. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17438. // Depht or Stencil test Constants.
  17439. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17440. Engine.NEVER = 0x0200;
  17441. /** 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 */
  17442. Engine.ALWAYS = 0x0207;
  17443. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17444. Engine.LESS = 0x0201;
  17445. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17446. Engine.EQUAL = 0x0202;
  17447. /** 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 */
  17448. Engine.LEQUAL = 0x0203;
  17449. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17450. Engine.GREATER = 0x0204;
  17451. /** 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 */
  17452. Engine.GEQUAL = 0x0206;
  17453. /** 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 */
  17454. Engine.NOTEQUAL = 0x0205;
  17455. // Stencil Actions Constants.
  17456. /** Passed to stencilOperation to specify that stencil value must be kept */
  17457. Engine.KEEP = 0x1E00;
  17458. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17459. Engine.REPLACE = 0x1E01;
  17460. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17461. Engine.INCR = 0x1E02;
  17462. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17463. Engine.DECR = 0x1E03;
  17464. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17465. Engine.INVERT = 0x150A;
  17466. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17467. Engine.INCR_WRAP = 0x8507;
  17468. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17469. Engine.DECR_WRAP = 0x8508;
  17470. /** Texture is not repeating outside of 0..1 UVs */
  17471. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17472. /** Texture is repeating outside of 0..1 UVs */
  17473. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17474. /** Texture is repeating and mirrored */
  17475. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17476. /** ALPHA */
  17477. Engine.TEXTUREFORMAT_ALPHA = 0;
  17478. /** LUMINANCE */
  17479. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17480. /** LUMINANCE_ALPHA */
  17481. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17482. /** RGB */
  17483. Engine.TEXTUREFORMAT_RGB = 4;
  17484. /** RGBA */
  17485. Engine.TEXTUREFORMAT_RGBA = 5;
  17486. /** RED */
  17487. Engine.TEXTUREFORMAT_RED = 6;
  17488. /** RED (2nd reference) */
  17489. Engine.TEXTUREFORMAT_R = 6;
  17490. /** RG */
  17491. Engine.TEXTUREFORMAT_RG = 7;
  17492. /** RED_INTEGER */
  17493. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17494. /** RED_INTEGER (2nd reference) */
  17495. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17496. /** RG_INTEGER */
  17497. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17498. /** RGB_INTEGER */
  17499. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17500. /** RGBA_INTEGER */
  17501. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17502. /** UNSIGNED_BYTE */
  17503. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17504. /** UNSIGNED_BYTE (2nd reference) */
  17505. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17506. /** FLOAT */
  17507. Engine.TEXTURETYPE_FLOAT = 1;
  17508. /** HALF_FLOAT */
  17509. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17510. /** BYTE */
  17511. Engine.TEXTURETYPE_BYTE = 3;
  17512. /** SHORT */
  17513. Engine.TEXTURETYPE_SHORT = 4;
  17514. /** UNSIGNED_SHORT */
  17515. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17516. /** INT */
  17517. Engine.TEXTURETYPE_INT = 6;
  17518. /** UNSIGNED_INT */
  17519. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17520. /** UNSIGNED_SHORT_4_4_4_4 */
  17521. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17522. /** UNSIGNED_SHORT_5_5_5_1 */
  17523. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17524. /** UNSIGNED_SHORT_5_6_5 */
  17525. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17526. /** UNSIGNED_INT_2_10_10_10_REV */
  17527. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17528. /** UNSIGNED_INT_24_8 */
  17529. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17530. /** UNSIGNED_INT_10F_11F_11F_REV */
  17531. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17532. /** UNSIGNED_INT_5_9_9_9_REV */
  17533. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17534. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17535. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17536. /** nearest is mag = nearest and min = nearest and mip = linear */
  17537. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17538. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17539. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17540. /** Trilinear is mag = linear and min = linear and mip = linear */
  17541. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17542. /** nearest is mag = nearest and min = nearest and mip = linear */
  17543. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17544. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17545. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17546. /** Trilinear is mag = linear and min = linear and mip = linear */
  17547. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17548. /** mag = nearest and min = nearest and mip = nearest */
  17549. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17550. /** mag = nearest and min = linear and mip = nearest */
  17551. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17552. /** mag = nearest and min = linear and mip = linear */
  17553. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17554. /** mag = nearest and min = linear and mip = none */
  17555. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17556. /** mag = nearest and min = nearest and mip = none */
  17557. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17558. /** mag = linear and min = nearest and mip = nearest */
  17559. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17560. /** mag = linear and min = nearest and mip = linear */
  17561. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17562. /** mag = linear and min = linear and mip = none */
  17563. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17564. /** mag = linear and min = nearest and mip = none */
  17565. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17566. /** Explicit coordinates mode */
  17567. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17568. /** Spherical coordinates mode */
  17569. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17570. /** Planar coordinates mode */
  17571. Engine.TEXTURE_PLANAR_MODE = 2;
  17572. /** Cubic coordinates mode */
  17573. Engine.TEXTURE_CUBIC_MODE = 3;
  17574. /** Projection coordinates mode */
  17575. Engine.TEXTURE_PROJECTION_MODE = 4;
  17576. /** Skybox coordinates mode */
  17577. Engine.TEXTURE_SKYBOX_MODE = 5;
  17578. /** Inverse Cubic coordinates mode */
  17579. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17580. /** Equirectangular coordinates mode */
  17581. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17582. /** Equirectangular Fixed coordinates mode */
  17583. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17584. /** Equirectangular Fixed Mirrored coordinates mode */
  17585. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17586. // Texture rescaling mode
  17587. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17588. Engine.SCALEMODE_FLOOR = 1;
  17589. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17590. Engine.SCALEMODE_NEAREST = 2;
  17591. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17592. Engine.SCALEMODE_CEILING = 3;
  17593. // Updatable statics so stick with vars here
  17594. /**
  17595. * Gets or sets the epsilon value used by collision engine
  17596. */
  17597. Engine.CollisionsEpsilon = 0.001;
  17598. /**
  17599. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17600. */
  17601. Engine.CodeRepository = "src/";
  17602. /**
  17603. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17604. */
  17605. Engine.ShadersRepository = "src/Shaders/";
  17606. return Engine;
  17607. }());
  17608. BABYLON.Engine = Engine;
  17609. })(BABYLON || (BABYLON = {}));
  17610. //# sourceMappingURL=babylon.engine.js.map
  17611. var BABYLON;
  17612. (function (BABYLON) {
  17613. /**
  17614. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17615. */
  17616. var Node = /** @class */ (function () {
  17617. /**
  17618. * Creates a new Node
  17619. * @param {string} name - the name and id to be given to this node
  17620. * @param {BABYLON.Scene} the scene this node will be added to
  17621. */
  17622. function Node(name, scene) {
  17623. if (scene === void 0) { scene = null; }
  17624. /**
  17625. * Gets or sets a string used to store user defined state for the node
  17626. */
  17627. this.state = "";
  17628. /**
  17629. * Gets or sets an object used to store user defined information for the node
  17630. */
  17631. this.metadata = null;
  17632. /**
  17633. * Gets or sets a boolean used to define if the node must be serialized
  17634. */
  17635. this.doNotSerialize = false;
  17636. /** @hidden */
  17637. this._isDisposed = false;
  17638. /**
  17639. * Gets a list of Animations associated with the node
  17640. */
  17641. this.animations = new Array();
  17642. this._ranges = {};
  17643. this._isEnabled = true;
  17644. this._isParentEnabled = true;
  17645. this._isReady = true;
  17646. /** @hidden */
  17647. this._currentRenderId = -1;
  17648. this._parentRenderId = -1;
  17649. this._childRenderId = -1;
  17650. /** @hidden */
  17651. this._worldMatrix = BABYLON.Matrix.Identity();
  17652. /** @hidden */
  17653. this._worldMatrixDeterminant = 0;
  17654. this._animationPropertiesOverride = null;
  17655. /**
  17656. * An event triggered when the mesh is disposed
  17657. */
  17658. this.onDisposeObservable = new BABYLON.Observable();
  17659. // Behaviors
  17660. this._behaviors = new Array();
  17661. this.name = name;
  17662. this.id = name;
  17663. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17664. this.uniqueId = this._scene.getUniqueId();
  17665. this._initCache();
  17666. this._scene.rootNodes.push(this);
  17667. }
  17668. /**
  17669. * Add a new node constructor
  17670. * @param type defines the type name of the node to construct
  17671. * @param constructorFunc defines the constructor function
  17672. */
  17673. Node.AddNodeConstructor = function (type, constructorFunc) {
  17674. this._NodeConstructors[type] = constructorFunc;
  17675. };
  17676. /**
  17677. * Returns a node constructor based on type name
  17678. * @param type defines the type name
  17679. * @param name defines the new node name
  17680. * @param scene defines the hosting scene
  17681. * @param options defines optional options to transmit to constructors
  17682. * @returns the new constructor or null
  17683. */
  17684. Node.Construct = function (type, name, scene, options) {
  17685. var constructorFunc = this._NodeConstructors[type];
  17686. if (!constructorFunc) {
  17687. return null;
  17688. }
  17689. return constructorFunc(name, scene, options);
  17690. };
  17691. /**
  17692. * Gets a boolean indicating if the node has been disposed
  17693. * @returns true if the node was disposed
  17694. */
  17695. Node.prototype.isDisposed = function () {
  17696. return this._isDisposed;
  17697. };
  17698. Object.defineProperty(Node.prototype, "parent", {
  17699. get: function () {
  17700. return this._parentNode;
  17701. },
  17702. /**
  17703. * Gets or sets the parent of the node
  17704. */
  17705. set: function (parent) {
  17706. if (this._parentNode === parent) {
  17707. return;
  17708. }
  17709. var previousParentNode = this._parentNode;
  17710. // Remove self from list of children of parent
  17711. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17712. var index = this._parentNode._children.indexOf(this);
  17713. if (index !== -1) {
  17714. this._parentNode._children.splice(index, 1);
  17715. }
  17716. if (!parent) {
  17717. // Need to add this node to the rootNodes
  17718. this._scene.rootNodes.push(this);
  17719. }
  17720. }
  17721. // Store new parent
  17722. this._parentNode = parent;
  17723. // Add as child to new parent
  17724. if (this._parentNode) {
  17725. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17726. this._parentNode._children = new Array();
  17727. }
  17728. this._parentNode._children.push(this);
  17729. if (!previousParentNode) {
  17730. // Need to remove from rootNodes
  17731. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  17732. if (rootNodeIndex > -1) {
  17733. this._scene.rootNodes.splice(rootNodeIndex, 1);
  17734. }
  17735. }
  17736. }
  17737. // Enabled state
  17738. this._syncParentEnabledState();
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17744. /**
  17745. * Gets or sets the animation properties override
  17746. */
  17747. get: function () {
  17748. if (!this._animationPropertiesOverride) {
  17749. return this._scene.animationPropertiesOverride;
  17750. }
  17751. return this._animationPropertiesOverride;
  17752. },
  17753. set: function (value) {
  17754. this._animationPropertiesOverride = value;
  17755. },
  17756. enumerable: true,
  17757. configurable: true
  17758. });
  17759. /**
  17760. * Gets a string idenfifying the name of the class
  17761. * @returns "Node" string
  17762. */
  17763. Node.prototype.getClassName = function () {
  17764. return "Node";
  17765. };
  17766. Object.defineProperty(Node.prototype, "onDispose", {
  17767. /**
  17768. * Sets a callback that will be raised when the node will be disposed
  17769. */
  17770. set: function (callback) {
  17771. if (this._onDisposeObserver) {
  17772. this.onDisposeObservable.remove(this._onDisposeObserver);
  17773. }
  17774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. /**
  17780. * Gets the scene of the node
  17781. * @returns a {BABYLON.Scene}
  17782. */
  17783. Node.prototype.getScene = function () {
  17784. return this._scene;
  17785. };
  17786. /**
  17787. * Gets the engine of the node
  17788. * @returns a {BABYLON.Engine}
  17789. */
  17790. Node.prototype.getEngine = function () {
  17791. return this._scene.getEngine();
  17792. };
  17793. /**
  17794. * Attach a behavior to the node
  17795. * @see http://doc.babylonjs.com/features/behaviour
  17796. * @param behavior defines the behavior to attach
  17797. * @returns the current Node
  17798. */
  17799. Node.prototype.addBehavior = function (behavior) {
  17800. var _this = this;
  17801. var index = this._behaviors.indexOf(behavior);
  17802. if (index !== -1) {
  17803. return this;
  17804. }
  17805. behavior.init();
  17806. if (this._scene.isLoading) {
  17807. // We defer the attach when the scene will be loaded
  17808. this._scene.onDataLoadedObservable.addOnce(function () {
  17809. behavior.attach(_this);
  17810. });
  17811. }
  17812. else {
  17813. behavior.attach(this);
  17814. }
  17815. this._behaviors.push(behavior);
  17816. return this;
  17817. };
  17818. /**
  17819. * Remove an attached behavior
  17820. * @see http://doc.babylonjs.com/features/behaviour
  17821. * @param behavior defines the behavior to attach
  17822. * @returns the current Node
  17823. */
  17824. Node.prototype.removeBehavior = function (behavior) {
  17825. var index = this._behaviors.indexOf(behavior);
  17826. if (index === -1) {
  17827. return this;
  17828. }
  17829. this._behaviors[index].detach();
  17830. this._behaviors.splice(index, 1);
  17831. return this;
  17832. };
  17833. Object.defineProperty(Node.prototype, "behaviors", {
  17834. /**
  17835. * Gets the list of attached behaviors
  17836. * @see http://doc.babylonjs.com/features/behaviour
  17837. */
  17838. get: function () {
  17839. return this._behaviors;
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. /**
  17845. * Gets an attached behavior by name
  17846. * @param name defines the name of the behavior to look for
  17847. * @see http://doc.babylonjs.com/features/behaviour
  17848. * @returns null if behavior was not found else the requested behavior
  17849. */
  17850. Node.prototype.getBehaviorByName = function (name) {
  17851. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17852. var behavior = _a[_i];
  17853. if (behavior.name === name) {
  17854. return behavior;
  17855. }
  17856. }
  17857. return null;
  17858. };
  17859. /**
  17860. * Returns the latest update of the World matrix
  17861. * @returns a Matrix
  17862. */
  17863. Node.prototype.getWorldMatrix = function () {
  17864. if (this._currentRenderId !== this._scene.getRenderId()) {
  17865. this.computeWorldMatrix();
  17866. }
  17867. return this._worldMatrix;
  17868. };
  17869. /** @hidden */
  17870. Node.prototype._getWorldMatrixDeterminant = function () {
  17871. return this._worldMatrixDeterminant;
  17872. };
  17873. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  17874. /**
  17875. * Returns directly the latest state of the mesh World matrix.
  17876. * A Matrix is returned.
  17877. */
  17878. get: function () {
  17879. return this._worldMatrix;
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. // override it in derived class if you add new variables to the cache
  17885. // and call the parent class method
  17886. /** @hidden */
  17887. Node.prototype._initCache = function () {
  17888. this._cache = {};
  17889. this._cache.parent = undefined;
  17890. };
  17891. /** @hidden */
  17892. Node.prototype.updateCache = function (force) {
  17893. if (!force && this.isSynchronized())
  17894. return;
  17895. this._cache.parent = this.parent;
  17896. this._updateCache();
  17897. };
  17898. // override it in derived class if you add new variables to the cache
  17899. // and call the parent class method if !ignoreParentClass
  17900. /** @hidden */
  17901. Node.prototype._updateCache = function (ignoreParentClass) {
  17902. };
  17903. // override it in derived class if you add new variables to the cache
  17904. /** @hidden */
  17905. Node.prototype._isSynchronized = function () {
  17906. return true;
  17907. };
  17908. /** @hidden */
  17909. Node.prototype._markSyncedWithParent = function () {
  17910. if (this._parentNode) {
  17911. this._parentRenderId = this._parentNode._childRenderId;
  17912. }
  17913. };
  17914. /** @hidden */
  17915. Node.prototype.isSynchronizedWithParent = function () {
  17916. if (!this._parentNode) {
  17917. return true;
  17918. }
  17919. if (this._parentRenderId !== this._parentNode._childRenderId) {
  17920. return false;
  17921. }
  17922. return this._parentNode.isSynchronized();
  17923. };
  17924. /** @hidden */
  17925. Node.prototype.isSynchronized = function () {
  17926. if (this._cache.parent != this._parentNode) {
  17927. this._cache.parent = this._parentNode;
  17928. return false;
  17929. }
  17930. if (this._parentNode && !this.isSynchronizedWithParent()) {
  17931. return false;
  17932. }
  17933. return this._isSynchronized();
  17934. };
  17935. /**
  17936. * Is this node ready to be used/rendered
  17937. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17938. * @return true if the node is ready
  17939. */
  17940. Node.prototype.isReady = function (completeCheck) {
  17941. if (completeCheck === void 0) { completeCheck = false; }
  17942. return this._isReady;
  17943. };
  17944. /**
  17945. * Is this node enabled?
  17946. * 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
  17947. * @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
  17948. * @return whether this node (and its parent) is enabled
  17949. */
  17950. Node.prototype.isEnabled = function (checkAncestors) {
  17951. if (checkAncestors === void 0) { checkAncestors = true; }
  17952. if (checkAncestors === false) {
  17953. return this._isEnabled;
  17954. }
  17955. if (!this._isEnabled) {
  17956. return false;
  17957. }
  17958. return this._isParentEnabled;
  17959. };
  17960. /** @hidden */
  17961. Node.prototype._syncParentEnabledState = function () {
  17962. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  17963. if (this._children) {
  17964. this._children.forEach(function (c) {
  17965. c._syncParentEnabledState(); // Force children to update accordingly
  17966. });
  17967. }
  17968. };
  17969. /**
  17970. * Set the enabled state of this node
  17971. * @param value defines the new enabled state
  17972. */
  17973. Node.prototype.setEnabled = function (value) {
  17974. this._isEnabled = value;
  17975. this._syncParentEnabledState();
  17976. };
  17977. /**
  17978. * Is this node a descendant of the given node?
  17979. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17980. * @param ancestor defines the parent node to inspect
  17981. * @returns a boolean indicating if this node is a descendant of the given node
  17982. */
  17983. Node.prototype.isDescendantOf = function (ancestor) {
  17984. if (this.parent) {
  17985. if (this.parent === ancestor) {
  17986. return true;
  17987. }
  17988. return this.parent.isDescendantOf(ancestor);
  17989. }
  17990. return false;
  17991. };
  17992. /** @hidden */
  17993. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17994. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17995. if (!this._children) {
  17996. return;
  17997. }
  17998. for (var index = 0; index < this._children.length; index++) {
  17999. var item = this._children[index];
  18000. if (!predicate || predicate(item)) {
  18001. results.push(item);
  18002. }
  18003. if (!directDescendantsOnly) {
  18004. item._getDescendants(results, false, predicate);
  18005. }
  18006. }
  18007. };
  18008. /**
  18009. * Will return all nodes that have this node as ascendant
  18010. * @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
  18011. * @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
  18012. * @return all children nodes of all types
  18013. */
  18014. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18015. var results = new Array();
  18016. this._getDescendants(results, directDescendantsOnly, predicate);
  18017. return results;
  18018. };
  18019. /**
  18020. * Get all child-meshes of this node
  18021. * @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
  18022. * @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
  18023. * @returns an array of {BABYLON.AbstractMesh}
  18024. */
  18025. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18026. var results = [];
  18027. this._getDescendants(results, directDescendantsOnly, function (node) {
  18028. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18029. });
  18030. return results;
  18031. };
  18032. /**
  18033. * Get all child-transformNodes of this node
  18034. * @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
  18035. * @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
  18036. * @returns an array of {BABYLON.TransformNode}
  18037. */
  18038. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18039. var results = [];
  18040. this._getDescendants(results, directDescendantsOnly, function (node) {
  18041. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18042. });
  18043. return results;
  18044. };
  18045. /**
  18046. * Get all direct children of this node
  18047. * @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
  18048. * @returns an array of {BABYLON.Node}
  18049. */
  18050. Node.prototype.getChildren = function (predicate) {
  18051. if (!predicate) {
  18052. return this._children;
  18053. }
  18054. return this.getDescendants(true, predicate);
  18055. };
  18056. /** @hidden */
  18057. Node.prototype._setReady = function (state) {
  18058. if (state === this._isReady) {
  18059. return;
  18060. }
  18061. if (!state) {
  18062. this._isReady = false;
  18063. return;
  18064. }
  18065. if (this.onReady) {
  18066. this.onReady(this);
  18067. }
  18068. this._isReady = true;
  18069. };
  18070. /**
  18071. * Get an animation by name
  18072. * @param name defines the name of the animation to look for
  18073. * @returns null if not found else the requested animation
  18074. */
  18075. Node.prototype.getAnimationByName = function (name) {
  18076. for (var i = 0; i < this.animations.length; i++) {
  18077. var animation = this.animations[i];
  18078. if (animation.name === name) {
  18079. return animation;
  18080. }
  18081. }
  18082. return null;
  18083. };
  18084. /**
  18085. * Creates an animation range for this node
  18086. * @param name defines the name of the range
  18087. * @param from defines the starting key
  18088. * @param to defines the end key
  18089. */
  18090. Node.prototype.createAnimationRange = function (name, from, to) {
  18091. // check name not already in use
  18092. if (!this._ranges[name]) {
  18093. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18094. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18095. if (this.animations[i]) {
  18096. this.animations[i].createRange(name, from, to);
  18097. }
  18098. }
  18099. }
  18100. };
  18101. /**
  18102. * Delete a specific animation range
  18103. * @param name defines the name of the range to delete
  18104. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18105. */
  18106. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18107. if (deleteFrames === void 0) { deleteFrames = true; }
  18108. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18109. if (this.animations[i]) {
  18110. this.animations[i].deleteRange(name, deleteFrames);
  18111. }
  18112. }
  18113. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18114. };
  18115. /**
  18116. * Get an animation range by name
  18117. * @param name defines the name of the animation range to look for
  18118. * @returns null if not found else the requested animation range
  18119. */
  18120. Node.prototype.getAnimationRange = function (name) {
  18121. return this._ranges[name];
  18122. };
  18123. /**
  18124. * Will start the animation sequence
  18125. * @param name defines the range frames for animation sequence
  18126. * @param loop defines if the animation should loop (false by default)
  18127. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18128. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18129. * @returns the object created for this animation. If range does not exist, it will return null
  18130. */
  18131. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18132. var range = this.getAnimationRange(name);
  18133. if (!range) {
  18134. return null;
  18135. }
  18136. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18137. };
  18138. /**
  18139. * Serialize animation ranges into a JSON compatible object
  18140. * @returns serialization object
  18141. */
  18142. Node.prototype.serializeAnimationRanges = function () {
  18143. var serializationRanges = [];
  18144. for (var name in this._ranges) {
  18145. var localRange = this._ranges[name];
  18146. if (!localRange) {
  18147. continue;
  18148. }
  18149. var range = {};
  18150. range.name = name;
  18151. range.from = localRange.from;
  18152. range.to = localRange.to;
  18153. serializationRanges.push(range);
  18154. }
  18155. return serializationRanges;
  18156. };
  18157. /**
  18158. * Computes the world matrix of the node
  18159. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18160. * @returns the world matrix
  18161. */
  18162. Node.prototype.computeWorldMatrix = function (force) {
  18163. if (!this._worldMatrix) {
  18164. this._worldMatrix = BABYLON.Matrix.Identity();
  18165. }
  18166. return this._worldMatrix;
  18167. };
  18168. /**
  18169. * Releases resources associated with this node.
  18170. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18171. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18172. */
  18173. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18174. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18175. if (!doNotRecurse) {
  18176. var nodes = this.getDescendants(true);
  18177. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18178. var node = nodes_1[_i];
  18179. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18180. }
  18181. }
  18182. else {
  18183. var transformNodes = this.getChildTransformNodes(true);
  18184. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18185. var transformNode = transformNodes_1[_a];
  18186. transformNode.parent = null;
  18187. transformNode.computeWorldMatrix(true);
  18188. }
  18189. }
  18190. if (!this.parent) {
  18191. var rootNodeIndex = this._scene.rootNodes.indexOf(this);
  18192. if (rootNodeIndex > -1) {
  18193. this._scene.rootNodes.splice(rootNodeIndex, 1);
  18194. }
  18195. }
  18196. else {
  18197. this.parent = null;
  18198. }
  18199. // Callback
  18200. this.onDisposeObservable.notifyObservers(this);
  18201. this.onDisposeObservable.clear();
  18202. // Behaviors
  18203. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18204. var behavior = _c[_b];
  18205. behavior.detach();
  18206. }
  18207. this._behaviors = [];
  18208. this._isDisposed = true;
  18209. };
  18210. /**
  18211. * Parse animation range data from a serialization object and store them into a given node
  18212. * @param node defines where to store the animation ranges
  18213. * @param parsedNode defines the serialization object to read data from
  18214. * @param scene defines the hosting scene
  18215. */
  18216. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18217. if (parsedNode.ranges) {
  18218. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18219. var data = parsedNode.ranges[index];
  18220. node.createAnimationRange(data.name, data.from, data.to);
  18221. }
  18222. }
  18223. };
  18224. Node._NodeConstructors = {};
  18225. __decorate([
  18226. BABYLON.serialize()
  18227. ], Node.prototype, "name", void 0);
  18228. __decorate([
  18229. BABYLON.serialize()
  18230. ], Node.prototype, "id", void 0);
  18231. __decorate([
  18232. BABYLON.serialize()
  18233. ], Node.prototype, "uniqueId", void 0);
  18234. __decorate([
  18235. BABYLON.serialize()
  18236. ], Node.prototype, "state", void 0);
  18237. __decorate([
  18238. BABYLON.serialize()
  18239. ], Node.prototype, "metadata", void 0);
  18240. return Node;
  18241. }());
  18242. BABYLON.Node = Node;
  18243. })(BABYLON || (BABYLON = {}));
  18244. //# sourceMappingURL=babylon.node.js.map
  18245. var BABYLON;
  18246. (function (BABYLON) {
  18247. // This matrix is used as a value to reset the bounding box.
  18248. var _identityMatrix = BABYLON.Matrix.Identity();
  18249. var _tempRadiusVector = new BABYLON.Vector3(0, 0, 0);
  18250. var BoundingSphere = /** @class */ (function () {
  18251. /**
  18252. * Creates a new bounding sphere
  18253. * @param min defines the minimum vector (in local space)
  18254. * @param max defines the maximum vector (in local space)
  18255. */
  18256. function BoundingSphere(min, max) {
  18257. this.center = BABYLON.Vector3.Zero();
  18258. this.centerWorld = BABYLON.Vector3.Zero();
  18259. this.reConstruct(min, max);
  18260. }
  18261. /**
  18262. * Recreates the entire bounding sphere from scratch
  18263. * @param min defines the new minimum vector (in local space)
  18264. * @param max defines the new maximum vector (in local space)
  18265. */
  18266. BoundingSphere.prototype.reConstruct = function (min, max) {
  18267. this.minimum = min.clone();
  18268. this.maximum = max.clone();
  18269. var distance = BABYLON.Vector3.Distance(min, max);
  18270. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18271. this.radius = distance * 0.5;
  18272. this.centerWorld.set(0, 0, 0);
  18273. this._update(_identityMatrix);
  18274. };
  18275. /**
  18276. * Scale the current bounding sphere by applying a scale factor
  18277. * @param factor defines the scale factor to apply
  18278. * @returns the current bounding box
  18279. */
  18280. BoundingSphere.prototype.scale = function (factor) {
  18281. var newRadius = this.radius * factor;
  18282. _tempRadiusVector.set(newRadius, newRadius, newRadius);
  18283. var min = this.center.subtract(_tempRadiusVector);
  18284. var max = this.center.add(_tempRadiusVector);
  18285. this.reConstruct(min, max);
  18286. return this;
  18287. };
  18288. // Methods
  18289. /** @hidden */
  18290. BoundingSphere.prototype._update = function (world) {
  18291. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18292. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, _tempRadiusVector);
  18293. this.radiusWorld = Math.max(Math.abs(_tempRadiusVector.x), Math.abs(_tempRadiusVector.y), Math.abs(_tempRadiusVector.z)) * this.radius;
  18294. };
  18295. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18296. for (var i = 0; i < 6; i++) {
  18297. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18298. return false;
  18299. }
  18300. return true;
  18301. };
  18302. BoundingSphere.prototype.intersectsPoint = function (point) {
  18303. var x = this.centerWorld.x - point.x;
  18304. var y = this.centerWorld.y - point.y;
  18305. var z = this.centerWorld.z - point.z;
  18306. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18307. if (this.radiusWorld < distance)
  18308. return false;
  18309. return true;
  18310. };
  18311. // Statics
  18312. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18313. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18314. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18315. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18316. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18317. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18318. return false;
  18319. return true;
  18320. };
  18321. return BoundingSphere;
  18322. }());
  18323. BABYLON.BoundingSphere = BoundingSphere;
  18324. })(BABYLON || (BABYLON = {}));
  18325. //# sourceMappingURL=babylon.boundingSphere.js.map
  18326. var BABYLON;
  18327. (function (BABYLON) {
  18328. var BoundingBox = /** @class */ (function () {
  18329. /**
  18330. * Creates a new bounding box
  18331. * @param min defines the minimum vector (in local space)
  18332. * @param max defines the maximum vector (in local space)
  18333. */
  18334. function BoundingBox(min, max) {
  18335. this.vectorsWorld = new Array();
  18336. this.reConstruct(min, max);
  18337. }
  18338. // Methods
  18339. /**
  18340. * Recreates the entire bounding box from scratch
  18341. * @param min defines the new minimum vector (in local space)
  18342. * @param max defines the new maximum vector (in local space)
  18343. */
  18344. BoundingBox.prototype.reConstruct = function (min, max) {
  18345. this.minimum = min.clone();
  18346. this.maximum = max.clone();
  18347. // Bounding vectors
  18348. this.vectors = [
  18349. this.minimum.clone(),
  18350. this.maximum.clone(),
  18351. this.minimum.clone(),
  18352. this.minimum.clone(),
  18353. this.minimum.clone(),
  18354. this.maximum.clone(),
  18355. this.maximum.clone(),
  18356. this.maximum.clone()
  18357. ];
  18358. this.vectors[2].x = this.maximum.x;
  18359. this.vectors[3].y = this.maximum.y;
  18360. this.vectors[4].z = this.maximum.z;
  18361. this.vectors[5].z = this.minimum.z;
  18362. this.vectors[6].x = this.minimum.x;
  18363. this.vectors[7].y = this.minimum.y;
  18364. // OBB
  18365. this.center = this.maximum.add(this.minimum).scale(0.5);
  18366. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18367. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18368. // World
  18369. for (var index = 0; index < this.vectors.length; index++) {
  18370. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18371. }
  18372. this.minimumWorld = BABYLON.Vector3.Zero();
  18373. this.maximumWorld = BABYLON.Vector3.Zero();
  18374. this.centerWorld = BABYLON.Vector3.Zero();
  18375. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18376. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18377. };
  18378. /**
  18379. * Scale the current bounding box by applying a scale factor
  18380. * @param factor defines the scale factor to apply
  18381. * @returns the current bounding box
  18382. */
  18383. BoundingBox.prototype.scale = function (factor) {
  18384. var diff = this.maximum.subtract(this.minimum);
  18385. var distance = diff.length() * factor;
  18386. diff.normalize();
  18387. var newRadius = diff.scale(distance / 2);
  18388. var min = this.center.subtract(newRadius);
  18389. var max = this.center.add(newRadius);
  18390. this.reConstruct(min, max);
  18391. return this;
  18392. };
  18393. BoundingBox.prototype.getWorldMatrix = function () {
  18394. return this._worldMatrix;
  18395. };
  18396. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18397. this._worldMatrix.copyFrom(matrix);
  18398. return this;
  18399. };
  18400. /** @hidden */
  18401. BoundingBox.prototype._update = function (world) {
  18402. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18403. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18404. for (var index = 0; index < this.vectors.length; index++) {
  18405. var v = this.vectorsWorld[index];
  18406. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18407. if (v.x < this.minimumWorld.x)
  18408. this.minimumWorld.x = v.x;
  18409. if (v.y < this.minimumWorld.y)
  18410. this.minimumWorld.y = v.y;
  18411. if (v.z < this.minimumWorld.z)
  18412. this.minimumWorld.z = v.z;
  18413. if (v.x > this.maximumWorld.x)
  18414. this.maximumWorld.x = v.x;
  18415. if (v.y > this.maximumWorld.y)
  18416. this.maximumWorld.y = v.y;
  18417. if (v.z > this.maximumWorld.z)
  18418. this.maximumWorld.z = v.z;
  18419. }
  18420. // Extend
  18421. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18422. this.extendSizeWorld.scaleInPlace(0.5);
  18423. // OBB
  18424. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18425. this.centerWorld.scaleInPlace(0.5);
  18426. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18427. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18428. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18429. this._worldMatrix = world;
  18430. };
  18431. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18432. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18433. };
  18434. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18435. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18436. };
  18437. BoundingBox.prototype.intersectsPoint = function (point) {
  18438. var delta = -BABYLON.Epsilon;
  18439. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18440. return false;
  18441. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18442. return false;
  18443. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18444. return false;
  18445. return true;
  18446. };
  18447. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18448. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18449. };
  18450. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18451. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18452. return false;
  18453. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18454. return false;
  18455. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18456. return false;
  18457. return true;
  18458. };
  18459. // Statics
  18460. BoundingBox.Intersects = function (box0, box1) {
  18461. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18462. return false;
  18463. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18464. return false;
  18465. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18466. return false;
  18467. return true;
  18468. };
  18469. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18470. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18471. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18472. return (num <= (sphereRadius * sphereRadius));
  18473. };
  18474. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18475. for (var p = 0; p < 6; p++) {
  18476. for (var i = 0; i < 8; i++) {
  18477. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18478. return false;
  18479. }
  18480. }
  18481. }
  18482. return true;
  18483. };
  18484. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18485. for (var p = 0; p < 6; p++) {
  18486. var inCount = 8;
  18487. for (var i = 0; i < 8; i++) {
  18488. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18489. --inCount;
  18490. }
  18491. else {
  18492. break;
  18493. }
  18494. }
  18495. if (inCount === 0)
  18496. return false;
  18497. }
  18498. return true;
  18499. };
  18500. return BoundingBox;
  18501. }());
  18502. BABYLON.BoundingBox = BoundingBox;
  18503. })(BABYLON || (BABYLON = {}));
  18504. //# sourceMappingURL=babylon.boundingBox.js.map
  18505. var BABYLON;
  18506. (function (BABYLON) {
  18507. var computeBoxExtents = function (axis, box) {
  18508. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18509. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18510. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18511. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18512. var r = r0 + r1 + r2;
  18513. return {
  18514. min: p - r,
  18515. max: p + r
  18516. };
  18517. };
  18518. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18519. var axisOverlap = function (axis, box0, box1) {
  18520. var result0 = computeBoxExtents(axis, box0);
  18521. var result1 = computeBoxExtents(axis, box1);
  18522. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18523. };
  18524. var BoundingInfo = /** @class */ (function () {
  18525. function BoundingInfo(minimum, maximum) {
  18526. this.minimum = minimum;
  18527. this.maximum = maximum;
  18528. this._isLocked = false;
  18529. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18530. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18531. }
  18532. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18533. get: function () {
  18534. return this._isLocked;
  18535. },
  18536. set: function (value) {
  18537. this._isLocked = value;
  18538. },
  18539. enumerable: true,
  18540. configurable: true
  18541. });
  18542. // Methods
  18543. BoundingInfo.prototype.update = function (world) {
  18544. if (this._isLocked) {
  18545. return;
  18546. }
  18547. this.boundingBox._update(world);
  18548. this.boundingSphere._update(world);
  18549. };
  18550. /**
  18551. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18552. * @param center New center of the bounding info
  18553. * @param extend New extend of the bounding info
  18554. */
  18555. BoundingInfo.prototype.centerOn = function (center, extend) {
  18556. this.minimum = center.subtract(extend);
  18557. this.maximum = center.add(extend);
  18558. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18559. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18560. return this;
  18561. };
  18562. /**
  18563. * Scale the current bounding info by applying a scale factor
  18564. * @param factor defines the scale factor to apply
  18565. * @returns the current bounding info
  18566. */
  18567. BoundingInfo.prototype.scale = function (factor) {
  18568. this.boundingBox.scale(factor);
  18569. this.boundingSphere.scale(factor);
  18570. return this;
  18571. };
  18572. /**
  18573. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18574. * @param frustumPlanes defines the frustum to test
  18575. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18576. * @returns true if the bounding info is in the frustum planes
  18577. */
  18578. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18579. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18580. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18581. return false;
  18582. }
  18583. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18584. return true;
  18585. }
  18586. return this.boundingBox.isInFrustum(frustumPlanes);
  18587. };
  18588. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18589. /**
  18590. * Gets the world distance between the min and max points of the bounding box
  18591. */
  18592. get: function () {
  18593. var boundingBox = this.boundingBox;
  18594. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18595. return size.length();
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18601. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18602. };
  18603. /** @hidden */
  18604. BoundingInfo.prototype._checkCollision = function (collider) {
  18605. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18606. };
  18607. BoundingInfo.prototype.intersectsPoint = function (point) {
  18608. if (!this.boundingSphere.centerWorld) {
  18609. return false;
  18610. }
  18611. if (!this.boundingSphere.intersectsPoint(point)) {
  18612. return false;
  18613. }
  18614. if (!this.boundingBox.intersectsPoint(point)) {
  18615. return false;
  18616. }
  18617. return true;
  18618. };
  18619. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18620. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18621. return false;
  18622. }
  18623. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18624. return false;
  18625. }
  18626. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18627. return false;
  18628. }
  18629. if (!precise) {
  18630. return true;
  18631. }
  18632. var box0 = this.boundingBox;
  18633. var box1 = boundingInfo.boundingBox;
  18634. if (!axisOverlap(box0.directions[0], box0, box1))
  18635. return false;
  18636. if (!axisOverlap(box0.directions[1], box0, box1))
  18637. return false;
  18638. if (!axisOverlap(box0.directions[2], box0, box1))
  18639. return false;
  18640. if (!axisOverlap(box1.directions[0], box0, box1))
  18641. return false;
  18642. if (!axisOverlap(box1.directions[1], box0, box1))
  18643. return false;
  18644. if (!axisOverlap(box1.directions[2], box0, box1))
  18645. return false;
  18646. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18647. return false;
  18648. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18649. return false;
  18650. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18651. return false;
  18652. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18653. return false;
  18654. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18655. return false;
  18656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18657. return false;
  18658. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18659. return false;
  18660. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18661. return false;
  18662. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18663. return false;
  18664. return true;
  18665. };
  18666. return BoundingInfo;
  18667. }());
  18668. BABYLON.BoundingInfo = BoundingInfo;
  18669. })(BABYLON || (BABYLON = {}));
  18670. //# sourceMappingURL=babylon.boundingInfo.js.map
  18671. var BABYLON;
  18672. (function (BABYLON) {
  18673. var TransformNode = /** @class */ (function (_super) {
  18674. __extends(TransformNode, _super);
  18675. function TransformNode(name, scene, isPure) {
  18676. if (scene === void 0) { scene = null; }
  18677. if (isPure === void 0) { isPure = true; }
  18678. var _this = _super.call(this, name, scene) || this;
  18679. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18680. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18681. _this._up = new BABYLON.Vector3(0, 1, 0);
  18682. _this._right = new BABYLON.Vector3(1, 0, 0);
  18683. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18684. // Properties
  18685. _this._position = BABYLON.Vector3.Zero();
  18686. _this._rotation = BABYLON.Vector3.Zero();
  18687. _this._scaling = BABYLON.Vector3.One();
  18688. _this._isDirty = false;
  18689. /**
  18690. * Set the billboard mode. Default is 0.
  18691. *
  18692. * | Value | Type | Description |
  18693. * | --- | --- | --- |
  18694. * | 0 | BILLBOARDMODE_NONE | |
  18695. * | 1 | BILLBOARDMODE_X | |
  18696. * | 2 | BILLBOARDMODE_Y | |
  18697. * | 4 | BILLBOARDMODE_Z | |
  18698. * | 7 | BILLBOARDMODE_ALL | |
  18699. *
  18700. */
  18701. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18702. _this.scalingDeterminant = 1;
  18703. _this.infiniteDistance = false;
  18704. /**
  18705. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18706. * By default the system will update normals to compensate
  18707. */
  18708. _this.ignoreNonUniformScaling = false;
  18709. _this._localWorld = BABYLON.Matrix.Zero();
  18710. _this._absolutePosition = BABYLON.Vector3.Zero();
  18711. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18712. _this._postMultiplyPivotMatrix = false;
  18713. _this._isWorldMatrixFrozen = false;
  18714. /**
  18715. * An event triggered after the world matrix is updated
  18716. */
  18717. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18718. _this._nonUniformScaling = false;
  18719. if (isPure) {
  18720. _this.getScene().addTransformNode(_this);
  18721. }
  18722. return _this;
  18723. }
  18724. /**
  18725. * Gets a string identifying the name of the class
  18726. * @returns "TransformNode" string
  18727. */
  18728. TransformNode.prototype.getClassName = function () {
  18729. return "TransformNode";
  18730. };
  18731. Object.defineProperty(TransformNode.prototype, "position", {
  18732. /**
  18733. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  18734. */
  18735. get: function () {
  18736. return this._position;
  18737. },
  18738. set: function (newPosition) {
  18739. this._position = newPosition;
  18740. this._isDirty = true;
  18741. },
  18742. enumerable: true,
  18743. configurable: true
  18744. });
  18745. Object.defineProperty(TransformNode.prototype, "rotation", {
  18746. /**
  18747. * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18748. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  18749. */
  18750. get: function () {
  18751. return this._rotation;
  18752. },
  18753. set: function (newRotation) {
  18754. this._rotation = newRotation;
  18755. this._isDirty = true;
  18756. },
  18757. enumerable: true,
  18758. configurable: true
  18759. });
  18760. Object.defineProperty(TransformNode.prototype, "scaling", {
  18761. /**
  18762. * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
  18763. */
  18764. get: function () {
  18765. return this._scaling;
  18766. },
  18767. set: function (newScaling) {
  18768. this._scaling = newScaling;
  18769. this._isDirty = true;
  18770. },
  18771. enumerable: true,
  18772. configurable: true
  18773. });
  18774. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18775. /**
  18776. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  18777. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  18778. */
  18779. get: function () {
  18780. return this._rotationQuaternion;
  18781. },
  18782. set: function (quaternion) {
  18783. this._rotationQuaternion = quaternion;
  18784. //reset the rotation vector.
  18785. if (quaternion && this.rotation.length()) {
  18786. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18787. }
  18788. },
  18789. enumerable: true,
  18790. configurable: true
  18791. });
  18792. Object.defineProperty(TransformNode.prototype, "forward", {
  18793. /**
  18794. * The forward direction of that transform in world space.
  18795. */
  18796. get: function () {
  18797. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18798. },
  18799. enumerable: true,
  18800. configurable: true
  18801. });
  18802. Object.defineProperty(TransformNode.prototype, "up", {
  18803. /**
  18804. * The up direction of that transform in world space.
  18805. */
  18806. get: function () {
  18807. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18808. },
  18809. enumerable: true,
  18810. configurable: true
  18811. });
  18812. Object.defineProperty(TransformNode.prototype, "right", {
  18813. /**
  18814. * The right direction of that transform in world space.
  18815. */
  18816. get: function () {
  18817. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18818. },
  18819. enumerable: true,
  18820. configurable: true
  18821. });
  18822. /**
  18823. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18824. * Returns the TransformNode.
  18825. */
  18826. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18827. this._poseMatrix.copyFrom(matrix);
  18828. return this;
  18829. };
  18830. /**
  18831. * Returns the mesh Pose matrix.
  18832. * Returned object : Matrix
  18833. */
  18834. TransformNode.prototype.getPoseMatrix = function () {
  18835. return this._poseMatrix;
  18836. };
  18837. /** @hidden */
  18838. TransformNode.prototype._isSynchronized = function () {
  18839. if (this._isDirty) {
  18840. return false;
  18841. }
  18842. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18843. return false;
  18844. if (this._cache.pivotMatrixUpdated) {
  18845. return false;
  18846. }
  18847. if (this.infiniteDistance) {
  18848. return false;
  18849. }
  18850. if (!this._cache.position.equals(this._position))
  18851. return false;
  18852. if (this._rotationQuaternion) {
  18853. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  18854. return false;
  18855. }
  18856. if (!this._cache.rotation.equals(this._rotation))
  18857. return false;
  18858. if (!this._cache.scaling.equals(this._scaling))
  18859. return false;
  18860. return true;
  18861. };
  18862. /** @hidden */
  18863. TransformNode.prototype._initCache = function () {
  18864. _super.prototype._initCache.call(this);
  18865. this._cache.localMatrixUpdated = false;
  18866. this._cache.position = BABYLON.Vector3.Zero();
  18867. this._cache.scaling = BABYLON.Vector3.Zero();
  18868. this._cache.rotation = BABYLON.Vector3.Zero();
  18869. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18870. this._cache.billboardMode = -1;
  18871. };
  18872. TransformNode.prototype.markAsDirty = function (property) {
  18873. if (property === "rotation") {
  18874. this.rotationQuaternion = null;
  18875. }
  18876. this._currentRenderId = Number.MAX_VALUE;
  18877. this._isDirty = true;
  18878. return this;
  18879. };
  18880. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18881. /**
  18882. * Returns the current mesh absolute position.
  18883. * Returns a Vector3.
  18884. */
  18885. get: function () {
  18886. return this._absolutePosition;
  18887. },
  18888. enumerable: true,
  18889. configurable: true
  18890. });
  18891. /**
  18892. * Sets a new matrix to apply before all other transformation
  18893. * @param matrix defines the transform matrix
  18894. * @returns the current TransformNode
  18895. */
  18896. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18897. return this.setPivotMatrix(matrix, false);
  18898. };
  18899. /**
  18900. * Sets a new pivot matrix to the current node
  18901. * @param matrix defines the new pivot matrix to use
  18902. * @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
  18903. * @returns the current TransformNode
  18904. */
  18905. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18906. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18907. this._pivotMatrix = matrix.clone();
  18908. this._cache.pivotMatrixUpdated = true;
  18909. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18910. if (this._postMultiplyPivotMatrix) {
  18911. if (!this._pivotMatrixInverse) {
  18912. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18913. }
  18914. else {
  18915. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18916. }
  18917. }
  18918. return this;
  18919. };
  18920. /**
  18921. * Returns the mesh pivot matrix.
  18922. * Default : Identity.
  18923. * A Matrix is returned.
  18924. */
  18925. TransformNode.prototype.getPivotMatrix = function () {
  18926. return this._pivotMatrix;
  18927. };
  18928. /**
  18929. * Prevents the World matrix to be computed any longer.
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.freezeWorldMatrix = function () {
  18933. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18934. this.computeWorldMatrix(true);
  18935. this._isWorldMatrixFrozen = true;
  18936. return this;
  18937. };
  18938. /**
  18939. * Allows back the World matrix computation.
  18940. * Returns the TransformNode.
  18941. */
  18942. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18943. this._isWorldMatrixFrozen = false;
  18944. this.computeWorldMatrix(true);
  18945. return this;
  18946. };
  18947. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18948. /**
  18949. * True if the World matrix has been frozen.
  18950. * Returns a boolean.
  18951. */
  18952. get: function () {
  18953. return this._isWorldMatrixFrozen;
  18954. },
  18955. enumerable: true,
  18956. configurable: true
  18957. });
  18958. /**
  18959. * Retuns the mesh absolute position in the World.
  18960. * Returns a Vector3.
  18961. */
  18962. TransformNode.prototype.getAbsolutePosition = function () {
  18963. this.computeWorldMatrix();
  18964. return this._absolutePosition;
  18965. };
  18966. /**
  18967. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18968. * Returns the TransformNode.
  18969. */
  18970. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18971. if (!absolutePosition) {
  18972. return this;
  18973. }
  18974. var absolutePositionX;
  18975. var absolutePositionY;
  18976. var absolutePositionZ;
  18977. if (absolutePosition.x === undefined) {
  18978. if (arguments.length < 3) {
  18979. return this;
  18980. }
  18981. absolutePositionX = arguments[0];
  18982. absolutePositionY = arguments[1];
  18983. absolutePositionZ = arguments[2];
  18984. }
  18985. else {
  18986. absolutePositionX = absolutePosition.x;
  18987. absolutePositionY = absolutePosition.y;
  18988. absolutePositionZ = absolutePosition.z;
  18989. }
  18990. if (this.parent) {
  18991. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18992. invertParentWorldMatrix.invert();
  18993. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18994. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18995. }
  18996. else {
  18997. this.position.x = absolutePositionX;
  18998. this.position.y = absolutePositionY;
  18999. this.position.z = absolutePositionZ;
  19000. }
  19001. return this;
  19002. };
  19003. /**
  19004. * Sets the mesh position in its local space.
  19005. * Returns the TransformNode.
  19006. */
  19007. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19008. this.computeWorldMatrix();
  19009. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19010. return this;
  19011. };
  19012. /**
  19013. * Returns the mesh position in the local space from the current World matrix values.
  19014. * Returns a new Vector3.
  19015. */
  19016. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19017. this.computeWorldMatrix();
  19018. var invLocalWorldMatrix = this._localWorld.clone();
  19019. invLocalWorldMatrix.invert();
  19020. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19021. };
  19022. /**
  19023. * Translates the mesh along the passed Vector3 in its local space.
  19024. * Returns the TransformNode.
  19025. */
  19026. TransformNode.prototype.locallyTranslate = function (vector3) {
  19027. this.computeWorldMatrix(true);
  19028. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19029. return this;
  19030. };
  19031. /**
  19032. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19033. * @param targetPoint the position (must be in same space as current mesh) to look at
  19034. * @param yawCor optional yaw (y-axis) correction in radians
  19035. * @param pitchCor optional pitch (x-axis) correction in radians
  19036. * @param rollCor optional roll (z-axis) correction in radians
  19037. * @param space the choosen space of the target
  19038. * @returns the TransformNode.
  19039. */
  19040. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19041. if (yawCor === void 0) { yawCor = 0; }
  19042. if (pitchCor === void 0) { pitchCor = 0; }
  19043. if (rollCor === void 0) { rollCor = 0; }
  19044. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19045. var dv = TransformNode._lookAtVectorCache;
  19046. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19047. targetPoint.subtractToRef(pos, dv);
  19048. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19049. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19050. var pitch = Math.atan2(dv.y, len);
  19051. if (this.rotationQuaternion) {
  19052. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19053. }
  19054. else {
  19055. this.rotation.x = pitch + pitchCor;
  19056. this.rotation.y = yaw + yawCor;
  19057. this.rotation.z = rollCor;
  19058. }
  19059. return this;
  19060. };
  19061. /**
  19062. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19063. * This Vector3 is expressed in the World space.
  19064. */
  19065. TransformNode.prototype.getDirection = function (localAxis) {
  19066. var result = BABYLON.Vector3.Zero();
  19067. this.getDirectionToRef(localAxis, result);
  19068. return result;
  19069. };
  19070. /**
  19071. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19072. * localAxis is expressed in the mesh local space.
  19073. * result is computed in the Wordl space from the mesh World matrix.
  19074. * Returns the TransformNode.
  19075. */
  19076. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19077. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19078. return this;
  19079. };
  19080. /**
  19081. * Sets a new pivot point to the current node
  19082. * @param point defines the new pivot point to use
  19083. * @param space defines if the point is in world or local space (local by default)
  19084. * @returns the current TransformNode
  19085. */
  19086. TransformNode.prototype.setPivotPoint = function (point, space) {
  19087. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19088. if (this.getScene().getRenderId() == 0) {
  19089. this.computeWorldMatrix(true);
  19090. }
  19091. var wm = this.getWorldMatrix();
  19092. if (space == BABYLON.Space.WORLD) {
  19093. var tmat = BABYLON.Tmp.Matrix[0];
  19094. wm.invertToRef(tmat);
  19095. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19096. }
  19097. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19098. };
  19099. /**
  19100. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19101. */
  19102. TransformNode.prototype.getPivotPoint = function () {
  19103. var point = BABYLON.Vector3.Zero();
  19104. this.getPivotPointToRef(point);
  19105. return point;
  19106. };
  19107. /**
  19108. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19109. * Returns the TransformNode.
  19110. */
  19111. TransformNode.prototype.getPivotPointToRef = function (result) {
  19112. result.x = -this._pivotMatrix.m[12];
  19113. result.y = -this._pivotMatrix.m[13];
  19114. result.z = -this._pivotMatrix.m[14];
  19115. return this;
  19116. };
  19117. /**
  19118. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19119. */
  19120. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19121. var point = BABYLON.Vector3.Zero();
  19122. this.getAbsolutePivotPointToRef(point);
  19123. return point;
  19124. };
  19125. /**
  19126. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19127. * Returns the TransformNode.
  19128. */
  19129. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19130. result.x = this._pivotMatrix.m[12];
  19131. result.y = this._pivotMatrix.m[13];
  19132. result.z = this._pivotMatrix.m[14];
  19133. this.getPivotPointToRef(result);
  19134. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19135. return this;
  19136. };
  19137. /**
  19138. * Defines the passed node as the parent of the current node.
  19139. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19140. * Returns the TransformNode.
  19141. */
  19142. TransformNode.prototype.setParent = function (node) {
  19143. if (!node && !this.parent) {
  19144. return this;
  19145. }
  19146. if (!node) {
  19147. var rotation = BABYLON.Tmp.Quaternion[0];
  19148. var position = BABYLON.Tmp.Vector3[0];
  19149. var scale = BABYLON.Tmp.Vector3[1];
  19150. if (this.parent && this.parent.computeWorldMatrix) {
  19151. this.parent.computeWorldMatrix(true);
  19152. }
  19153. this.computeWorldMatrix(true);
  19154. this.getWorldMatrix().decompose(scale, rotation, position);
  19155. if (this.rotationQuaternion) {
  19156. this.rotationQuaternion.copyFrom(rotation);
  19157. }
  19158. else {
  19159. rotation.toEulerAnglesToRef(this.rotation);
  19160. }
  19161. this.scaling.x = scale.x;
  19162. this.scaling.y = scale.y;
  19163. this.scaling.z = scale.z;
  19164. this.position.x = position.x;
  19165. this.position.y = position.y;
  19166. this.position.z = position.z;
  19167. }
  19168. else {
  19169. var rotation = BABYLON.Tmp.Quaternion[0];
  19170. var position = BABYLON.Tmp.Vector3[0];
  19171. var scale = BABYLON.Tmp.Vector3[1];
  19172. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19173. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19174. this.computeWorldMatrix(true);
  19175. node.computeWorldMatrix(true);
  19176. node.getWorldMatrix().invertToRef(invParentMatrix);
  19177. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19178. diffMatrix.decompose(scale, rotation, position);
  19179. if (this.rotationQuaternion) {
  19180. this.rotationQuaternion.copyFrom(rotation);
  19181. }
  19182. else {
  19183. rotation.toEulerAnglesToRef(this.rotation);
  19184. }
  19185. this.position.x = position.x;
  19186. this.position.y = position.y;
  19187. this.position.z = position.z;
  19188. this.scaling.x = scale.x;
  19189. this.scaling.y = scale.y;
  19190. this.scaling.z = scale.z;
  19191. }
  19192. this.parent = node;
  19193. return this;
  19194. };
  19195. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19196. get: function () {
  19197. return this._nonUniformScaling;
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. /** @hidden */
  19203. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19204. if (this._nonUniformScaling === value) {
  19205. return false;
  19206. }
  19207. this._nonUniformScaling = value;
  19208. return true;
  19209. };
  19210. /**
  19211. * Attach the current TransformNode to another TransformNode associated with a bone
  19212. * @param bone Bone affecting the TransformNode
  19213. * @param affectedTransformNode TransformNode associated with the bone
  19214. */
  19215. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19216. this._transformToBoneReferal = affectedTransformNode;
  19217. this.parent = bone;
  19218. if (bone.getWorldMatrix().determinant() < 0) {
  19219. this.scalingDeterminant *= -1;
  19220. }
  19221. return this;
  19222. };
  19223. TransformNode.prototype.detachFromBone = function () {
  19224. if (!this.parent) {
  19225. return this;
  19226. }
  19227. if (this.parent.getWorldMatrix().determinant() < 0) {
  19228. this.scalingDeterminant *= -1;
  19229. }
  19230. this._transformToBoneReferal = null;
  19231. this.parent = null;
  19232. return this;
  19233. };
  19234. /**
  19235. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19236. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19237. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19238. * The passed axis is also normalized.
  19239. * Returns the TransformNode.
  19240. */
  19241. TransformNode.prototype.rotate = function (axis, amount, space) {
  19242. axis.normalize();
  19243. if (!this.rotationQuaternion) {
  19244. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19245. this.rotation = BABYLON.Vector3.Zero();
  19246. }
  19247. var rotationQuaternion;
  19248. if (!space || space === BABYLON.Space.LOCAL) {
  19249. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19250. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19251. }
  19252. else {
  19253. if (this.parent) {
  19254. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19255. invertParentWorldMatrix.invert();
  19256. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19257. }
  19258. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19259. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19260. }
  19261. return this;
  19262. };
  19263. /**
  19264. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19265. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19266. * The passed axis is also normalized.
  19267. * Returns the TransformNode.
  19268. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19269. */
  19270. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19271. axis.normalize();
  19272. if (!this.rotationQuaternion) {
  19273. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19274. this.rotation.copyFromFloats(0, 0, 0);
  19275. }
  19276. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19277. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19278. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19279. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19280. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19281. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19282. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19283. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19284. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19285. return this;
  19286. };
  19287. /**
  19288. * Translates the mesh along the axis vector for the passed distance in the given space.
  19289. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19290. * Returns the TransformNode.
  19291. */
  19292. TransformNode.prototype.translate = function (axis, distance, space) {
  19293. var displacementVector = axis.scale(distance);
  19294. if (!space || space === BABYLON.Space.LOCAL) {
  19295. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19296. this.setPositionWithLocalVector(tempV3);
  19297. }
  19298. else {
  19299. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19300. }
  19301. return this;
  19302. };
  19303. /**
  19304. * Adds a rotation step to the mesh current rotation.
  19305. * x, y, z are Euler angles expressed in radians.
  19306. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19307. * This means this rotation is made in the mesh local space only.
  19308. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19309. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19310. * ```javascript
  19311. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19312. * ```
  19313. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19314. * 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.
  19315. * Returns the TransformNode.
  19316. */
  19317. TransformNode.prototype.addRotation = function (x, y, z) {
  19318. var rotationQuaternion;
  19319. if (this.rotationQuaternion) {
  19320. rotationQuaternion = this.rotationQuaternion;
  19321. }
  19322. else {
  19323. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19324. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19325. }
  19326. var accumulation = BABYLON.Tmp.Quaternion[0];
  19327. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19328. rotationQuaternion.multiplyInPlace(accumulation);
  19329. if (!this.rotationQuaternion) {
  19330. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19331. }
  19332. return this;
  19333. };
  19334. /**
  19335. * Computes the world matrix of the node
  19336. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  19337. * @returns the world matrix
  19338. */
  19339. TransformNode.prototype.computeWorldMatrix = function (force) {
  19340. if (this._isWorldMatrixFrozen) {
  19341. return this._worldMatrix;
  19342. }
  19343. if (!force && this.isSynchronized()) {
  19344. this._currentRenderId = this.getScene().getRenderId();
  19345. return this._worldMatrix;
  19346. }
  19347. this._updateCache();
  19348. this._cache.position.copyFrom(this.position);
  19349. this._cache.scaling.copyFrom(this.scaling);
  19350. this._cache.pivotMatrixUpdated = false;
  19351. this._cache.billboardMode = this.billboardMode;
  19352. this._currentRenderId = this.getScene().getRenderId();
  19353. this._childRenderId = this.getScene().getRenderId();
  19354. this._isDirty = false;
  19355. // Scaling
  19356. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19357. // Rotation
  19358. //rotate, if quaternion is set and rotation was used
  19359. if (this.rotationQuaternion) {
  19360. var len = this.rotation.length();
  19361. if (len) {
  19362. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19363. this.rotation.copyFromFloats(0, 0, 0);
  19364. }
  19365. }
  19366. if (this.rotationQuaternion) {
  19367. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19368. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19369. }
  19370. else {
  19371. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19372. this._cache.rotation.copyFrom(this.rotation);
  19373. }
  19374. // Translation
  19375. var camera = this.getScene().activeCamera;
  19376. if (this.infiniteDistance && !this.parent && camera) {
  19377. var cameraWorldMatrix = camera.getWorldMatrix();
  19378. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19379. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19380. }
  19381. else {
  19382. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19383. }
  19384. // Composing transformations
  19385. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19386. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19387. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19388. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19389. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19390. // Need to decompose each rotation here
  19391. var currentPosition = BABYLON.Tmp.Vector3[3];
  19392. if (this.parent && this.parent.getWorldMatrix) {
  19393. if (this._transformToBoneReferal) {
  19394. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19395. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19396. }
  19397. else {
  19398. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19399. }
  19400. }
  19401. else {
  19402. currentPosition.copyFrom(this.position);
  19403. }
  19404. currentPosition.subtractInPlace(camera.globalPosition);
  19405. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19406. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19407. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19408. }
  19409. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19410. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19411. }
  19412. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19413. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19414. }
  19415. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19416. }
  19417. else {
  19418. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19419. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19420. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19421. }
  19422. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19423. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19424. }
  19425. // Post multiply inverse of pivotMatrix
  19426. if (this._postMultiplyPivotMatrix) {
  19427. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19428. }
  19429. // Local world
  19430. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19431. // Parent
  19432. if (this.parent && this.parent.getWorldMatrix) {
  19433. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19434. if (this._transformToBoneReferal) {
  19435. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19436. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19437. }
  19438. else {
  19439. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19440. }
  19441. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19442. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19443. this._worldMatrix.copyFrom(this._localWorld);
  19444. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19445. }
  19446. else {
  19447. if (this._transformToBoneReferal) {
  19448. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19449. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19450. }
  19451. else {
  19452. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19453. }
  19454. }
  19455. this._markSyncedWithParent();
  19456. }
  19457. else {
  19458. this._worldMatrix.copyFrom(this._localWorld);
  19459. }
  19460. // Normal matrix
  19461. if (!this.ignoreNonUniformScaling) {
  19462. if (this.scaling.isNonUniform) {
  19463. this._updateNonUniformScalingState(true);
  19464. }
  19465. else if (this.parent && this.parent._nonUniformScaling) {
  19466. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19467. }
  19468. else {
  19469. this._updateNonUniformScalingState(false);
  19470. }
  19471. }
  19472. else {
  19473. this._updateNonUniformScalingState(false);
  19474. }
  19475. this._afterComputeWorldMatrix();
  19476. // Absolute position
  19477. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19478. // Callbacks
  19479. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19480. if (!this._poseMatrix) {
  19481. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19482. }
  19483. // Cache the determinant
  19484. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19485. return this._worldMatrix;
  19486. };
  19487. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19488. };
  19489. /**
  19490. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19491. * @param func: callback function to add
  19492. *
  19493. * Returns the TransformNode.
  19494. */
  19495. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19496. this.onAfterWorldMatrixUpdateObservable.add(func);
  19497. return this;
  19498. };
  19499. /**
  19500. * Removes a registered callback function.
  19501. * Returns the TransformNode.
  19502. */
  19503. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19504. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19505. return this;
  19506. };
  19507. /**
  19508. * Clone the current transform node
  19509. * Returns the new transform node
  19510. * @param name Name of the new clone
  19511. * @param newParent New parent for the clone
  19512. * @param doNotCloneChildren Do not clone children hierarchy
  19513. */
  19514. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19515. var _this = this;
  19516. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19517. result.name = name;
  19518. result.id = name;
  19519. if (newParent) {
  19520. result.parent = newParent;
  19521. }
  19522. if (!doNotCloneChildren) {
  19523. // Children
  19524. var directDescendants = this.getDescendants(true);
  19525. for (var index = 0; index < directDescendants.length; index++) {
  19526. var child = directDescendants[index];
  19527. if (child.clone) {
  19528. child.clone(name + "." + child.name, result);
  19529. }
  19530. }
  19531. }
  19532. return result;
  19533. };
  19534. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19535. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19536. serializationObject.type = this.getClassName();
  19537. // Parent
  19538. if (this.parent) {
  19539. serializationObject.parentId = this.parent.id;
  19540. }
  19541. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19542. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19543. }
  19544. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19545. serializationObject.isEnabled = this.isEnabled();
  19546. // Parent
  19547. if (this.parent) {
  19548. serializationObject.parentId = this.parent.id;
  19549. }
  19550. return serializationObject;
  19551. };
  19552. // Statics
  19553. /**
  19554. * Returns a new TransformNode object parsed from the source provided.
  19555. * The parameter `parsedMesh` is the source.
  19556. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19557. */
  19558. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19559. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19560. if (BABYLON.Tags) {
  19561. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19562. }
  19563. if (parsedTransformNode.localMatrix) {
  19564. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19565. }
  19566. else if (parsedTransformNode.pivotMatrix) {
  19567. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19568. }
  19569. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19570. // Parent
  19571. if (parsedTransformNode.parentId) {
  19572. transformNode._waitingParentId = parsedTransformNode.parentId;
  19573. }
  19574. return transformNode;
  19575. };
  19576. /**
  19577. * Releases resources associated with this transform node.
  19578. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19579. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19580. */
  19581. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19582. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19583. // Animations
  19584. this.getScene().stopAnimation(this);
  19585. // Remove from scene
  19586. this.getScene().removeTransformNode(this);
  19587. this.onAfterWorldMatrixUpdateObservable.clear();
  19588. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19589. };
  19590. // Statics
  19591. TransformNode.BILLBOARDMODE_NONE = 0;
  19592. TransformNode.BILLBOARDMODE_X = 1;
  19593. TransformNode.BILLBOARDMODE_Y = 2;
  19594. TransformNode.BILLBOARDMODE_Z = 4;
  19595. TransformNode.BILLBOARDMODE_ALL = 7;
  19596. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19597. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19598. __decorate([
  19599. BABYLON.serializeAsVector3("position")
  19600. ], TransformNode.prototype, "_position", void 0);
  19601. __decorate([
  19602. BABYLON.serializeAsVector3("rotation")
  19603. ], TransformNode.prototype, "_rotation", void 0);
  19604. __decorate([
  19605. BABYLON.serializeAsQuaternion("rotationQuaternion")
  19606. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19607. __decorate([
  19608. BABYLON.serializeAsVector3("scaling")
  19609. ], TransformNode.prototype, "_scaling", void 0);
  19610. __decorate([
  19611. BABYLON.serialize()
  19612. ], TransformNode.prototype, "billboardMode", void 0);
  19613. __decorate([
  19614. BABYLON.serialize()
  19615. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19616. __decorate([
  19617. BABYLON.serialize()
  19618. ], TransformNode.prototype, "infiniteDistance", void 0);
  19619. __decorate([
  19620. BABYLON.serialize()
  19621. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19622. return TransformNode;
  19623. }(BABYLON.Node));
  19624. BABYLON.TransformNode = TransformNode;
  19625. })(BABYLON || (BABYLON = {}));
  19626. //# sourceMappingURL=babylon.transformNode.js.map
  19627. var BABYLON;
  19628. (function (BABYLON) {
  19629. /**
  19630. * Class used to store all common mesh properties
  19631. */
  19632. var AbstractMesh = /** @class */ (function (_super) {
  19633. __extends(AbstractMesh, _super);
  19634. // Constructor
  19635. /**
  19636. * Creates a new AbstractMesh
  19637. * @param name defines the name of the mesh
  19638. * @param scene defines the hosting scene
  19639. */
  19640. function AbstractMesh(name, scene) {
  19641. if (scene === void 0) { scene = null; }
  19642. var _this = _super.call(this, name, scene, false) || this;
  19643. _this._facetNb = 0; // facet number
  19644. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19645. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19646. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19647. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19648. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19649. _this._subDiv = {
  19650. max: 1,
  19651. X: 1,
  19652. Y: 1,
  19653. Z: 1
  19654. };
  19655. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19656. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19657. /** Gets ot sets the culling strategy to use to find visible meshes */
  19658. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19659. // Events
  19660. /**
  19661. * An event triggered when this mesh collides with another one
  19662. */
  19663. _this.onCollideObservable = new BABYLON.Observable();
  19664. /**
  19665. * An event triggered when the collision's position changes
  19666. */
  19667. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19668. /**
  19669. * An event triggered when material is changed
  19670. */
  19671. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19672. // Properties
  19673. /**
  19674. * Gets or sets the orientation for POV movement & rotation
  19675. */
  19676. _this.definedFacingForward = true;
  19677. /**
  19678. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19679. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19680. * * 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.
  19681. * @see http://doc.babylonjs.com/features/occlusionquery
  19682. */
  19683. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19684. /**
  19685. * 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:
  19686. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19687. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19688. * * 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.
  19689. * @see http://doc.babylonjs.com/features/occlusionquery
  19690. */
  19691. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19692. /**
  19693. * 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.
  19694. * The default value is -1 which means don't break the query and wait till the result
  19695. * @see http://doc.babylonjs.com/features/occlusionquery
  19696. */
  19697. _this.occlusionRetryCount = -1;
  19698. /** @hidden */
  19699. _this._occlusionInternalRetryCounter = 0;
  19700. /** @hidden */
  19701. _this._isOccluded = false;
  19702. /** @hidden */
  19703. _this._isOcclusionQueryInProgress = false;
  19704. _this._visibility = 1.0;
  19705. /** Gets or sets the alpha index used to sort transparent meshes
  19706. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19707. */
  19708. _this.alphaIndex = Number.MAX_VALUE;
  19709. /**
  19710. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19711. */
  19712. _this.isVisible = true;
  19713. /**
  19714. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19715. */
  19716. _this.isPickable = true;
  19717. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19718. _this.showSubMeshesBoundingBox = false;
  19719. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19720. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19721. */
  19722. _this.isBlocker = false;
  19723. /**
  19724. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19725. */
  19726. _this.enablePointerMoveEvents = false;
  19727. /**
  19728. * Specifies the rendering group id for this mesh (0 by default)
  19729. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19730. */
  19731. _this.renderingGroupId = 0;
  19732. _this._receiveShadows = false;
  19733. /** Defines color to use when rendering outline */
  19734. _this.outlineColor = BABYLON.Color3.Red();
  19735. /** Define width to use when rendering outline */
  19736. _this.outlineWidth = 0.02;
  19737. /** Defines color to use when rendering overlay */
  19738. _this.overlayColor = BABYLON.Color3.Red();
  19739. /** Defines alpha to use when rendering overlay */
  19740. _this.overlayAlpha = 0.5;
  19741. _this._hasVertexAlpha = false;
  19742. _this._useVertexColors = true;
  19743. _this._computeBonesUsingShaders = true;
  19744. _this._numBoneInfluencers = 4;
  19745. _this._applyFog = true;
  19746. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19747. _this.useOctreeForRenderingSelection = true;
  19748. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19749. _this.useOctreeForPicking = true;
  19750. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19751. _this.useOctreeForCollisions = true;
  19752. _this._layerMask = 0x0FFFFFFF;
  19753. /**
  19754. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19755. */
  19756. _this.alwaysSelectAsActiveMesh = false;
  19757. /**
  19758. * Gets or sets the current action manager
  19759. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19760. */
  19761. _this.actionManager = null;
  19762. // Collisions
  19763. _this._checkCollisions = false;
  19764. _this._collisionMask = -1;
  19765. _this._collisionGroup = -1;
  19766. /**
  19767. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19768. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19769. */
  19770. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19771. /**
  19772. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19773. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19774. */
  19775. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19776. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19777. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19778. // Edges
  19779. /**
  19780. * Defines edge width used when edgesRenderer is enabled
  19781. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19782. */
  19783. _this.edgesWidth = 1;
  19784. /**
  19785. * Defines edge color used when edgesRenderer is enabled
  19786. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19787. */
  19788. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19789. // Cache
  19790. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19791. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19792. /** @hidden */
  19793. _this._renderId = 0;
  19794. /** @hidden */
  19795. _this._intersectionsInProgress = new Array();
  19796. /** @hidden */
  19797. _this._unIndexed = false;
  19798. /** @hidden */
  19799. _this._lightSources = new Array();
  19800. /**
  19801. * An event triggered when the mesh is rebuilt.
  19802. */
  19803. _this.onRebuildObservable = new BABYLON.Observable();
  19804. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19805. if (collidedMesh === void 0) { collidedMesh = null; }
  19806. //TODO move this to the collision coordinator!
  19807. if (_this.getScene().workerCollisions)
  19808. newPosition.multiplyInPlace(_this._collider._radius);
  19809. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19810. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19811. _this.position.addInPlace(_this._diffPositionForCollisions);
  19812. }
  19813. if (collidedMesh) {
  19814. _this.onCollideObservable.notifyObservers(collidedMesh);
  19815. }
  19816. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19817. };
  19818. _this.getScene().addMesh(_this);
  19819. _this._resyncLightSources();
  19820. return _this;
  19821. }
  19822. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19823. /**
  19824. * No billboard
  19825. */
  19826. get: function () {
  19827. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19833. /** Billboard on X axis */
  19834. get: function () {
  19835. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19836. },
  19837. enumerable: true,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19841. /** Billboard on Y axis */
  19842. get: function () {
  19843. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19844. },
  19845. enumerable: true,
  19846. configurable: true
  19847. });
  19848. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19849. /** Billboard on Z axis */
  19850. get: function () {
  19851. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19857. /** Billboard on all axes */
  19858. get: function () {
  19859. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19860. },
  19861. enumerable: true,
  19862. configurable: true
  19863. });
  19864. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19865. /**
  19866. * Gets the number of facets in the mesh
  19867. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19868. */
  19869. get: function () {
  19870. return this._facetNb;
  19871. },
  19872. enumerable: true,
  19873. configurable: true
  19874. });
  19875. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19876. /**
  19877. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19878. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19879. */
  19880. get: function () {
  19881. return this._partitioningSubdivisions;
  19882. },
  19883. set: function (nb) {
  19884. this._partitioningSubdivisions = nb;
  19885. },
  19886. enumerable: true,
  19887. configurable: true
  19888. });
  19889. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19890. /**
  19891. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19892. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19893. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19894. */
  19895. get: function () {
  19896. return this._partitioningBBoxRatio;
  19897. },
  19898. set: function (ratio) {
  19899. this._partitioningBBoxRatio = ratio;
  19900. },
  19901. enumerable: true,
  19902. configurable: true
  19903. });
  19904. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19905. /**
  19906. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19907. * Works only for updatable meshes.
  19908. * Doesn't work with multi-materials
  19909. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19910. */
  19911. get: function () {
  19912. return this._facetDepthSort;
  19913. },
  19914. set: function (sort) {
  19915. this._facetDepthSort = sort;
  19916. },
  19917. enumerable: true,
  19918. configurable: true
  19919. });
  19920. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19921. /**
  19922. * The location (Vector3) where the facet depth sort must be computed from.
  19923. * By default, the active camera position.
  19924. * Used only when facet depth sort is enabled
  19925. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19926. */
  19927. get: function () {
  19928. return this._facetDepthSortFrom;
  19929. },
  19930. set: function (location) {
  19931. this._facetDepthSortFrom = location;
  19932. },
  19933. enumerable: true,
  19934. configurable: true
  19935. });
  19936. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19937. /**
  19938. * gets a boolean indicating if facetData is enabled
  19939. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19940. */
  19941. get: function () {
  19942. return this._facetDataEnabled;
  19943. },
  19944. enumerable: true,
  19945. configurable: true
  19946. });
  19947. /** @hidden */
  19948. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19949. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19950. return false;
  19951. }
  19952. this._markSubMeshesAsMiscDirty();
  19953. return true;
  19954. };
  19955. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19956. /** Set a function to call when this mesh collides with another one */
  19957. set: function (callback) {
  19958. if (this._onCollideObserver) {
  19959. this.onCollideObservable.remove(this._onCollideObserver);
  19960. }
  19961. this._onCollideObserver = this.onCollideObservable.add(callback);
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19967. /** Set a function to call when the collision's position changes */
  19968. set: function (callback) {
  19969. if (this._onCollisionPositionChangeObserver) {
  19970. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19971. }
  19972. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19973. },
  19974. enumerable: true,
  19975. configurable: true
  19976. });
  19977. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19978. /**
  19979. * 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
  19980. * @see http://doc.babylonjs.com/features/occlusionquery
  19981. */
  19982. get: function () {
  19983. return this._isOccluded;
  19984. },
  19985. set: function (value) {
  19986. this._isOccluded = value;
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19992. /**
  19993. * Flag to check the progress status of the query
  19994. * @see http://doc.babylonjs.com/features/occlusionquery
  19995. */
  19996. get: function () {
  19997. return this._isOcclusionQueryInProgress;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20003. /**
  20004. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20005. */
  20006. get: function () {
  20007. return this._visibility;
  20008. },
  20009. /**
  20010. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20011. */
  20012. set: function (value) {
  20013. if (this._visibility === value) {
  20014. return;
  20015. }
  20016. this._visibility = value;
  20017. this._markSubMeshesAsMiscDirty();
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(AbstractMesh.prototype, "material", {
  20023. /** Gets or sets current material */
  20024. get: function () {
  20025. return this._material;
  20026. },
  20027. set: function (value) {
  20028. if (this._material === value) {
  20029. return;
  20030. }
  20031. this._material = value;
  20032. if (this.onMaterialChangedObservable.hasObservers) {
  20033. this.onMaterialChangedObservable.notifyObservers(this);
  20034. }
  20035. if (!this.subMeshes) {
  20036. return;
  20037. }
  20038. this._unBindEffect();
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20044. /**
  20045. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20046. * @see http://doc.babylonjs.com/babylon101/shadows
  20047. */
  20048. get: function () {
  20049. return this._receiveShadows;
  20050. },
  20051. set: function (value) {
  20052. if (this._receiveShadows === value) {
  20053. return;
  20054. }
  20055. this._receiveShadows = value;
  20056. this._markSubMeshesAsLightDirty();
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20062. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20063. get: function () {
  20064. return this._hasVertexAlpha;
  20065. },
  20066. set: function (value) {
  20067. if (this._hasVertexAlpha === value) {
  20068. return;
  20069. }
  20070. this._hasVertexAlpha = value;
  20071. this._markSubMeshesAsAttributesDirty();
  20072. this._markSubMeshesAsMiscDirty();
  20073. },
  20074. enumerable: true,
  20075. configurable: true
  20076. });
  20077. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20078. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20079. get: function () {
  20080. return this._useVertexColors;
  20081. },
  20082. set: function (value) {
  20083. if (this._useVertexColors === value) {
  20084. return;
  20085. }
  20086. this._useVertexColors = value;
  20087. this._markSubMeshesAsAttributesDirty();
  20088. },
  20089. enumerable: true,
  20090. configurable: true
  20091. });
  20092. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20093. /**
  20094. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20095. */
  20096. get: function () {
  20097. return this._computeBonesUsingShaders;
  20098. },
  20099. set: function (value) {
  20100. if (this._computeBonesUsingShaders === value) {
  20101. return;
  20102. }
  20103. this._computeBonesUsingShaders = value;
  20104. this._markSubMeshesAsAttributesDirty();
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20110. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20111. get: function () {
  20112. return this._numBoneInfluencers;
  20113. },
  20114. set: function (value) {
  20115. if (this._numBoneInfluencers === value) {
  20116. return;
  20117. }
  20118. this._numBoneInfluencers = value;
  20119. this._markSubMeshesAsAttributesDirty();
  20120. },
  20121. enumerable: true,
  20122. configurable: true
  20123. });
  20124. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20125. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20126. get: function () {
  20127. return this._applyFog;
  20128. },
  20129. set: function (value) {
  20130. if (this._applyFog === value) {
  20131. return;
  20132. }
  20133. this._applyFog = value;
  20134. this._markSubMeshesAsMiscDirty();
  20135. },
  20136. enumerable: true,
  20137. configurable: true
  20138. });
  20139. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20140. /**
  20141. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20142. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20143. */
  20144. get: function () {
  20145. return this._layerMask;
  20146. },
  20147. set: function (value) {
  20148. if (value === this._layerMask) {
  20149. return;
  20150. }
  20151. this._layerMask = value;
  20152. this._resyncLightSources();
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20158. /**
  20159. * Gets or sets a collision mask used to mask collisions (default is -1).
  20160. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20161. */
  20162. get: function () {
  20163. return this._collisionMask;
  20164. },
  20165. set: function (mask) {
  20166. this._collisionMask = !isNaN(mask) ? mask : -1;
  20167. },
  20168. enumerable: true,
  20169. configurable: true
  20170. });
  20171. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20172. /**
  20173. * Gets or sets the current collision group mask (-1 by default).
  20174. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20175. */
  20176. get: function () {
  20177. return this._collisionGroup;
  20178. },
  20179. set: function (mask) {
  20180. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20181. },
  20182. enumerable: true,
  20183. configurable: true
  20184. });
  20185. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20186. /** @hidden */
  20187. get: function () {
  20188. return null;
  20189. },
  20190. enumerable: true,
  20191. configurable: true
  20192. });
  20193. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20194. get: function () {
  20195. return this._skeleton;
  20196. },
  20197. /**
  20198. * Gets or sets a skeleton to apply skining transformations
  20199. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20200. */
  20201. set: function (value) {
  20202. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20203. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20204. }
  20205. if (value && value.needInitialSkinMatrix) {
  20206. value._registerMeshWithPoseMatrix(this);
  20207. }
  20208. this._skeleton = value;
  20209. if (!this._skeleton) {
  20210. this._bonesTransformMatrices = null;
  20211. }
  20212. this._markSubMeshesAsAttributesDirty();
  20213. },
  20214. enumerable: true,
  20215. configurable: true
  20216. });
  20217. /**
  20218. * Returns the string "AbstractMesh"
  20219. * @returns "AbstractMesh"
  20220. */
  20221. AbstractMesh.prototype.getClassName = function () {
  20222. return "AbstractMesh";
  20223. };
  20224. /**
  20225. * Gets a string representation of the current mesh
  20226. * @param fullDetails defines a boolean indicating if full details must be included
  20227. * @returns a string representation of the current mesh
  20228. */
  20229. AbstractMesh.prototype.toString = function (fullDetails) {
  20230. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20231. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20232. if (this._skeleton) {
  20233. ret += ", skeleton: " + this._skeleton.name;
  20234. }
  20235. if (fullDetails) {
  20236. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20237. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20238. }
  20239. return ret;
  20240. };
  20241. /** @hidden */
  20242. AbstractMesh.prototype._rebuild = function () {
  20243. this.onRebuildObservable.notifyObservers(this);
  20244. if (this._occlusionQuery) {
  20245. this._occlusionQuery = null;
  20246. }
  20247. if (!this.subMeshes) {
  20248. return;
  20249. }
  20250. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20251. var subMesh = _a[_i];
  20252. subMesh._rebuild();
  20253. }
  20254. };
  20255. /** @hidden */
  20256. AbstractMesh.prototype._resyncLightSources = function () {
  20257. this._lightSources.length = 0;
  20258. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20259. var light = _a[_i];
  20260. if (!light.isEnabled()) {
  20261. continue;
  20262. }
  20263. if (light.canAffectMesh(this)) {
  20264. this._lightSources.push(light);
  20265. }
  20266. }
  20267. this._markSubMeshesAsLightDirty();
  20268. };
  20269. /** @hidden */
  20270. AbstractMesh.prototype._resyncLighSource = function (light) {
  20271. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20272. var index = this._lightSources.indexOf(light);
  20273. if (index === -1) {
  20274. if (!isIn) {
  20275. return;
  20276. }
  20277. this._lightSources.push(light);
  20278. }
  20279. else {
  20280. if (isIn) {
  20281. return;
  20282. }
  20283. this._lightSources.splice(index, 1);
  20284. }
  20285. this._markSubMeshesAsLightDirty();
  20286. };
  20287. /** @hidden */
  20288. AbstractMesh.prototype._unBindEffect = function () {
  20289. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20290. var subMesh = _a[_i];
  20291. subMesh.setEffect(null);
  20292. }
  20293. };
  20294. /** @hidden */
  20295. AbstractMesh.prototype._removeLightSource = function (light) {
  20296. var index = this._lightSources.indexOf(light);
  20297. if (index === -1) {
  20298. return;
  20299. }
  20300. this._lightSources.splice(index, 1);
  20301. this._markSubMeshesAsLightDirty();
  20302. };
  20303. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20304. if (!this.subMeshes) {
  20305. return;
  20306. }
  20307. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20308. var subMesh = _a[_i];
  20309. if (subMesh._materialDefines) {
  20310. func(subMesh._materialDefines);
  20311. }
  20312. }
  20313. };
  20314. /** @hidden */
  20315. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20316. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20317. };
  20318. /** @hidden */
  20319. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20320. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20321. };
  20322. /** @hidden */
  20323. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20324. if (!this.subMeshes) {
  20325. return;
  20326. }
  20327. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20328. var subMesh = _a[_i];
  20329. var material = subMesh.getMaterial();
  20330. if (material) {
  20331. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20332. }
  20333. }
  20334. };
  20335. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20336. /**
  20337. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20338. */
  20339. get: function () {
  20340. return this._scaling;
  20341. },
  20342. set: function (newScaling) {
  20343. this._scaling = newScaling;
  20344. if (this.physicsImpostor) {
  20345. this.physicsImpostor.forceUpdate();
  20346. }
  20347. },
  20348. enumerable: true,
  20349. configurable: true
  20350. });
  20351. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20352. // Methods
  20353. /**
  20354. * Returns true if the mesh is blocked. Implemented by child classes
  20355. */
  20356. get: function () {
  20357. return false;
  20358. },
  20359. enumerable: true,
  20360. configurable: true
  20361. });
  20362. /**
  20363. * Returns the mesh itself by default. Implemented by child classes
  20364. * @param camera defines the camera to use to pick the right LOD level
  20365. * @returns the currentAbstractMesh
  20366. */
  20367. AbstractMesh.prototype.getLOD = function (camera) {
  20368. return this;
  20369. };
  20370. /**
  20371. * Returns 0 by default. Implemented by child classes
  20372. * @returns an integer
  20373. */
  20374. AbstractMesh.prototype.getTotalVertices = function () {
  20375. return 0;
  20376. };
  20377. /**
  20378. * Returns null by default. Implemented by child classes
  20379. * @returns null
  20380. */
  20381. AbstractMesh.prototype.getIndices = function () {
  20382. return null;
  20383. };
  20384. /**
  20385. * Returns the array of the requested vertex data kind. Implemented by child classes
  20386. * @param kind defines the vertex data kind to use
  20387. * @returns null
  20388. */
  20389. AbstractMesh.prototype.getVerticesData = function (kind) {
  20390. return null;
  20391. };
  20392. /**
  20393. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20394. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20395. * Note that a new underlying VertexBuffer object is created each call.
  20396. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20397. * @param kind defines vertex data kind:
  20398. * * BABYLON.VertexBuffer.PositionKind
  20399. * * BABYLON.VertexBuffer.UVKind
  20400. * * BABYLON.VertexBuffer.UV2Kind
  20401. * * BABYLON.VertexBuffer.UV3Kind
  20402. * * BABYLON.VertexBuffer.UV4Kind
  20403. * * BABYLON.VertexBuffer.UV5Kind
  20404. * * BABYLON.VertexBuffer.UV6Kind
  20405. * * BABYLON.VertexBuffer.ColorKind
  20406. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20407. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20408. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20409. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20410. * @param data defines the data source
  20411. * @param updatable defines if the data must be flagged as updatable (or static)
  20412. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20413. * @returns the current mesh
  20414. */
  20415. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20416. return this;
  20417. };
  20418. /**
  20419. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20420. * If the mesh has no geometry, it is simply returned as it is.
  20421. * @param kind defines vertex data kind:
  20422. * * BABYLON.VertexBuffer.PositionKind
  20423. * * BABYLON.VertexBuffer.UVKind
  20424. * * BABYLON.VertexBuffer.UV2Kind
  20425. * * BABYLON.VertexBuffer.UV3Kind
  20426. * * BABYLON.VertexBuffer.UV4Kind
  20427. * * BABYLON.VertexBuffer.UV5Kind
  20428. * * BABYLON.VertexBuffer.UV6Kind
  20429. * * BABYLON.VertexBuffer.ColorKind
  20430. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20431. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20432. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20433. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20434. * @param data defines the data source
  20435. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20436. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20437. * @returns the current mesh
  20438. */
  20439. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20440. return this;
  20441. };
  20442. /**
  20443. * Sets the mesh indices,
  20444. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20445. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20446. * @param totalVertices Defines the total number of vertices
  20447. * @returns the current mesh
  20448. */
  20449. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20450. return this;
  20451. };
  20452. /**
  20453. * Gets a boolean indicating if specific vertex data is present
  20454. * @param kind defines the vertex data kind to use
  20455. * @returns true is data kind is present
  20456. */
  20457. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20458. return false;
  20459. };
  20460. /**
  20461. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20462. * @returns a BoundingInfo
  20463. */
  20464. AbstractMesh.prototype.getBoundingInfo = function () {
  20465. if (this._masterMesh) {
  20466. return this._masterMesh.getBoundingInfo();
  20467. }
  20468. if (!this._boundingInfo) {
  20469. // this._boundingInfo is being created here
  20470. this._updateBoundingInfo();
  20471. }
  20472. // cannot be null.
  20473. return this._boundingInfo;
  20474. };
  20475. /**
  20476. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20477. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20478. * @returns the current mesh
  20479. */
  20480. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20481. if (includeDescendants === void 0) { includeDescendants = true; }
  20482. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20483. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20484. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20485. if (maxDimension === 0) {
  20486. return this;
  20487. }
  20488. var scale = 1 / maxDimension;
  20489. this.scaling.scaleInPlace(scale);
  20490. return this;
  20491. };
  20492. /**
  20493. * Overwrite the current bounding info
  20494. * @param boundingInfo defines the new bounding info
  20495. * @returns the current mesh
  20496. */
  20497. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20498. this._boundingInfo = boundingInfo;
  20499. return this;
  20500. };
  20501. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20502. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20503. get: function () {
  20504. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20505. },
  20506. enumerable: true,
  20507. configurable: true
  20508. });
  20509. /** @hidden */
  20510. AbstractMesh.prototype._preActivate = function () {
  20511. };
  20512. /** @hidden */
  20513. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20514. };
  20515. /** @hidden */
  20516. AbstractMesh.prototype._activate = function (renderId) {
  20517. this._renderId = renderId;
  20518. };
  20519. /**
  20520. * Gets the current world matrix
  20521. * @returns a Matrix
  20522. */
  20523. AbstractMesh.prototype.getWorldMatrix = function () {
  20524. if (this._masterMesh) {
  20525. return this._masterMesh.getWorldMatrix();
  20526. }
  20527. return _super.prototype.getWorldMatrix.call(this);
  20528. };
  20529. /** @hidden */
  20530. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20531. if (this._masterMesh) {
  20532. return this._masterMesh._getWorldMatrixDeterminant();
  20533. }
  20534. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20535. };
  20536. // ================================== Point of View Movement =================================
  20537. /**
  20538. * Perform relative position change from the point of view of behind the front of the mesh.
  20539. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20540. * Supports definition of mesh facing forward or backward
  20541. * @param amountRight defines the distance on the right axis
  20542. * @param amountUp defines the distance on the up axis
  20543. * @param amountForward defines the distance on the forward axis
  20544. * @returns the current mesh
  20545. */
  20546. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20547. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20548. return this;
  20549. };
  20550. /**
  20551. * Calculate relative position change from the point of view of behind the front of the mesh.
  20552. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20553. * Supports definition of mesh facing forward or backward
  20554. * @param amountRight defines the distance on the right axis
  20555. * @param amountUp defines the distance on the up axis
  20556. * @param amountForward defines the distance on the forward axis
  20557. * @returns the new displacement vector
  20558. */
  20559. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20560. var rotMatrix = new BABYLON.Matrix();
  20561. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20562. rotQuaternion.toRotationMatrix(rotMatrix);
  20563. var translationDelta = BABYLON.Vector3.Zero();
  20564. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20565. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20566. return translationDelta;
  20567. };
  20568. // ================================== Point of View Rotation =================================
  20569. /**
  20570. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20571. * Supports definition of mesh facing forward or backward
  20572. * @param flipBack defines the flip
  20573. * @param twirlClockwise defines the twirl
  20574. * @param tiltRight defines the tilt
  20575. * @returns the current mesh
  20576. */
  20577. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20578. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20579. return this;
  20580. };
  20581. /**
  20582. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20583. * Supports definition of mesh facing forward or backward.
  20584. * @param flipBack defines the flip
  20585. * @param twirlClockwise defines the twirl
  20586. * @param tiltRight defines the tilt
  20587. * @returns the new rotation vector
  20588. */
  20589. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20590. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20591. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20592. };
  20593. /**
  20594. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20595. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20596. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20597. * @returns the new bounding vectors
  20598. */
  20599. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20600. if (includeDescendants === void 0) { includeDescendants = true; }
  20601. if (predicate === void 0) { predicate = null; }
  20602. // Ensures that all world matrix will be recomputed.
  20603. this.getScene().incrementRenderId();
  20604. this.computeWorldMatrix(true);
  20605. var min;
  20606. var max;
  20607. var boundingInfo = this.getBoundingInfo();
  20608. if (!this.subMeshes) {
  20609. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20610. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20611. }
  20612. else {
  20613. min = boundingInfo.boundingBox.minimumWorld;
  20614. max = boundingInfo.boundingBox.maximumWorld;
  20615. }
  20616. if (includeDescendants) {
  20617. var descendants = this.getDescendants(false);
  20618. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20619. var descendant = descendants_1[_i];
  20620. var childMesh = descendant;
  20621. childMesh.computeWorldMatrix(true);
  20622. // Filters meshes based on custom predicate function.
  20623. if (predicate && !predicate(childMesh)) {
  20624. continue;
  20625. }
  20626. //make sure we have the needed params to get mix and max
  20627. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20628. continue;
  20629. }
  20630. var childBoundingInfo = childMesh.getBoundingInfo();
  20631. var boundingBox = childBoundingInfo.boundingBox;
  20632. var minBox = boundingBox.minimumWorld;
  20633. var maxBox = boundingBox.maximumWorld;
  20634. BABYLON.Tools.CheckExtends(minBox, min, max);
  20635. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20636. }
  20637. }
  20638. return {
  20639. min: min,
  20640. max: max
  20641. };
  20642. };
  20643. /** @hidden */
  20644. AbstractMesh.prototype._updateBoundingInfo = function () {
  20645. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20646. this._boundingInfo.update(this.worldMatrixFromCache);
  20647. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20648. return this;
  20649. };
  20650. /** @hidden */
  20651. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20652. if (!this.subMeshes) {
  20653. return this;
  20654. }
  20655. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20656. var subMesh = this.subMeshes[subIndex];
  20657. if (!subMesh.IsGlobal) {
  20658. subMesh.updateBoundingInfo(matrix);
  20659. }
  20660. }
  20661. return this;
  20662. };
  20663. /** @hidden */
  20664. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20665. // Bounding info
  20666. this._updateBoundingInfo();
  20667. };
  20668. /**
  20669. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20670. * A mesh is in the frustum if its bounding box intersects the frustum
  20671. * @param frustumPlanes defines the frustum to test
  20672. * @returns true if the mesh is in the frustum planes
  20673. */
  20674. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20675. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20676. };
  20677. /**
  20678. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20679. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20680. * @param frustumPlanes defines the frustum to test
  20681. * @returns true if the mesh is completely in the frustum planes
  20682. */
  20683. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20684. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20685. };
  20686. /**
  20687. * True if the mesh intersects another mesh or a SolidParticle object
  20688. * @param mesh defines a target mesh or SolidParticle to test
  20689. * @param precise 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)
  20690. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20691. * @returns true if there is an intersection
  20692. */
  20693. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20694. if (precise === void 0) { precise = false; }
  20695. if (!this._boundingInfo || !mesh._boundingInfo) {
  20696. return false;
  20697. }
  20698. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20699. return true;
  20700. }
  20701. if (includeDescendants) {
  20702. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20703. var child = _a[_i];
  20704. if (child.intersectsMesh(mesh, precise, true)) {
  20705. return true;
  20706. }
  20707. }
  20708. }
  20709. return false;
  20710. };
  20711. /**
  20712. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20713. * @param point defines the point to test
  20714. * @returns true if there is an intersection
  20715. */
  20716. AbstractMesh.prototype.intersectsPoint = function (point) {
  20717. if (!this._boundingInfo) {
  20718. return false;
  20719. }
  20720. return this._boundingInfo.intersectsPoint(point);
  20721. };
  20722. /**
  20723. * Gets the position of the current mesh in camera space
  20724. * @param camera defines the camera to use
  20725. * @returns a position
  20726. */
  20727. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20728. if (camera === void 0) { camera = null; }
  20729. if (!camera) {
  20730. camera = this.getScene().activeCamera;
  20731. }
  20732. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20733. };
  20734. /**
  20735. * Returns the distance from the mesh to the active camera
  20736. * @param camera defines the camera to use
  20737. * @returns the distance
  20738. */
  20739. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20740. if (camera === void 0) { camera = null; }
  20741. if (!camera) {
  20742. camera = this.getScene().activeCamera;
  20743. }
  20744. return this.absolutePosition.subtract(camera.position).length();
  20745. };
  20746. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20747. // Collisions
  20748. /**
  20749. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20750. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20751. */
  20752. get: function () {
  20753. return this._checkCollisions;
  20754. },
  20755. set: function (collisionEnabled) {
  20756. this._checkCollisions = collisionEnabled;
  20757. if (this.getScene().workerCollisions) {
  20758. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20759. }
  20760. },
  20761. enumerable: true,
  20762. configurable: true
  20763. });
  20764. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20765. /**
  20766. * Gets Collider object used to compute collisions (not physics)
  20767. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20768. */
  20769. get: function () {
  20770. return this._collider;
  20771. },
  20772. enumerable: true,
  20773. configurable: true
  20774. });
  20775. /**
  20776. * Move the mesh using collision engine
  20777. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20778. * @param displacement defines the requested displacement vector
  20779. * @returns the current mesh
  20780. */
  20781. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20782. var globalPosition = this.getAbsolutePosition();
  20783. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20784. if (!this._collider) {
  20785. this._collider = new BABYLON.Collider();
  20786. }
  20787. this._collider._radius = this.ellipsoid;
  20788. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20789. return this;
  20790. };
  20791. // Collisions
  20792. /** @hidden */
  20793. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20794. this._generatePointsArray();
  20795. if (!this._positions) {
  20796. return this;
  20797. }
  20798. // Transformation
  20799. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20800. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20801. subMesh._lastColliderWorldVertices = [];
  20802. subMesh._trianglePlanes = [];
  20803. var start = subMesh.verticesStart;
  20804. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20805. for (var i = start; i < end; i++) {
  20806. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20807. }
  20808. }
  20809. // Collide
  20810. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20811. if (collider.collisionFound) {
  20812. collider.collidedMesh = this;
  20813. }
  20814. return this;
  20815. };
  20816. /** @hidden */
  20817. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20818. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  20819. var len = subMeshes.length;
  20820. for (var index = 0; index < len; index++) {
  20821. var subMesh = subMeshes.data[index];
  20822. // Bounding test
  20823. if (len > 1 && !subMesh._checkCollision(collider))
  20824. continue;
  20825. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20826. }
  20827. return this;
  20828. };
  20829. /** @hidden */
  20830. AbstractMesh.prototype._checkCollision = function (collider) {
  20831. // Bounding box test
  20832. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20833. return this;
  20834. // Transformation matrix
  20835. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20836. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20837. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20838. return this;
  20839. };
  20840. // Picking
  20841. /** @hidden */
  20842. AbstractMesh.prototype._generatePointsArray = function () {
  20843. return false;
  20844. };
  20845. /**
  20846. * Checks if the passed Ray intersects with the mesh
  20847. * @param ray defines the ray to use
  20848. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20849. * @returns the picking info
  20850. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20851. */
  20852. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20853. var pickingInfo = new BABYLON.PickingInfo();
  20854. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20855. return pickingInfo;
  20856. }
  20857. if (!this._generatePointsArray()) {
  20858. return pickingInfo;
  20859. }
  20860. var intersectInfo = null;
  20861. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  20862. var len = subMeshes.length;
  20863. for (var index = 0; index < len; index++) {
  20864. var subMesh = subMeshes.data[index];
  20865. // Bounding test
  20866. if (len > 1 && !subMesh.canIntersects(ray))
  20867. continue;
  20868. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20869. if (currentIntersectInfo) {
  20870. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20871. intersectInfo = currentIntersectInfo;
  20872. intersectInfo.subMeshId = index;
  20873. if (fastCheck) {
  20874. break;
  20875. }
  20876. }
  20877. }
  20878. }
  20879. if (intersectInfo) {
  20880. // Get picked point
  20881. var world = this.getWorldMatrix();
  20882. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20883. var direction = ray.direction.clone();
  20884. direction = direction.scale(intersectInfo.distance);
  20885. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20886. var pickedPoint = worldOrigin.add(worldDirection);
  20887. // Return result
  20888. pickingInfo.hit = true;
  20889. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20890. pickingInfo.pickedPoint = pickedPoint;
  20891. pickingInfo.pickedMesh = this;
  20892. pickingInfo.bu = intersectInfo.bu || 0;
  20893. pickingInfo.bv = intersectInfo.bv || 0;
  20894. pickingInfo.faceId = intersectInfo.faceId;
  20895. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20896. return pickingInfo;
  20897. }
  20898. return pickingInfo;
  20899. };
  20900. /**
  20901. * Clones the current mesh
  20902. * @param name defines the mesh name
  20903. * @param newParent defines the new mesh parent
  20904. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20905. * @returns the new mesh
  20906. */
  20907. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20908. return null;
  20909. };
  20910. /**
  20911. * Disposes all the submeshes of the current meshnp
  20912. * @returns the current mesh
  20913. */
  20914. AbstractMesh.prototype.releaseSubMeshes = function () {
  20915. if (this.subMeshes) {
  20916. while (this.subMeshes.length) {
  20917. this.subMeshes[0].dispose();
  20918. }
  20919. }
  20920. else {
  20921. this.subMeshes = new Array();
  20922. }
  20923. return this;
  20924. };
  20925. /**
  20926. * Releases resources associated with this abstract mesh.
  20927. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20928. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20929. */
  20930. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20931. var _this = this;
  20932. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20933. var index;
  20934. // Smart Array Retainers.
  20935. this.getScene().freeActiveMeshes();
  20936. this.getScene().freeRenderingGroups();
  20937. // Action manager
  20938. if (this.actionManager !== undefined && this.actionManager !== null) {
  20939. this.actionManager.dispose();
  20940. this.actionManager = null;
  20941. }
  20942. // Skeleton
  20943. this._skeleton = null;
  20944. // Intersections in progress
  20945. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20946. var other = this._intersectionsInProgress[index];
  20947. var pos = other._intersectionsInProgress.indexOf(this);
  20948. other._intersectionsInProgress.splice(pos, 1);
  20949. }
  20950. this._intersectionsInProgress = [];
  20951. // Lights
  20952. var lights = this.getScene().lights;
  20953. lights.forEach(function (light) {
  20954. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20955. if (meshIndex !== -1) {
  20956. light.includedOnlyMeshes.splice(meshIndex, 1);
  20957. }
  20958. meshIndex = light.excludedMeshes.indexOf(_this);
  20959. if (meshIndex !== -1) {
  20960. light.excludedMeshes.splice(meshIndex, 1);
  20961. }
  20962. // Shadow generators
  20963. var generator = light.getShadowGenerator();
  20964. if (generator) {
  20965. var shadowMap = generator.getShadowMap();
  20966. if (shadowMap && shadowMap.renderList) {
  20967. meshIndex = shadowMap.renderList.indexOf(_this);
  20968. if (meshIndex !== -1) {
  20969. shadowMap.renderList.splice(meshIndex, 1);
  20970. }
  20971. }
  20972. }
  20973. });
  20974. // SubMeshes
  20975. if (this.getClassName() !== "InstancedMesh") {
  20976. this.releaseSubMeshes();
  20977. }
  20978. // Query
  20979. var engine = this.getScene().getEngine();
  20980. if (this._occlusionQuery) {
  20981. this._isOcclusionQueryInProgress = false;
  20982. engine.deleteQuery(this._occlusionQuery);
  20983. this._occlusionQuery = null;
  20984. }
  20985. // Engine
  20986. engine.wipeCaches();
  20987. // Remove from scene
  20988. this.getScene().removeMesh(this);
  20989. if (disposeMaterialAndTextures) {
  20990. if (this.material) {
  20991. this.material.dispose(false, true);
  20992. }
  20993. }
  20994. if (!doNotRecurse) {
  20995. // Particles
  20996. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20997. if (this.getScene().particleSystems[index].emitter === this) {
  20998. this.getScene().particleSystems[index].dispose();
  20999. index--;
  21000. }
  21001. }
  21002. }
  21003. // facet data
  21004. if (this._facetDataEnabled) {
  21005. this.disableFacetData();
  21006. }
  21007. this.onAfterWorldMatrixUpdateObservable.clear();
  21008. this.onCollideObservable.clear();
  21009. this.onCollisionPositionChangeObservable.clear();
  21010. this.onRebuildObservable.clear();
  21011. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21012. };
  21013. /**
  21014. * Adds the passed mesh as a child to the current mesh
  21015. * @param mesh defines the child mesh
  21016. * @returns the current mesh
  21017. */
  21018. AbstractMesh.prototype.addChild = function (mesh) {
  21019. mesh.setParent(this);
  21020. return this;
  21021. };
  21022. /**
  21023. * Removes the passed mesh from the current mesh children list
  21024. * @param mesh defines the child mesh
  21025. * @returns the current mesh
  21026. */
  21027. AbstractMesh.prototype.removeChild = function (mesh) {
  21028. mesh.setParent(null);
  21029. return this;
  21030. };
  21031. // Facet data
  21032. /** @hidden */
  21033. AbstractMesh.prototype._initFacetData = function () {
  21034. if (!this._facetNormals) {
  21035. this._facetNormals = new Array();
  21036. }
  21037. if (!this._facetPositions) {
  21038. this._facetPositions = new Array();
  21039. }
  21040. if (!this._facetPartitioning) {
  21041. this._facetPartitioning = new Array();
  21042. }
  21043. this._facetNb = (this.getIndices().length / 3) | 0;
  21044. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21045. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21046. for (var f = 0; f < this._facetNb; f++) {
  21047. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21048. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21049. }
  21050. this._facetDataEnabled = true;
  21051. return this;
  21052. };
  21053. /**
  21054. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21055. * This method can be called within the render loop.
  21056. * 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
  21057. * @returns the current mesh
  21058. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21059. */
  21060. AbstractMesh.prototype.updateFacetData = function () {
  21061. if (!this._facetDataEnabled) {
  21062. this._initFacetData();
  21063. }
  21064. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21065. var indices = this.getIndices();
  21066. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21067. var bInfo = this.getBoundingInfo();
  21068. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21069. // init arrays, matrix and sort function on first call
  21070. this._facetDepthSortEnabled = true;
  21071. if (indices instanceof Uint16Array) {
  21072. this._depthSortedIndices = new Uint16Array(indices);
  21073. }
  21074. else if (indices instanceof Uint32Array) {
  21075. this._depthSortedIndices = new Uint32Array(indices);
  21076. }
  21077. else {
  21078. var needs32bits = false;
  21079. for (var i = 0; i < indices.length; i++) {
  21080. if (indices[i] > 65535) {
  21081. needs32bits = true;
  21082. break;
  21083. }
  21084. }
  21085. if (needs32bits) {
  21086. this._depthSortedIndices = new Uint32Array(indices);
  21087. }
  21088. else {
  21089. this._depthSortedIndices = new Uint16Array(indices);
  21090. }
  21091. }
  21092. this._facetDepthSortFunction = function (f1, f2) {
  21093. return (f2.sqDistance - f1.sqDistance);
  21094. };
  21095. if (!this._facetDepthSortFrom) {
  21096. var camera = this.getScene().activeCamera;
  21097. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21098. }
  21099. this._depthSortedFacets = [];
  21100. for (var f = 0; f < this._facetNb; f++) {
  21101. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21102. this._depthSortedFacets.push(depthSortedFacet);
  21103. }
  21104. this._invertedMatrix = BABYLON.Matrix.Identity();
  21105. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21106. }
  21107. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21108. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21109. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21110. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21111. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21112. this._subDiv.max = this._partitioningSubdivisions;
  21113. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21114. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21115. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21116. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21117. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21118. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21119. // set the parameters for ComputeNormals()
  21120. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21121. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21122. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21123. this._facetParameters.bInfo = bInfo;
  21124. this._facetParameters.bbSize = this._bbSize;
  21125. this._facetParameters.subDiv = this._subDiv;
  21126. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21127. this._facetParameters.depthSort = this._facetDepthSort;
  21128. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21129. this.computeWorldMatrix(true);
  21130. this._worldMatrix.invertToRef(this._invertedMatrix);
  21131. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21132. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21133. }
  21134. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21135. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21136. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21137. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21138. var l = (this._depthSortedIndices.length / 3) | 0;
  21139. for (var f = 0; f < l; f++) {
  21140. var sind = this._depthSortedFacets[f].ind;
  21141. this._depthSortedIndices[f * 3] = indices[sind];
  21142. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21143. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21144. }
  21145. this.updateIndices(this._depthSortedIndices);
  21146. }
  21147. return this;
  21148. };
  21149. /**
  21150. * Returns the facetLocalNormals array.
  21151. * The normals are expressed in the mesh local spac
  21152. * @returns an array of Vector3
  21153. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21154. */
  21155. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21156. if (!this._facetNormals) {
  21157. this.updateFacetData();
  21158. }
  21159. return this._facetNormals;
  21160. };
  21161. /**
  21162. * Returns the facetLocalPositions array.
  21163. * The facet positions are expressed in the mesh local space
  21164. * @returns an array of Vector3
  21165. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21166. */
  21167. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21168. if (!this._facetPositions) {
  21169. this.updateFacetData();
  21170. }
  21171. return this._facetPositions;
  21172. };
  21173. /**
  21174. * Returns the facetLocalPartioning array
  21175. * @returns an array of array of numbers
  21176. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21177. */
  21178. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21179. if (!this._facetPartitioning) {
  21180. this.updateFacetData();
  21181. }
  21182. return this._facetPartitioning;
  21183. };
  21184. /**
  21185. * Returns the i-th facet position in the world system.
  21186. * This method allocates a new Vector3 per call
  21187. * @param i defines the facet index
  21188. * @returns a new Vector3
  21189. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21190. */
  21191. AbstractMesh.prototype.getFacetPosition = function (i) {
  21192. var pos = BABYLON.Vector3.Zero();
  21193. this.getFacetPositionToRef(i, pos);
  21194. return pos;
  21195. };
  21196. /**
  21197. * Sets the reference Vector3 with the i-th facet position in the world system
  21198. * @param i defines the facet index
  21199. * @param ref defines the target vector
  21200. * @returns the current mesh
  21201. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21202. */
  21203. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21204. var localPos = (this.getFacetLocalPositions())[i];
  21205. var world = this.getWorldMatrix();
  21206. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21207. return this;
  21208. };
  21209. /**
  21210. * Returns the i-th facet normal in the world system.
  21211. * This method allocates a new Vector3 per call
  21212. * @param i defines the facet index
  21213. * @returns a new Vector3
  21214. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21215. */
  21216. AbstractMesh.prototype.getFacetNormal = function (i) {
  21217. var norm = BABYLON.Vector3.Zero();
  21218. this.getFacetNormalToRef(i, norm);
  21219. return norm;
  21220. };
  21221. /**
  21222. * Sets the reference Vector3 with the i-th facet normal in the world system
  21223. * @param i defines the facet index
  21224. * @param ref defines the target vector
  21225. * @returns the current mesh
  21226. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21227. */
  21228. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21229. var localNorm = (this.getFacetLocalNormals())[i];
  21230. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21231. return this;
  21232. };
  21233. /**
  21234. * 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)
  21235. * @param x defines x coordinate
  21236. * @param y defines y coordinate
  21237. * @param z defines z coordinate
  21238. * @returns the array of facet indexes
  21239. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21240. */
  21241. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21242. var bInfo = this.getBoundingInfo();
  21243. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21244. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21245. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21246. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21247. return null;
  21248. }
  21249. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21250. };
  21251. /**
  21252. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21253. * @param projected sets as the (x,y,z) world projection on the facet
  21254. * @param checkFace if 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
  21255. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21256. * @param x defines x coordinate
  21257. * @param y defines y coordinate
  21258. * @param z defines z coordinate
  21259. * @returns the face index if found (or null instead)
  21260. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21261. */
  21262. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21263. if (checkFace === void 0) { checkFace = false; }
  21264. if (facing === void 0) { facing = true; }
  21265. var world = this.getWorldMatrix();
  21266. var invMat = BABYLON.Tmp.Matrix[5];
  21267. world.invertToRef(invMat);
  21268. var invVect = BABYLON.Tmp.Vector3[8];
  21269. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21270. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21271. if (projected) {
  21272. // tranform the local computed projected vector to world coordinates
  21273. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21274. }
  21275. return closest;
  21276. };
  21277. /**
  21278. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21279. * @param projected sets as the (x,y,z) local projection on the facet
  21280. * @param checkFace if 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
  21281. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. 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
  21282. * @param x defines x coordinate
  21283. * @param y defines y coordinate
  21284. * @param z defines z coordinate
  21285. * @returns the face index if found (or null instead)
  21286. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21287. */
  21288. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21289. if (checkFace === void 0) { checkFace = false; }
  21290. if (facing === void 0) { facing = true; }
  21291. var closest = null;
  21292. var tmpx = 0.0;
  21293. var tmpy = 0.0;
  21294. var tmpz = 0.0;
  21295. var d = 0.0; // tmp dot facet normal * facet position
  21296. var t0 = 0.0;
  21297. var projx = 0.0;
  21298. var projy = 0.0;
  21299. var projz = 0.0;
  21300. // Get all the facets in the same partitioning block than (x, y, z)
  21301. var facetPositions = this.getFacetLocalPositions();
  21302. var facetNormals = this.getFacetLocalNormals();
  21303. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21304. if (!facetsInBlock) {
  21305. return null;
  21306. }
  21307. // Get the closest facet to (x, y, z)
  21308. var shortest = Number.MAX_VALUE; // init distance vars
  21309. var tmpDistance = shortest;
  21310. var fib; // current facet in the block
  21311. var norm; // current facet normal
  21312. var p0; // current facet barycenter position
  21313. // loop on all the facets in the current partitioning block
  21314. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21315. fib = facetsInBlock[idx];
  21316. norm = facetNormals[fib];
  21317. p0 = facetPositions[fib];
  21318. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21319. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21320. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21321. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21322. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21323. projx = x + norm.x * t0;
  21324. projy = y + norm.y * t0;
  21325. projz = z + norm.z * t0;
  21326. tmpx = projx - x;
  21327. tmpy = projy - y;
  21328. tmpz = projz - z;
  21329. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21330. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21331. shortest = tmpDistance;
  21332. closest = fib;
  21333. if (projected) {
  21334. projected.x = projx;
  21335. projected.y = projy;
  21336. projected.z = projz;
  21337. }
  21338. }
  21339. }
  21340. }
  21341. return closest;
  21342. };
  21343. /**
  21344. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21345. * @returns the parameters
  21346. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21347. */
  21348. AbstractMesh.prototype.getFacetDataParameters = function () {
  21349. return this._facetParameters;
  21350. };
  21351. /**
  21352. * Disables the feature FacetData and frees the related memory
  21353. * @returns the current mesh
  21354. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21355. */
  21356. AbstractMesh.prototype.disableFacetData = function () {
  21357. if (this._facetDataEnabled) {
  21358. this._facetDataEnabled = false;
  21359. this._facetPositions = new Array();
  21360. this._facetNormals = new Array();
  21361. this._facetPartitioning = new Array();
  21362. this._facetParameters = null;
  21363. this._depthSortedIndices = new Uint32Array(0);
  21364. }
  21365. return this;
  21366. };
  21367. /**
  21368. * Updates the AbstractMesh indices array
  21369. * @param indices defines the data source
  21370. * @returns the current mesh
  21371. */
  21372. AbstractMesh.prototype.updateIndices = function (indices) {
  21373. return this;
  21374. };
  21375. /**
  21376. * Creates new normals data for the mesh
  21377. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21378. * @returns the current mesh
  21379. */
  21380. AbstractMesh.prototype.createNormals = function (updatable) {
  21381. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21382. var indices = this.getIndices();
  21383. var normals;
  21384. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21385. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21386. }
  21387. else {
  21388. normals = [];
  21389. }
  21390. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21391. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21392. return this;
  21393. };
  21394. /**
  21395. * Align the mesh with a normal
  21396. * @param normal defines the normal to use
  21397. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21398. * @returns the current mesh
  21399. */
  21400. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21401. if (!upDirection) {
  21402. upDirection = BABYLON.Axis.Y;
  21403. }
  21404. var axisX = BABYLON.Tmp.Vector3[0];
  21405. var axisZ = BABYLON.Tmp.Vector3[1];
  21406. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21407. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21408. if (this.rotationQuaternion) {
  21409. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21410. }
  21411. else {
  21412. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21413. }
  21414. return this;
  21415. };
  21416. /** @hidden */
  21417. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21418. this._isOccluded = false;
  21419. };
  21420. /** No occlusion */
  21421. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21422. /** Occlusion set to optimisitic */
  21423. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21424. /** Occlusion set to strict */
  21425. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21426. /** Use an accurante occlusion algorithm */
  21427. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21428. /** Use a conservative occlusion algorithm */
  21429. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21430. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21431. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21432. /** Culling strategy with bounding sphere only and then frustum culling */
  21433. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21434. return AbstractMesh;
  21435. }(BABYLON.TransformNode));
  21436. BABYLON.AbstractMesh = AbstractMesh;
  21437. })(BABYLON || (BABYLON = {}));
  21438. //# sourceMappingURL=babylon.abstractMesh.js.map
  21439. var BABYLON;
  21440. (function (BABYLON) {
  21441. /**
  21442. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21443. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21444. * 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.
  21445. */
  21446. var Light = /** @class */ (function (_super) {
  21447. __extends(Light, _super);
  21448. /**
  21449. * Creates a Light object in the scene.
  21450. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21451. * @param name The firendly name of the light
  21452. * @param scene The scene the light belongs too
  21453. */
  21454. function Light(name, scene) {
  21455. var _this = _super.call(this, name, scene) || this;
  21456. /**
  21457. * Diffuse gives the basic color to an object.
  21458. */
  21459. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21460. /**
  21461. * Specular produces a highlight color on an object.
  21462. * Note: This is note affecting PBR materials.
  21463. */
  21464. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21465. /**
  21466. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21467. * falling off base on range or angle.
  21468. * This can be set to any values in Light.FALLOFF_x.
  21469. *
  21470. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21471. * other types of materials.
  21472. */
  21473. _this.falloffType = Light.FALLOFF_DEFAULT;
  21474. /**
  21475. * Strength of the light.
  21476. * Note: By default it is define in the framework own unit.
  21477. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21478. */
  21479. _this.intensity = 1.0;
  21480. _this._range = Number.MAX_VALUE;
  21481. _this._inverseSquaredRange = 0;
  21482. /**
  21483. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21484. * of light.
  21485. */
  21486. _this._photometricScale = 1.0;
  21487. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21488. _this._radius = 0.00001;
  21489. /**
  21490. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21491. * exceeding the number allowed of the materials.
  21492. */
  21493. _this.renderPriority = 0;
  21494. _this._shadowEnabled = true;
  21495. _this._excludeWithLayerMask = 0;
  21496. _this._includeOnlyWithLayerMask = 0;
  21497. _this._lightmapMode = 0;
  21498. /**
  21499. * @hidden Internal use only.
  21500. */
  21501. _this._excludedMeshesIds = new Array();
  21502. /**
  21503. * @hidden Internal use only.
  21504. */
  21505. _this._includedOnlyMeshesIds = new Array();
  21506. _this.getScene().addLight(_this);
  21507. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21508. _this._buildUniformLayout();
  21509. _this.includedOnlyMeshes = new Array();
  21510. _this.excludedMeshes = new Array();
  21511. _this._resyncMeshes();
  21512. return _this;
  21513. }
  21514. Object.defineProperty(Light.prototype, "range", {
  21515. /**
  21516. * Defines how far from the source the light is impacting in scene units.
  21517. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21518. */
  21519. get: function () {
  21520. return this._range;
  21521. },
  21522. /**
  21523. * Defines how far from the source the light is impacting in scene units.
  21524. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21525. */
  21526. set: function (value) {
  21527. this._range = value;
  21528. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21529. },
  21530. enumerable: true,
  21531. configurable: true
  21532. });
  21533. Object.defineProperty(Light.prototype, "intensityMode", {
  21534. /**
  21535. * Gets the photometric scale used to interpret the intensity.
  21536. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21537. */
  21538. get: function () {
  21539. return this._intensityMode;
  21540. },
  21541. /**
  21542. * Sets the photometric scale used to interpret the intensity.
  21543. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21544. */
  21545. set: function (value) {
  21546. this._intensityMode = value;
  21547. this._computePhotometricScale();
  21548. },
  21549. enumerable: true,
  21550. configurable: true
  21551. });
  21552. ;
  21553. ;
  21554. Object.defineProperty(Light.prototype, "radius", {
  21555. /**
  21556. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21557. */
  21558. get: function () {
  21559. return this._radius;
  21560. },
  21561. /**
  21562. * sets the light radius used by PBR Materials to simulate soft area lights.
  21563. */
  21564. set: function (value) {
  21565. this._radius = value;
  21566. this._computePhotometricScale();
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. ;
  21572. ;
  21573. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21574. /**
  21575. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21576. * the current shadow generator.
  21577. */
  21578. get: function () {
  21579. return this._shadowEnabled;
  21580. },
  21581. /**
  21582. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21583. * the current shadow generator.
  21584. */
  21585. set: function (value) {
  21586. if (this._shadowEnabled === value) {
  21587. return;
  21588. }
  21589. this._shadowEnabled = value;
  21590. this._markMeshesAsLightDirty();
  21591. },
  21592. enumerable: true,
  21593. configurable: true
  21594. });
  21595. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21596. /**
  21597. * Gets the only meshes impacted by this light.
  21598. */
  21599. get: function () {
  21600. return this._includedOnlyMeshes;
  21601. },
  21602. /**
  21603. * Sets the only meshes impacted by this light.
  21604. */
  21605. set: function (value) {
  21606. this._includedOnlyMeshes = value;
  21607. this._hookArrayForIncludedOnly(value);
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21613. /**
  21614. * Gets the meshes not impacted by this light.
  21615. */
  21616. get: function () {
  21617. return this._excludedMeshes;
  21618. },
  21619. /**
  21620. * Sets the meshes not impacted by this light.
  21621. */
  21622. set: function (value) {
  21623. this._excludedMeshes = value;
  21624. this._hookArrayForExcluded(value);
  21625. },
  21626. enumerable: true,
  21627. configurable: true
  21628. });
  21629. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21630. /**
  21631. * Gets the layer id use to find what meshes are not impacted by the light.
  21632. * Inactive if 0
  21633. */
  21634. get: function () {
  21635. return this._excludeWithLayerMask;
  21636. },
  21637. /**
  21638. * Sets the layer id use to find what meshes are not impacted by the light.
  21639. * Inactive if 0
  21640. */
  21641. set: function (value) {
  21642. this._excludeWithLayerMask = value;
  21643. this._resyncMeshes();
  21644. },
  21645. enumerable: true,
  21646. configurable: true
  21647. });
  21648. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21649. /**
  21650. * Gets the layer id use to find what meshes are impacted by the light.
  21651. * Inactive if 0
  21652. */
  21653. get: function () {
  21654. return this._includeOnlyWithLayerMask;
  21655. },
  21656. /**
  21657. * Sets the layer id use to find what meshes are impacted by the light.
  21658. * Inactive if 0
  21659. */
  21660. set: function (value) {
  21661. this._includeOnlyWithLayerMask = value;
  21662. this._resyncMeshes();
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Object.defineProperty(Light.prototype, "lightmapMode", {
  21668. /**
  21669. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21670. */
  21671. get: function () {
  21672. return this._lightmapMode;
  21673. },
  21674. /**
  21675. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21676. */
  21677. set: function (value) {
  21678. if (this._lightmapMode === value) {
  21679. return;
  21680. }
  21681. this._lightmapMode = value;
  21682. this._markMeshesAsLightDirty();
  21683. },
  21684. enumerable: true,
  21685. configurable: true
  21686. });
  21687. /**
  21688. * Returns the string "Light".
  21689. * @returns the class name
  21690. */
  21691. Light.prototype.getClassName = function () {
  21692. return "Light";
  21693. };
  21694. /**
  21695. * Converts the light information to a readable string for debug purpose.
  21696. * @param fullDetails Supports for multiple levels of logging within scene loading
  21697. * @returns the human readable light info
  21698. */
  21699. Light.prototype.toString = function (fullDetails) {
  21700. var ret = "Name: " + this.name;
  21701. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21702. if (this.animations) {
  21703. for (var i = 0; i < this.animations.length; i++) {
  21704. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21705. }
  21706. }
  21707. if (fullDetails) {
  21708. }
  21709. return ret;
  21710. };
  21711. /** @hidden */
  21712. Light.prototype._syncParentEnabledState = function () {
  21713. _super.prototype._syncParentEnabledState.call(this);
  21714. this._resyncMeshes();
  21715. };
  21716. /**
  21717. * Set the enabled state of this node.
  21718. * @param value - the new enabled state
  21719. */
  21720. Light.prototype.setEnabled = function (value) {
  21721. _super.prototype.setEnabled.call(this, value);
  21722. this._resyncMeshes();
  21723. };
  21724. /**
  21725. * Returns the Light associated shadow generator if any.
  21726. * @return the associated shadow generator.
  21727. */
  21728. Light.prototype.getShadowGenerator = function () {
  21729. return this._shadowGenerator;
  21730. };
  21731. /**
  21732. * Returns a Vector3, the absolute light position in the World.
  21733. * @returns the world space position of the light
  21734. */
  21735. Light.prototype.getAbsolutePosition = function () {
  21736. return BABYLON.Vector3.Zero();
  21737. };
  21738. /**
  21739. * Specifies if the light will affect the passed mesh.
  21740. * @param mesh The mesh to test against the light
  21741. * @return true the mesh is affected otherwise, false.
  21742. */
  21743. Light.prototype.canAffectMesh = function (mesh) {
  21744. if (!mesh) {
  21745. return true;
  21746. }
  21747. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21748. return false;
  21749. }
  21750. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21751. return false;
  21752. }
  21753. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21754. return false;
  21755. }
  21756. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21757. return false;
  21758. }
  21759. return true;
  21760. };
  21761. /**
  21762. * Sort function to order lights for rendering.
  21763. * @param a First Light object to compare to second.
  21764. * @param b Second Light object to compare first.
  21765. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21766. */
  21767. Light.CompareLightsPriority = function (a, b) {
  21768. //shadow-casting lights have priority over non-shadow-casting lights
  21769. //the renderPrioirty is a secondary sort criterion
  21770. if (a.shadowEnabled !== b.shadowEnabled) {
  21771. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21772. }
  21773. return b.renderPriority - a.renderPriority;
  21774. };
  21775. /**
  21776. * Releases resources associated with this node.
  21777. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21778. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21779. */
  21780. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21781. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21782. if (this._shadowGenerator) {
  21783. this._shadowGenerator.dispose();
  21784. this._shadowGenerator = null;
  21785. }
  21786. // Animations
  21787. this.getScene().stopAnimation(this);
  21788. // Remove from meshes
  21789. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21790. var mesh = _a[_i];
  21791. mesh._removeLightSource(this);
  21792. }
  21793. this._uniformBuffer.dispose();
  21794. // Remove from scene
  21795. this.getScene().removeLight(this);
  21796. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21797. };
  21798. /**
  21799. * Returns the light type ID (integer).
  21800. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21801. */
  21802. Light.prototype.getTypeID = function () {
  21803. return 0;
  21804. };
  21805. /**
  21806. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21807. * @returns the scaled intensity in intensity mode unit
  21808. */
  21809. Light.prototype.getScaledIntensity = function () {
  21810. return this._photometricScale * this.intensity;
  21811. };
  21812. /**
  21813. * Returns a new Light object, named "name", from the current one.
  21814. * @param name The name of the cloned light
  21815. * @returns the new created light
  21816. */
  21817. Light.prototype.clone = function (name) {
  21818. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21819. if (!constructor) {
  21820. return null;
  21821. }
  21822. return BABYLON.SerializationHelper.Clone(constructor, this);
  21823. };
  21824. /**
  21825. * Serializes the current light into a Serialization object.
  21826. * @returns the serialized object.
  21827. */
  21828. Light.prototype.serialize = function () {
  21829. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21830. // Type
  21831. serializationObject.type = this.getTypeID();
  21832. // Parent
  21833. if (this.parent) {
  21834. serializationObject.parentId = this.parent.id;
  21835. }
  21836. // Inclusion / exclusions
  21837. if (this.excludedMeshes.length > 0) {
  21838. serializationObject.excludedMeshesIds = [];
  21839. this.excludedMeshes.forEach(function (mesh) {
  21840. serializationObject.excludedMeshesIds.push(mesh.id);
  21841. });
  21842. }
  21843. if (this.includedOnlyMeshes.length > 0) {
  21844. serializationObject.includedOnlyMeshesIds = [];
  21845. this.includedOnlyMeshes.forEach(function (mesh) {
  21846. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21847. });
  21848. }
  21849. // Animations
  21850. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21851. serializationObject.ranges = this.serializeAnimationRanges();
  21852. return serializationObject;
  21853. };
  21854. /**
  21855. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21856. * This new light is named "name" and added to the passed scene.
  21857. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21858. * @param name The friendly name of the light
  21859. * @param scene The scene the new light will belong to
  21860. * @returns the constructor function
  21861. */
  21862. Light.GetConstructorFromName = function (type, name, scene) {
  21863. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21864. if (constructorFunc) {
  21865. return constructorFunc;
  21866. }
  21867. // Default to no light for none present once.
  21868. return null;
  21869. };
  21870. /**
  21871. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21872. * @param parsedLight The JSON representation of the light
  21873. * @param scene The scene to create the parsed light in
  21874. * @returns the created light after parsing
  21875. */
  21876. Light.Parse = function (parsedLight, scene) {
  21877. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21878. if (!constructor) {
  21879. return null;
  21880. }
  21881. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21882. // Inclusion / exclusions
  21883. if (parsedLight.excludedMeshesIds) {
  21884. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21885. }
  21886. if (parsedLight.includedOnlyMeshesIds) {
  21887. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21888. }
  21889. // Parent
  21890. if (parsedLight.parentId) {
  21891. light._waitingParentId = parsedLight.parentId;
  21892. }
  21893. // Animations
  21894. if (parsedLight.animations) {
  21895. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21896. var parsedAnimation = parsedLight.animations[animationIndex];
  21897. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21898. }
  21899. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21900. }
  21901. if (parsedLight.autoAnimate) {
  21902. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21903. }
  21904. return light;
  21905. };
  21906. Light.prototype._hookArrayForExcluded = function (array) {
  21907. var _this = this;
  21908. var oldPush = array.push;
  21909. array.push = function () {
  21910. var items = [];
  21911. for (var _i = 0; _i < arguments.length; _i++) {
  21912. items[_i] = arguments[_i];
  21913. }
  21914. var result = oldPush.apply(array, items);
  21915. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21916. var item = items_1[_a];
  21917. item._resyncLighSource(_this);
  21918. }
  21919. return result;
  21920. };
  21921. var oldSplice = array.splice;
  21922. array.splice = function (index, deleteCount) {
  21923. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21924. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21925. var item = deleted_1[_i];
  21926. item._resyncLighSource(_this);
  21927. }
  21928. return deleted;
  21929. };
  21930. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21931. var item = array_1[_i];
  21932. item._resyncLighSource(this);
  21933. }
  21934. };
  21935. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21936. var _this = this;
  21937. var oldPush = array.push;
  21938. array.push = function () {
  21939. var items = [];
  21940. for (var _i = 0; _i < arguments.length; _i++) {
  21941. items[_i] = arguments[_i];
  21942. }
  21943. var result = oldPush.apply(array, items);
  21944. _this._resyncMeshes();
  21945. return result;
  21946. };
  21947. var oldSplice = array.splice;
  21948. array.splice = function (index, deleteCount) {
  21949. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21950. _this._resyncMeshes();
  21951. return deleted;
  21952. };
  21953. this._resyncMeshes();
  21954. };
  21955. Light.prototype._resyncMeshes = function () {
  21956. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21957. var mesh = _a[_i];
  21958. mesh._resyncLighSource(this);
  21959. }
  21960. };
  21961. /**
  21962. * Forces the meshes to update their light related information in their rendering used effects
  21963. * @hidden Internal Use Only
  21964. */
  21965. Light.prototype._markMeshesAsLightDirty = function () {
  21966. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21967. var mesh = _a[_i];
  21968. if (mesh._lightSources.indexOf(this) !== -1) {
  21969. mesh._markSubMeshesAsLightDirty();
  21970. }
  21971. }
  21972. };
  21973. /**
  21974. * Recomputes the cached photometric scale if needed.
  21975. */
  21976. Light.prototype._computePhotometricScale = function () {
  21977. this._photometricScale = this._getPhotometricScale();
  21978. this.getScene().resetCachedMaterial();
  21979. };
  21980. /**
  21981. * Returns the Photometric Scale according to the light type and intensity mode.
  21982. */
  21983. Light.prototype._getPhotometricScale = function () {
  21984. var photometricScale = 0.0;
  21985. var lightTypeID = this.getTypeID();
  21986. //get photometric mode
  21987. var photometricMode = this.intensityMode;
  21988. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21989. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21990. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21991. }
  21992. else {
  21993. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21994. }
  21995. }
  21996. //compute photometric scale
  21997. switch (lightTypeID) {
  21998. case Light.LIGHTTYPEID_POINTLIGHT:
  21999. case Light.LIGHTTYPEID_SPOTLIGHT:
  22000. switch (photometricMode) {
  22001. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22002. photometricScale = 1.0 / (4.0 * Math.PI);
  22003. break;
  22004. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22005. photometricScale = 1.0;
  22006. break;
  22007. case Light.INTENSITYMODE_LUMINANCE:
  22008. photometricScale = this.radius * this.radius;
  22009. break;
  22010. }
  22011. break;
  22012. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22013. switch (photometricMode) {
  22014. case Light.INTENSITYMODE_ILLUMINANCE:
  22015. photometricScale = 1.0;
  22016. break;
  22017. case Light.INTENSITYMODE_LUMINANCE:
  22018. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22019. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22020. var apexAngleRadians = this.radius;
  22021. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22022. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22023. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22024. photometricScale = solidAngle;
  22025. break;
  22026. }
  22027. break;
  22028. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22029. // No fall off in hemisperic light.
  22030. photometricScale = 1.0;
  22031. break;
  22032. }
  22033. return photometricScale;
  22034. };
  22035. /**
  22036. * Reorder the light in the scene according to their defined priority.
  22037. * @hidden Internal Use Only
  22038. */
  22039. Light.prototype._reorderLightsInScene = function () {
  22040. var scene = this.getScene();
  22041. if (this._renderPriority != 0) {
  22042. scene.requireLightSorting = true;
  22043. }
  22044. this.getScene().sortLightsByPriority();
  22045. };
  22046. /**
  22047. * Falloff Default: light is falling off following the material specification:
  22048. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22049. */
  22050. Light.FALLOFF_DEFAULT = 0;
  22051. /**
  22052. * Falloff Physical: light is falling off following the inverse squared distance law.
  22053. */
  22054. Light.FALLOFF_PHYSICAL = 1;
  22055. /**
  22056. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22057. * to enhance interoperability with other engines.
  22058. */
  22059. Light.FALLOFF_GLTF = 2;
  22060. /**
  22061. * Falloff Standard: light is falling off like in the standard material
  22062. * to enhance interoperability with other materials.
  22063. */
  22064. Light.FALLOFF_STANDARD = 3;
  22065. //lightmapMode Consts
  22066. /**
  22067. * If every light affecting the material is in this lightmapMode,
  22068. * material.lightmapTexture adds or multiplies
  22069. * (depends on material.useLightmapAsShadowmap)
  22070. * after every other light calculations.
  22071. */
  22072. Light.LIGHTMAP_DEFAULT = 0;
  22073. /**
  22074. * material.lightmapTexture as only diffuse lighting from this light
  22075. * adds only specular lighting from this light
  22076. * adds dynamic shadows
  22077. */
  22078. Light.LIGHTMAP_SPECULAR = 1;
  22079. /**
  22080. * material.lightmapTexture as only lighting
  22081. * no light calculation from this light
  22082. * only adds dynamic shadows from this light
  22083. */
  22084. Light.LIGHTMAP_SHADOWSONLY = 2;
  22085. // Intensity Mode Consts
  22086. /**
  22087. * Each light type uses the default quantity according to its type:
  22088. * point/spot lights use luminous intensity
  22089. * directional lights use illuminance
  22090. */
  22091. Light.INTENSITYMODE_AUTOMATIC = 0;
  22092. /**
  22093. * lumen (lm)
  22094. */
  22095. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22096. /**
  22097. * candela (lm/sr)
  22098. */
  22099. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22100. /**
  22101. * lux (lm/m^2)
  22102. */
  22103. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22104. /**
  22105. * nit (cd/m^2)
  22106. */
  22107. Light.INTENSITYMODE_LUMINANCE = 4;
  22108. // Light types ids const.
  22109. /**
  22110. * Light type const id of the point light.
  22111. */
  22112. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22113. /**
  22114. * Light type const id of the directional light.
  22115. */
  22116. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22117. /**
  22118. * Light type const id of the spot light.
  22119. */
  22120. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22121. /**
  22122. * Light type const id of the hemispheric light.
  22123. */
  22124. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22125. __decorate([
  22126. BABYLON.serializeAsColor3()
  22127. ], Light.prototype, "diffuse", void 0);
  22128. __decorate([
  22129. BABYLON.serializeAsColor3()
  22130. ], Light.prototype, "specular", void 0);
  22131. __decorate([
  22132. BABYLON.serialize()
  22133. ], Light.prototype, "falloffType", void 0);
  22134. __decorate([
  22135. BABYLON.serialize()
  22136. ], Light.prototype, "intensity", void 0);
  22137. __decorate([
  22138. BABYLON.serialize()
  22139. ], Light.prototype, "range", null);
  22140. __decorate([
  22141. BABYLON.serialize()
  22142. ], Light.prototype, "intensityMode", null);
  22143. __decorate([
  22144. BABYLON.serialize()
  22145. ], Light.prototype, "radius", null);
  22146. __decorate([
  22147. BABYLON.serialize()
  22148. ], Light.prototype, "_renderPriority", void 0);
  22149. __decorate([
  22150. BABYLON.expandToProperty("_reorderLightsInScene")
  22151. ], Light.prototype, "renderPriority", void 0);
  22152. __decorate([
  22153. BABYLON.serialize("shadowEnabled")
  22154. ], Light.prototype, "_shadowEnabled", void 0);
  22155. __decorate([
  22156. BABYLON.serialize("excludeWithLayerMask")
  22157. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22158. __decorate([
  22159. BABYLON.serialize("includeOnlyWithLayerMask")
  22160. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22161. __decorate([
  22162. BABYLON.serialize("lightmapMode")
  22163. ], Light.prototype, "_lightmapMode", void 0);
  22164. return Light;
  22165. }(BABYLON.Node));
  22166. BABYLON.Light = Light;
  22167. })(BABYLON || (BABYLON = {}));
  22168. //# sourceMappingURL=babylon.light.js.map
  22169. var BABYLON;
  22170. (function (BABYLON) {
  22171. /**
  22172. * This is the base class of all the camera used in the application.
  22173. * @see http://doc.babylonjs.com/features/cameras
  22174. */
  22175. var Camera = /** @class */ (function (_super) {
  22176. __extends(Camera, _super);
  22177. /**
  22178. * Instantiates a new camera object.
  22179. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  22180. * @see http://doc.babylonjs.com/features/cameras
  22181. * @param name Defines the name of the camera in the scene
  22182. * @param position Defines the position of the camera
  22183. * @param scene Defines the scene the camera belongs too
  22184. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  22185. */
  22186. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22187. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22188. var _this = _super.call(this, name, scene) || this;
  22189. /**
  22190. * The vector the camera should consider as up.
  22191. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22192. */
  22193. _this.upVector = BABYLON.Vector3.Up();
  22194. /**
  22195. * Define the current limit on the left side for an orthographic camera
  22196. * In scene unit
  22197. */
  22198. _this.orthoLeft = null;
  22199. /**
  22200. * Define the current limit on the right side for an orthographic camera
  22201. * In scene unit
  22202. */
  22203. _this.orthoRight = null;
  22204. /**
  22205. * Define the current limit on the bottom side for an orthographic camera
  22206. * In scene unit
  22207. */
  22208. _this.orthoBottom = null;
  22209. /**
  22210. * Define the current limit on the top side for an orthographic camera
  22211. * In scene unit
  22212. */
  22213. _this.orthoTop = null;
  22214. /**
  22215. * Field Of View is set in Radians. (default is 0.8)
  22216. */
  22217. _this.fov = 0.8;
  22218. /**
  22219. * Define the minimum distance the camera can see from.
  22220. * This is important to note that the depth buffer are not infinite and the closer it starts
  22221. * the more your scene might encounter depth fighting issue.
  22222. */
  22223. _this.minZ = 1;
  22224. /**
  22225. * Define the maximum distance the camera can see to.
  22226. * This is important to note that the depth buffer are not infinite and the further it end
  22227. * the more your scene might encounter depth fighting issue.
  22228. */
  22229. _this.maxZ = 10000.0;
  22230. /**
  22231. * Define the default inertia of the camera.
  22232. * This helps giving a smooth feeling to the camera movement.
  22233. */
  22234. _this.inertia = 0.9;
  22235. /**
  22236. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  22237. */
  22238. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22239. /**
  22240. * Define wether the camera is intermediate.
  22241. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  22242. */
  22243. _this.isIntermediate = false;
  22244. /**
  22245. * Define the viewport of the camera.
  22246. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  22247. */
  22248. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22249. /**
  22250. * Restricts the camera to viewing objects with the same layerMask.
  22251. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22252. */
  22253. _this.layerMask = 0x0FFFFFFF;
  22254. /**
  22255. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22256. */
  22257. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22258. /**
  22259. * Rig mode of the camera.
  22260. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  22261. * This is normally controlled byt the camera themselves as internal use.
  22262. */
  22263. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22264. /**
  22265. * Defines the list of custom render target the camera should render to.
  22266. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  22267. * else in the scene.
  22268. */
  22269. _this.customRenderTargets = new Array();
  22270. /**
  22271. * Observable triggered when the camera view matrix has changed.
  22272. */
  22273. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22274. /**
  22275. * Observable triggered when the camera Projection matrix has changed.
  22276. */
  22277. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22278. /**
  22279. * Observable triggered when the inputs have been processed.
  22280. */
  22281. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22282. /**
  22283. * Observable triggered when reset has been called and applied to the camera.
  22284. */
  22285. _this.onRestoreStateObservable = new BABYLON.Observable();
  22286. /** @hidden */
  22287. _this._rigCameras = new Array();
  22288. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22289. /** @hidden */
  22290. _this._skipRendering = false;
  22291. /** @hidden */
  22292. _this._projectionMatrix = new BABYLON.Matrix();
  22293. /** @hidden */
  22294. _this._postProcesses = new Array();
  22295. /** @hidden */
  22296. _this._activeMeshes = new BABYLON.SmartArray(256);
  22297. _this._globalPosition = BABYLON.Vector3.Zero();
  22298. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22299. _this._doNotComputeProjectionMatrix = false;
  22300. _this._transformMatrix = BABYLON.Matrix.Zero();
  22301. _this._refreshFrustumPlanes = true;
  22302. _this.getScene().addCamera(_this);
  22303. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22304. _this.getScene().activeCamera = _this;
  22305. }
  22306. _this.position = position;
  22307. return _this;
  22308. }
  22309. /**
  22310. * Store current camera state (fov, position, etc..)
  22311. * @returns the camera
  22312. */
  22313. Camera.prototype.storeState = function () {
  22314. this._stateStored = true;
  22315. this._storedFov = this.fov;
  22316. return this;
  22317. };
  22318. /**
  22319. * Restores the camera state values if it has been stored. You must call storeState() first
  22320. */
  22321. Camera.prototype._restoreStateValues = function () {
  22322. if (!this._stateStored) {
  22323. return false;
  22324. }
  22325. this.fov = this._storedFov;
  22326. return true;
  22327. };
  22328. /**
  22329. * Restored camera state. You must call storeState() first.
  22330. * @returns true if restored and false otherwise
  22331. */
  22332. Camera.prototype.restoreState = function () {
  22333. if (this._restoreStateValues()) {
  22334. this.onRestoreStateObservable.notifyObservers(this);
  22335. return true;
  22336. }
  22337. return false;
  22338. };
  22339. /**
  22340. * Gets the class name of the camera.
  22341. * @returns the class name
  22342. */
  22343. Camera.prototype.getClassName = function () {
  22344. return "Camera";
  22345. };
  22346. /**
  22347. * Gets a string representation of the camera usefull for debug purpose.
  22348. * @param fullDetails Defines that a more verboe level of logging is required
  22349. * @returns the string representation
  22350. */
  22351. Camera.prototype.toString = function (fullDetails) {
  22352. var ret = "Name: " + this.name;
  22353. ret += ", type: " + this.getClassName();
  22354. if (this.animations) {
  22355. for (var i = 0; i < this.animations.length; i++) {
  22356. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22357. }
  22358. }
  22359. if (fullDetails) {
  22360. }
  22361. return ret;
  22362. };
  22363. Object.defineProperty(Camera.prototype, "globalPosition", {
  22364. /**
  22365. * Gets the current world space position of the camera.
  22366. */
  22367. get: function () {
  22368. return this._globalPosition;
  22369. },
  22370. enumerable: true,
  22371. configurable: true
  22372. });
  22373. /**
  22374. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  22375. * @returns the active meshe list
  22376. */
  22377. Camera.prototype.getActiveMeshes = function () {
  22378. return this._activeMeshes;
  22379. };
  22380. /**
  22381. * Check wether a mesh is part of the current active mesh list of the camera
  22382. * @param mesh Defines the mesh to check
  22383. * @returns true if active, false otherwise
  22384. */
  22385. Camera.prototype.isActiveMesh = function (mesh) {
  22386. return (this._activeMeshes.indexOf(mesh) !== -1);
  22387. };
  22388. /**
  22389. * Is this camera ready to be used/rendered
  22390. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22391. * @return true if the camera is ready
  22392. */
  22393. Camera.prototype.isReady = function (completeCheck) {
  22394. if (completeCheck === void 0) { completeCheck = false; }
  22395. if (completeCheck) {
  22396. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22397. var pp = _a[_i];
  22398. if (pp && !pp.isReady()) {
  22399. return false;
  22400. }
  22401. }
  22402. }
  22403. return _super.prototype.isReady.call(this, completeCheck);
  22404. };
  22405. /** @hidden */
  22406. Camera.prototype._initCache = function () {
  22407. _super.prototype._initCache.call(this);
  22408. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22409. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22410. this._cache.mode = undefined;
  22411. this._cache.minZ = undefined;
  22412. this._cache.maxZ = undefined;
  22413. this._cache.fov = undefined;
  22414. this._cache.fovMode = undefined;
  22415. this._cache.aspectRatio = undefined;
  22416. this._cache.orthoLeft = undefined;
  22417. this._cache.orthoRight = undefined;
  22418. this._cache.orthoBottom = undefined;
  22419. this._cache.orthoTop = undefined;
  22420. this._cache.renderWidth = undefined;
  22421. this._cache.renderHeight = undefined;
  22422. };
  22423. /** @hidden */
  22424. Camera.prototype._updateCache = function (ignoreParentClass) {
  22425. if (!ignoreParentClass) {
  22426. _super.prototype._updateCache.call(this);
  22427. }
  22428. this._cache.position.copyFrom(this.position);
  22429. this._cache.upVector.copyFrom(this.upVector);
  22430. };
  22431. /** @hidden */
  22432. Camera.prototype._isSynchronized = function () {
  22433. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22434. };
  22435. /** @hidden */
  22436. Camera.prototype._isSynchronizedViewMatrix = function () {
  22437. if (!_super.prototype._isSynchronized.call(this))
  22438. return false;
  22439. return this._cache.position.equals(this.position)
  22440. && this._cache.upVector.equals(this.upVector)
  22441. && this.isSynchronizedWithParent();
  22442. };
  22443. /** @hidden */
  22444. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22445. var check = this._cache.mode === this.mode
  22446. && this._cache.minZ === this.minZ
  22447. && this._cache.maxZ === this.maxZ;
  22448. if (!check) {
  22449. return false;
  22450. }
  22451. var engine = this.getEngine();
  22452. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22453. check = this._cache.fov === this.fov
  22454. && this._cache.fovMode === this.fovMode
  22455. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22456. }
  22457. else {
  22458. check = this._cache.orthoLeft === this.orthoLeft
  22459. && this._cache.orthoRight === this.orthoRight
  22460. && this._cache.orthoBottom === this.orthoBottom
  22461. && this._cache.orthoTop === this.orthoTop
  22462. && this._cache.renderWidth === engine.getRenderWidth()
  22463. && this._cache.renderHeight === engine.getRenderHeight();
  22464. }
  22465. return check;
  22466. };
  22467. /**
  22468. * Attach the input controls to a specific dom element to get the input from.
  22469. * @param element Defines the element the controls should be listened from
  22470. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  22471. */
  22472. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22473. };
  22474. /**
  22475. * Detach the current controls from the specified dom element.
  22476. * @param element Defines the element to stop listening the inputs from
  22477. */
  22478. Camera.prototype.detachControl = function (element) {
  22479. };
  22480. /**
  22481. * Update the camera state according to the different inputs gathered during the frame.
  22482. */
  22483. Camera.prototype.update = function () {
  22484. this._checkInputs();
  22485. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22486. this._updateRigCameras();
  22487. }
  22488. };
  22489. /** @hidden */
  22490. Camera.prototype._checkInputs = function () {
  22491. this.onAfterCheckInputsObservable.notifyObservers(this);
  22492. };
  22493. Object.defineProperty(Camera.prototype, "rigCameras", {
  22494. /** @hidden */
  22495. get: function () {
  22496. return this._rigCameras;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22502. get: function () {
  22503. return this._rigPostProcess;
  22504. },
  22505. enumerable: true,
  22506. configurable: true
  22507. });
  22508. /**
  22509. * Internal, gets the first post proces.
  22510. * @returns the first post process to be run on this camera.
  22511. */
  22512. Camera.prototype._getFirstPostProcess = function () {
  22513. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22514. if (this._postProcesses[ppIndex] !== null) {
  22515. return this._postProcesses[ppIndex];
  22516. }
  22517. }
  22518. return null;
  22519. };
  22520. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22521. // invalidate framebuffer
  22522. var firstPostProcess = this._getFirstPostProcess();
  22523. if (firstPostProcess) {
  22524. firstPostProcess.markTextureDirty();
  22525. }
  22526. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22527. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22528. var cam = this._rigCameras[i];
  22529. var rigPostProcess = cam._rigPostProcess;
  22530. // for VR rig, there does not have to be a post process
  22531. if (rigPostProcess) {
  22532. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22533. if (isPass) {
  22534. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22535. cam.isIntermediate = this._postProcesses.length === 0;
  22536. }
  22537. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22538. rigPostProcess.markTextureDirty();
  22539. }
  22540. else {
  22541. cam._postProcesses = this._postProcesses.slice(0);
  22542. }
  22543. }
  22544. };
  22545. /**
  22546. * Attach a post process to the camera.
  22547. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22548. * @param postProcess The post process to attach to the camera
  22549. * @param insertAt The position of the post process in case several of them are in use in the scene
  22550. * @returns the position the post process has been inserted at
  22551. */
  22552. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22553. if (insertAt === void 0) { insertAt = null; }
  22554. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22555. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22556. return 0;
  22557. }
  22558. if (insertAt == null || insertAt < 0) {
  22559. this._postProcesses.push(postProcess);
  22560. }
  22561. else if (this._postProcesses[insertAt] === null) {
  22562. this._postProcesses[insertAt] = postProcess;
  22563. }
  22564. else {
  22565. this._postProcesses.splice(insertAt, 0, postProcess);
  22566. }
  22567. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22568. return this._postProcesses.indexOf(postProcess);
  22569. };
  22570. /**
  22571. * Detach a post process to the camera.
  22572. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  22573. * @param postProcess The post process to detach from the camera
  22574. */
  22575. Camera.prototype.detachPostProcess = function (postProcess) {
  22576. var idx = this._postProcesses.indexOf(postProcess);
  22577. if (idx !== -1) {
  22578. this._postProcesses[idx] = null;
  22579. }
  22580. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22581. };
  22582. /**
  22583. * Gets the current world matrix of the camera
  22584. */
  22585. Camera.prototype.getWorldMatrix = function () {
  22586. if (this._isSynchronizedViewMatrix()) {
  22587. return this._worldMatrix;
  22588. }
  22589. // Getting the the view matrix will also compute the world matrix.
  22590. this.getViewMatrix();
  22591. return this._worldMatrix;
  22592. };
  22593. /** @hidden */
  22594. Camera.prototype._getViewMatrix = function () {
  22595. return BABYLON.Matrix.Identity();
  22596. };
  22597. /**
  22598. * Gets the current view matrix of the camera.
  22599. * @param force forces the camera to recompute the matrix without looking at the cached state
  22600. * @returns the view matrix
  22601. */
  22602. Camera.prototype.getViewMatrix = function (force) {
  22603. if (!force && this._isSynchronizedViewMatrix()) {
  22604. return this._computedViewMatrix;
  22605. }
  22606. this.updateCache();
  22607. this._computedViewMatrix = this._getViewMatrix();
  22608. this._currentRenderId = this.getScene().getRenderId();
  22609. this._childRenderId = this._currentRenderId;
  22610. this._refreshFrustumPlanes = true;
  22611. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22612. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22613. }
  22614. this.onViewMatrixChangedObservable.notifyObservers(this);
  22615. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22616. return this._computedViewMatrix;
  22617. };
  22618. /**
  22619. * Freeze the projection matrix.
  22620. * It will prevent the cache check of the camera projection compute and can speed up perf
  22621. * if no parameter of the camera are meant to change
  22622. * @param projection Defines manually a projection if necessary
  22623. */
  22624. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22625. this._doNotComputeProjectionMatrix = true;
  22626. if (projection !== undefined) {
  22627. this._projectionMatrix = projection;
  22628. }
  22629. };
  22630. ;
  22631. /**
  22632. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  22633. */
  22634. Camera.prototype.unfreezeProjectionMatrix = function () {
  22635. this._doNotComputeProjectionMatrix = false;
  22636. };
  22637. ;
  22638. /**
  22639. * Gets the current projection matrix of the camera.
  22640. * @param force forces the camera to recompute the matrix without looking at the cached state
  22641. * @returns the projection matrix
  22642. */
  22643. Camera.prototype.getProjectionMatrix = function (force) {
  22644. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22645. return this._projectionMatrix;
  22646. }
  22647. // Cache
  22648. this._cache.mode = this.mode;
  22649. this._cache.minZ = this.minZ;
  22650. this._cache.maxZ = this.maxZ;
  22651. // Matrix
  22652. this._refreshFrustumPlanes = true;
  22653. var engine = this.getEngine();
  22654. var scene = this.getScene();
  22655. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22656. this._cache.fov = this.fov;
  22657. this._cache.fovMode = this.fovMode;
  22658. this._cache.aspectRatio = engine.getAspectRatio(this);
  22659. if (this.minZ <= 0) {
  22660. this.minZ = 0.1;
  22661. }
  22662. if (scene.useRightHandedSystem) {
  22663. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22664. }
  22665. else {
  22666. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22667. }
  22668. }
  22669. else {
  22670. var halfWidth = engine.getRenderWidth() / 2.0;
  22671. var halfHeight = engine.getRenderHeight() / 2.0;
  22672. if (scene.useRightHandedSystem) {
  22673. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22674. }
  22675. else {
  22676. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22677. }
  22678. this._cache.orthoLeft = this.orthoLeft;
  22679. this._cache.orthoRight = this.orthoRight;
  22680. this._cache.orthoBottom = this.orthoBottom;
  22681. this._cache.orthoTop = this.orthoTop;
  22682. this._cache.renderWidth = engine.getRenderWidth();
  22683. this._cache.renderHeight = engine.getRenderHeight();
  22684. }
  22685. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22686. return this._projectionMatrix;
  22687. };
  22688. /**
  22689. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22690. * @returns a Matrix
  22691. */
  22692. Camera.prototype.getTransformationMatrix = function () {
  22693. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22694. return this._transformMatrix;
  22695. };
  22696. Camera.prototype._updateFrustumPlanes = function () {
  22697. if (!this._refreshFrustumPlanes) {
  22698. return;
  22699. }
  22700. this.getTransformationMatrix();
  22701. if (!this._frustumPlanes) {
  22702. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22703. }
  22704. else {
  22705. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22706. }
  22707. this._refreshFrustumPlanes = false;
  22708. };
  22709. /**
  22710. * Checks if a cullable object (mesh...) is in the camera frustum
  22711. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  22712. * @param target The object to check
  22713. * @returns true if the object is in frustum otherwise false
  22714. */
  22715. Camera.prototype.isInFrustum = function (target) {
  22716. this._updateFrustumPlanes();
  22717. return target.isInFrustum(this._frustumPlanes);
  22718. };
  22719. /**
  22720. * Checks if a cullable object (mesh...) is in the camera frustum
  22721. * Unlike isInFrustum this cheks the full bounding box
  22722. * @param target The object to check
  22723. * @returns true if the object is in frustum otherwise false
  22724. */
  22725. Camera.prototype.isCompletelyInFrustum = function (target) {
  22726. this._updateFrustumPlanes();
  22727. return target.isCompletelyInFrustum(this._frustumPlanes);
  22728. };
  22729. /**
  22730. * Gets a ray in the forward direction from the camera.
  22731. * @param length Defines the length of the ray to create
  22732. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  22733. * @param origin Defines the start point of the ray which defaults to the camera position
  22734. * @returns the forward ray
  22735. */
  22736. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22737. if (length === void 0) { length = 100; }
  22738. if (!transform) {
  22739. transform = this.getWorldMatrix();
  22740. }
  22741. if (!origin) {
  22742. origin = this.position;
  22743. }
  22744. var forward = new BABYLON.Vector3(0, 0, 1);
  22745. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22746. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22747. return new BABYLON.Ray(origin, direction, length);
  22748. };
  22749. /**
  22750. * Releases resources associated with this node.
  22751. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22752. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22753. */
  22754. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22755. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22756. // Observables
  22757. this.onViewMatrixChangedObservable.clear();
  22758. this.onProjectionMatrixChangedObservable.clear();
  22759. this.onAfterCheckInputsObservable.clear();
  22760. this.onRestoreStateObservable.clear();
  22761. // Inputs
  22762. if (this.inputs) {
  22763. this.inputs.clear();
  22764. }
  22765. // Animations
  22766. this.getScene().stopAnimation(this);
  22767. // Remove from scene
  22768. this.getScene().removeCamera(this);
  22769. while (this._rigCameras.length > 0) {
  22770. var camera = this._rigCameras.pop();
  22771. if (camera) {
  22772. camera.dispose();
  22773. }
  22774. }
  22775. // Postprocesses
  22776. if (this._rigPostProcess) {
  22777. this._rigPostProcess.dispose(this);
  22778. this._rigPostProcess = null;
  22779. this._postProcesses = [];
  22780. }
  22781. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22782. this._rigPostProcess = null;
  22783. this._postProcesses = [];
  22784. }
  22785. else {
  22786. var i = this._postProcesses.length;
  22787. while (--i >= 0) {
  22788. var postProcess = this._postProcesses[i];
  22789. if (postProcess) {
  22790. postProcess.dispose(this);
  22791. }
  22792. }
  22793. }
  22794. // Render targets
  22795. var i = this.customRenderTargets.length;
  22796. while (--i >= 0) {
  22797. this.customRenderTargets[i].dispose();
  22798. }
  22799. this.customRenderTargets = [];
  22800. // Active Meshes
  22801. this._activeMeshes.dispose();
  22802. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22803. };
  22804. Object.defineProperty(Camera.prototype, "leftCamera", {
  22805. /**
  22806. * Gets the left camera of a rig setup in case of Rigged Camera
  22807. */
  22808. get: function () {
  22809. if (this._rigCameras.length < 1) {
  22810. return null;
  22811. }
  22812. return this._rigCameras[0];
  22813. },
  22814. enumerable: true,
  22815. configurable: true
  22816. });
  22817. Object.defineProperty(Camera.prototype, "rightCamera", {
  22818. /**
  22819. * Gets the right camera of a rig setup in case of Rigged Camera
  22820. */
  22821. get: function () {
  22822. if (this._rigCameras.length < 2) {
  22823. return null;
  22824. }
  22825. return this._rigCameras[1];
  22826. },
  22827. enumerable: true,
  22828. configurable: true
  22829. });
  22830. /**
  22831. * Gets the left camera target of a rig setup in case of Rigged Camera
  22832. * @returns the target position
  22833. */
  22834. Camera.prototype.getLeftTarget = function () {
  22835. if (this._rigCameras.length < 1) {
  22836. return null;
  22837. }
  22838. return this._rigCameras[0].getTarget();
  22839. };
  22840. /**
  22841. * Gets the right camera target of a rig setup in case of Rigged Camera
  22842. * @returns the target position
  22843. */
  22844. Camera.prototype.getRightTarget = function () {
  22845. if (this._rigCameras.length < 2) {
  22846. return null;
  22847. }
  22848. return this._rigCameras[1].getTarget();
  22849. };
  22850. /**
  22851. * @hidden
  22852. */
  22853. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22854. if (this.cameraRigMode === mode) {
  22855. return;
  22856. }
  22857. while (this._rigCameras.length > 0) {
  22858. var camera = this._rigCameras.pop();
  22859. if (camera) {
  22860. camera.dispose();
  22861. }
  22862. }
  22863. this.cameraRigMode = mode;
  22864. this._cameraRigParams = {};
  22865. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22866. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22867. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22868. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22869. // create the rig cameras, unless none
  22870. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22871. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22872. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22873. if (leftCamera && rightCamera) {
  22874. this._rigCameras.push(leftCamera);
  22875. this._rigCameras.push(rightCamera);
  22876. }
  22877. }
  22878. switch (this.cameraRigMode) {
  22879. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22880. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22881. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22882. break;
  22883. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22884. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22885. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22886. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22887. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22888. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22889. break;
  22890. case Camera.RIG_MODE_VR:
  22891. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22892. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22893. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22894. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22895. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22896. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22897. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22898. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22899. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22900. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22901. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22902. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22903. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22904. if (metrics.compensateDistortion) {
  22905. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22906. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22907. }
  22908. break;
  22909. case Camera.RIG_MODE_WEBVR:
  22910. if (rigParams.vrDisplay) {
  22911. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22912. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22913. //Left eye
  22914. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22915. this._rigCameras[0].setCameraRigParameter("left", true);
  22916. //leaving this for future reference
  22917. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22918. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22919. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22920. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22921. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22922. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22923. this._rigCameras[0].parent = this;
  22924. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22925. //Right eye
  22926. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22927. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22928. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22929. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22930. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22931. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22932. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22933. this._rigCameras[1].parent = this;
  22934. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22935. if (Camera.UseAlternateWebVRRendering) {
  22936. this._rigCameras[1]._skipRendering = true;
  22937. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22938. }
  22939. }
  22940. break;
  22941. }
  22942. this._cascadePostProcessesToRigCams();
  22943. this.update();
  22944. };
  22945. Camera.prototype._getVRProjectionMatrix = function () {
  22946. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22947. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22948. return this._projectionMatrix;
  22949. };
  22950. Camera.prototype._updateCameraRotationMatrix = function () {
  22951. //Here for WebVR
  22952. };
  22953. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22954. //Here for WebVR
  22955. };
  22956. /**
  22957. * This function MUST be overwritten by the different WebVR cameras available.
  22958. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22959. */
  22960. Camera.prototype._getWebVRProjectionMatrix = function () {
  22961. return BABYLON.Matrix.Identity();
  22962. };
  22963. /**
  22964. * This function MUST be overwritten by the different WebVR cameras available.
  22965. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22966. */
  22967. Camera.prototype._getWebVRViewMatrix = function () {
  22968. return BABYLON.Matrix.Identity();
  22969. };
  22970. /** @hidden */
  22971. Camera.prototype.setCameraRigParameter = function (name, value) {
  22972. if (!this._cameraRigParams) {
  22973. this._cameraRigParams = {};
  22974. }
  22975. this._cameraRigParams[name] = value;
  22976. //provisionnally:
  22977. if (name === "interaxialDistance") {
  22978. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22979. }
  22980. };
  22981. /**
  22982. * needs to be overridden by children so sub has required properties to be copied
  22983. * @hidden
  22984. */
  22985. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22986. return null;
  22987. };
  22988. /**
  22989. * May need to be overridden by children
  22990. * @hidden
  22991. */
  22992. Camera.prototype._updateRigCameras = function () {
  22993. for (var i = 0; i < this._rigCameras.length; i++) {
  22994. this._rigCameras[i].minZ = this.minZ;
  22995. this._rigCameras[i].maxZ = this.maxZ;
  22996. this._rigCameras[i].fov = this.fov;
  22997. }
  22998. // only update viewport when ANAGLYPH
  22999. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23000. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23001. }
  23002. };
  23003. /** @hidden */
  23004. Camera.prototype._setupInputs = function () {
  23005. };
  23006. /**
  23007. * Serialiaze the camera setup to a json represention
  23008. * @returns the JSON representation
  23009. */
  23010. Camera.prototype.serialize = function () {
  23011. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23012. // Type
  23013. serializationObject.type = this.getClassName();
  23014. // Parent
  23015. if (this.parent) {
  23016. serializationObject.parentId = this.parent.id;
  23017. }
  23018. if (this.inputs) {
  23019. this.inputs.serialize(serializationObject);
  23020. }
  23021. // Animations
  23022. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23023. serializationObject.ranges = this.serializeAnimationRanges();
  23024. return serializationObject;
  23025. };
  23026. /**
  23027. * Clones the current camera.
  23028. * @param name The cloned camera name
  23029. * @returns the cloned camera
  23030. */
  23031. Camera.prototype.clone = function (name) {
  23032. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23033. };
  23034. /**
  23035. * Gets the direction of the camera relative to a given local axis.
  23036. * @param localAxis Defines the reference axis to provide a relative direction.
  23037. * @return the direction
  23038. */
  23039. Camera.prototype.getDirection = function (localAxis) {
  23040. var result = BABYLON.Vector3.Zero();
  23041. this.getDirectionToRef(localAxis, result);
  23042. return result;
  23043. };
  23044. /**
  23045. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23046. * @param localAxis Defines the reference axis to provide a relative direction.
  23047. * @param result Defines the vector to store the result in
  23048. */
  23049. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23050. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23051. };
  23052. /**
  23053. * Gets a camera constructor for a given camera type
  23054. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23055. * @param name The name of the camera the result will be able to instantiate
  23056. * @param scene The scene the result will construct the camera in
  23057. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23058. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23059. * @returns a factory method to construc the camera
  23060. */
  23061. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23062. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23063. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23064. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23065. interaxial_distance: interaxial_distance,
  23066. isStereoscopicSideBySide: isStereoscopicSideBySide
  23067. });
  23068. if (constructorFunc) {
  23069. return constructorFunc;
  23070. }
  23071. // Default to universal camera
  23072. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23073. };
  23074. /**
  23075. * Compute the world matrix of the camera.
  23076. * @returns the camera workd matrix
  23077. */
  23078. Camera.prototype.computeWorldMatrix = function () {
  23079. return this.getWorldMatrix();
  23080. };
  23081. /**
  23082. * Parse a JSON and creates the camera from the parsed information
  23083. * @param parsedCamera The JSON to parse
  23084. * @param scene The scene to instantiate the camera in
  23085. * @returns the newly constructed camera
  23086. */
  23087. Camera.Parse = function (parsedCamera, scene) {
  23088. var type = parsedCamera.type;
  23089. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23090. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23091. // Parent
  23092. if (parsedCamera.parentId) {
  23093. camera._waitingParentId = parsedCamera.parentId;
  23094. }
  23095. //If camera has an input manager, let it parse inputs settings
  23096. if (camera.inputs) {
  23097. camera.inputs.parse(parsedCamera);
  23098. camera._setupInputs();
  23099. }
  23100. if (camera.setPosition) { // need to force position
  23101. camera.position.copyFromFloats(0, 0, 0);
  23102. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23103. }
  23104. // Target
  23105. if (parsedCamera.target) {
  23106. if (camera.setTarget) {
  23107. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23108. }
  23109. }
  23110. // Apply 3d rig, when found
  23111. if (parsedCamera.cameraRigMode) {
  23112. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23113. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23114. }
  23115. // Animations
  23116. if (parsedCamera.animations) {
  23117. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23118. var parsedAnimation = parsedCamera.animations[animationIndex];
  23119. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23120. }
  23121. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23122. }
  23123. if (parsedCamera.autoAnimate) {
  23124. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23125. }
  23126. return camera;
  23127. };
  23128. /**
  23129. * This is the default projection mode used by the cameras.
  23130. * It helps recreating a feeling of perspective and better appreciate depth.
  23131. * This is the best way to simulate real life cameras.
  23132. */
  23133. Camera.PERSPECTIVE_CAMERA = 0;
  23134. /**
  23135. * This helps creating camera with an orthographic mode.
  23136. * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
  23137. */
  23138. Camera.ORTHOGRAPHIC_CAMERA = 1;
  23139. /**
  23140. * This is the default FOV mode for perspective cameras.
  23141. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  23142. */
  23143. Camera.FOVMODE_VERTICAL_FIXED = 0;
  23144. /**
  23145. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  23146. */
  23147. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  23148. /**
  23149. * This specifies ther is no need for a camera rig.
  23150. * Basically only one eye is rendered corresponding to the camera.
  23151. */
  23152. Camera.RIG_MODE_NONE = 0;
  23153. /**
  23154. * Simulates a camera Rig with one blue eye and one red eye.
  23155. * This can be use with 3d blue and red glasses.
  23156. */
  23157. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23158. /**
  23159. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  23160. */
  23161. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23162. /**
  23163. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  23164. */
  23165. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23166. /**
  23167. * Defines that both eyes of the camera will be rendered over under each other.
  23168. */
  23169. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23170. /**
  23171. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  23172. */
  23173. Camera.RIG_MODE_VR = 20;
  23174. /**
  23175. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  23176. */
  23177. Camera.RIG_MODE_WEBVR = 21;
  23178. /**
  23179. * Defines if by default attaching controls should prevent the default javascript event to continue.
  23180. */
  23181. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23182. /**
  23183. * @hidden
  23184. * Might be removed once multiview will be a thing
  23185. */
  23186. Camera.UseAlternateWebVRRendering = false;
  23187. __decorate([
  23188. BABYLON.serializeAsVector3()
  23189. ], Camera.prototype, "position", void 0);
  23190. __decorate([
  23191. BABYLON.serializeAsVector3()
  23192. ], Camera.prototype, "upVector", void 0);
  23193. __decorate([
  23194. BABYLON.serialize()
  23195. ], Camera.prototype, "orthoLeft", void 0);
  23196. __decorate([
  23197. BABYLON.serialize()
  23198. ], Camera.prototype, "orthoRight", void 0);
  23199. __decorate([
  23200. BABYLON.serialize()
  23201. ], Camera.prototype, "orthoBottom", void 0);
  23202. __decorate([
  23203. BABYLON.serialize()
  23204. ], Camera.prototype, "orthoTop", void 0);
  23205. __decorate([
  23206. BABYLON.serialize()
  23207. ], Camera.prototype, "fov", void 0);
  23208. __decorate([
  23209. BABYLON.serialize()
  23210. ], Camera.prototype, "minZ", void 0);
  23211. __decorate([
  23212. BABYLON.serialize()
  23213. ], Camera.prototype, "maxZ", void 0);
  23214. __decorate([
  23215. BABYLON.serialize()
  23216. ], Camera.prototype, "inertia", void 0);
  23217. __decorate([
  23218. BABYLON.serialize()
  23219. ], Camera.prototype, "mode", void 0);
  23220. __decorate([
  23221. BABYLON.serialize()
  23222. ], Camera.prototype, "layerMask", void 0);
  23223. __decorate([
  23224. BABYLON.serialize()
  23225. ], Camera.prototype, "fovMode", void 0);
  23226. __decorate([
  23227. BABYLON.serialize()
  23228. ], Camera.prototype, "cameraRigMode", void 0);
  23229. __decorate([
  23230. BABYLON.serialize()
  23231. ], Camera.prototype, "interaxialDistance", void 0);
  23232. __decorate([
  23233. BABYLON.serialize()
  23234. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23235. return Camera;
  23236. }(BABYLON.Node));
  23237. BABYLON.Camera = Camera;
  23238. })(BABYLON || (BABYLON = {}));
  23239. //# sourceMappingURL=babylon.camera.js.map
  23240. var BABYLON;
  23241. (function (BABYLON) {
  23242. var RenderingManager = /** @class */ (function () {
  23243. function RenderingManager(scene) {
  23244. /**
  23245. * @hidden
  23246. */
  23247. this._useSceneAutoClearSetup = false;
  23248. this._renderingGroups = new Array();
  23249. this._autoClearDepthStencil = {};
  23250. this._customOpaqueSortCompareFn = {};
  23251. this._customAlphaTestSortCompareFn = {};
  23252. this._customTransparentSortCompareFn = {};
  23253. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23254. this._scene = scene;
  23255. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23256. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23257. }
  23258. }
  23259. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23260. if (depth === void 0) { depth = true; }
  23261. if (stencil === void 0) { stencil = true; }
  23262. if (this._depthStencilBufferAlreadyCleaned) {
  23263. return;
  23264. }
  23265. this._scene.getEngine().clear(null, false, depth, stencil);
  23266. this._depthStencilBufferAlreadyCleaned = true;
  23267. };
  23268. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23269. // Update the observable context (not null as it only goes away on dispose)
  23270. var info = this._renderingGroupInfo;
  23271. info.scene = this._scene;
  23272. info.camera = this._scene.activeCamera;
  23273. // Dispatch sprites
  23274. if (this._scene.spriteManagers && renderSprites) {
  23275. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23276. var manager = this._scene.spriteManagers[index];
  23277. this.dispatchSprites(manager);
  23278. }
  23279. }
  23280. // Render
  23281. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23282. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23283. var renderingGroup = this._renderingGroups[index];
  23284. if (!renderingGroup)
  23285. continue;
  23286. var renderingGroupMask = Math.pow(2, index);
  23287. info.renderingGroupId = index;
  23288. // Before Observable
  23289. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23290. // Clear depth/stencil if needed
  23291. if (RenderingManager.AUTOCLEAR) {
  23292. var autoClear = this._useSceneAutoClearSetup ?
  23293. this._scene.getAutoClearDepthStencilSetup(index) :
  23294. this._autoClearDepthStencil[index];
  23295. if (autoClear && autoClear.autoClear) {
  23296. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23297. }
  23298. }
  23299. // Render
  23300. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23301. var step = _a[_i];
  23302. step.action(index);
  23303. }
  23304. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23305. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23306. var step = _c[_b];
  23307. step.action(index);
  23308. }
  23309. // After Observable
  23310. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23311. }
  23312. };
  23313. RenderingManager.prototype.reset = function () {
  23314. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23315. var renderingGroup = this._renderingGroups[index];
  23316. if (renderingGroup) {
  23317. renderingGroup.prepare();
  23318. }
  23319. }
  23320. };
  23321. RenderingManager.prototype.dispose = function () {
  23322. this.freeRenderingGroups();
  23323. this._renderingGroups.length = 0;
  23324. this._renderingGroupInfo = null;
  23325. };
  23326. /**
  23327. * Clear the info related to rendering groups preventing retention points during dispose.
  23328. */
  23329. RenderingManager.prototype.freeRenderingGroups = function () {
  23330. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23331. var renderingGroup = this._renderingGroups[index];
  23332. if (renderingGroup) {
  23333. renderingGroup.dispose();
  23334. }
  23335. }
  23336. };
  23337. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23338. if (this._renderingGroups[renderingGroupId] === undefined) {
  23339. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23340. }
  23341. };
  23342. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23343. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23344. this._prepareRenderingGroup(renderingGroupId);
  23345. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23346. };
  23347. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23348. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23349. this._prepareRenderingGroup(renderingGroupId);
  23350. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23351. };
  23352. /**
  23353. * @param subMesh The submesh to dispatch
  23354. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23355. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23356. */
  23357. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23358. if (mesh === undefined) {
  23359. mesh = subMesh.getMesh();
  23360. }
  23361. var renderingGroupId = mesh.renderingGroupId || 0;
  23362. this._prepareRenderingGroup(renderingGroupId);
  23363. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23364. };
  23365. /**
  23366. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23367. * This allowed control for front to back rendering or reversly depending of the special needs.
  23368. *
  23369. * @param renderingGroupId The rendering group id corresponding to its index
  23370. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23371. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23372. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23373. */
  23374. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23375. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23376. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23377. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23378. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23379. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23380. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23381. if (this._renderingGroups[renderingGroupId]) {
  23382. var group = this._renderingGroups[renderingGroupId];
  23383. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23384. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23385. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23386. }
  23387. };
  23388. /**
  23389. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23390. *
  23391. * @param renderingGroupId The rendering group id corresponding to its index
  23392. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23393. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23394. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23395. */
  23396. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23397. if (depth === void 0) { depth = true; }
  23398. if (stencil === void 0) { stencil = true; }
  23399. this._autoClearDepthStencil[renderingGroupId] = {
  23400. autoClear: autoClearDepthStencil,
  23401. depth: depth,
  23402. stencil: stencil
  23403. };
  23404. };
  23405. /**
  23406. * Gets the current auto clear configuration for one rendering group of the rendering
  23407. * manager.
  23408. * @param index the rendering group index to get the information for
  23409. * @returns The auto clear setup for the requested rendering group
  23410. */
  23411. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23412. return this._autoClearDepthStencil[index];
  23413. };
  23414. /**
  23415. * The max id used for rendering groups (not included)
  23416. */
  23417. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23418. /**
  23419. * The min id used for rendering groups (included)
  23420. */
  23421. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23422. /**
  23423. * Used to globally prevent autoclearing scenes.
  23424. */
  23425. RenderingManager.AUTOCLEAR = true;
  23426. return RenderingManager;
  23427. }());
  23428. BABYLON.RenderingManager = RenderingManager;
  23429. })(BABYLON || (BABYLON = {}));
  23430. //# sourceMappingURL=babylon.renderingManager.js.map
  23431. var BABYLON;
  23432. (function (BABYLON) {
  23433. var RenderingGroup = /** @class */ (function () {
  23434. /**
  23435. * Creates a new rendering group.
  23436. * @param index The rendering group index
  23437. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23438. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23439. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23440. */
  23441. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23442. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23443. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23444. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23445. this.index = index;
  23446. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23447. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23448. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23449. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23450. this._particleSystems = new BABYLON.SmartArray(256);
  23451. this._spriteManagers = new BABYLON.SmartArray(256);
  23452. this._edgesRenderers = new BABYLON.SmartArray(16);
  23453. this._scene = scene;
  23454. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23455. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23456. this.transparentSortCompareFn = transparentSortCompareFn;
  23457. }
  23458. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23459. /**
  23460. * Set the opaque sort comparison function.
  23461. * If null the sub meshes will be render in the order they were created
  23462. */
  23463. set: function (value) {
  23464. this._opaqueSortCompareFn = value;
  23465. if (value) {
  23466. this._renderOpaque = this.renderOpaqueSorted;
  23467. }
  23468. else {
  23469. this._renderOpaque = RenderingGroup.renderUnsorted;
  23470. }
  23471. },
  23472. enumerable: true,
  23473. configurable: true
  23474. });
  23475. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23476. /**
  23477. * Set the alpha test sort comparison function.
  23478. * If null the sub meshes will be render in the order they were created
  23479. */
  23480. set: function (value) {
  23481. this._alphaTestSortCompareFn = value;
  23482. if (value) {
  23483. this._renderAlphaTest = this.renderAlphaTestSorted;
  23484. }
  23485. else {
  23486. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23487. }
  23488. },
  23489. enumerable: true,
  23490. configurable: true
  23491. });
  23492. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23493. /**
  23494. * Set the transparent sort comparison function.
  23495. * If null the sub meshes will be render in the order they were created
  23496. */
  23497. set: function (value) {
  23498. if (value) {
  23499. this._transparentSortCompareFn = value;
  23500. }
  23501. else {
  23502. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23503. }
  23504. this._renderTransparent = this.renderTransparentSorted;
  23505. },
  23506. enumerable: true,
  23507. configurable: true
  23508. });
  23509. /**
  23510. * Render all the sub meshes contained in the group.
  23511. * @param customRenderFunction Used to override the default render behaviour of the group.
  23512. * @returns true if rendered some submeshes.
  23513. */
  23514. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23515. if (customRenderFunction) {
  23516. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23517. return;
  23518. }
  23519. var engine = this._scene.getEngine();
  23520. // Depth only
  23521. if (this._depthOnlySubMeshes.length !== 0) {
  23522. engine.setColorWrite(false);
  23523. this._renderAlphaTest(this._depthOnlySubMeshes);
  23524. engine.setColorWrite(true);
  23525. }
  23526. // Opaque
  23527. if (this._opaqueSubMeshes.length !== 0) {
  23528. this._renderOpaque(this._opaqueSubMeshes);
  23529. }
  23530. // Alpha test
  23531. if (this._alphaTestSubMeshes.length !== 0) {
  23532. this._renderAlphaTest(this._alphaTestSubMeshes);
  23533. }
  23534. var stencilState = engine.getStencilBuffer();
  23535. engine.setStencilBuffer(false);
  23536. // Sprites
  23537. if (renderSprites) {
  23538. this._renderSprites();
  23539. }
  23540. // Particles
  23541. if (renderParticles) {
  23542. this._renderParticles(activeMeshes);
  23543. }
  23544. if (this.onBeforeTransparentRendering) {
  23545. this.onBeforeTransparentRendering();
  23546. }
  23547. // Transparent
  23548. if (this._transparentSubMeshes.length !== 0) {
  23549. this._renderTransparent(this._transparentSubMeshes);
  23550. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23551. }
  23552. // Set back stencil to false in case it changes before the edge renderer.
  23553. engine.setStencilBuffer(false);
  23554. // Edges
  23555. if (this._edgesRenderers.length) {
  23556. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23557. this._edgesRenderers.data[edgesRendererIndex].render();
  23558. }
  23559. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23560. }
  23561. // Restore Stencil state.
  23562. engine.setStencilBuffer(stencilState);
  23563. };
  23564. /**
  23565. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23566. * @param subMeshes The submeshes to render
  23567. */
  23568. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23569. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23570. };
  23571. /**
  23572. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23573. * @param subMeshes The submeshes to render
  23574. */
  23575. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23576. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23577. };
  23578. /**
  23579. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23580. * @param subMeshes The submeshes to render
  23581. */
  23582. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23583. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23584. };
  23585. /**
  23586. * Renders the submeshes in a specified order.
  23587. * @param subMeshes The submeshes to sort before render
  23588. * @param sortCompareFn The comparison function use to sort
  23589. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23590. * @param transparent Specifies to activate blending if true
  23591. */
  23592. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23593. var subIndex = 0;
  23594. var subMesh;
  23595. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23596. for (; subIndex < subMeshes.length; subIndex++) {
  23597. subMesh = subMeshes.data[subIndex];
  23598. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23599. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23600. }
  23601. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23602. if (sortCompareFn) {
  23603. sortedArray.sort(sortCompareFn);
  23604. }
  23605. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23606. subMesh = sortedArray[subIndex];
  23607. if (transparent) {
  23608. var material = subMesh.getMaterial();
  23609. if (material && material.needDepthPrePass) {
  23610. var engine = material.getScene().getEngine();
  23611. engine.setColorWrite(false);
  23612. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23613. subMesh.render(false);
  23614. engine.setColorWrite(true);
  23615. }
  23616. }
  23617. subMesh.render(transparent);
  23618. }
  23619. };
  23620. /**
  23621. * Renders the submeshes in the order they were dispatched (no sort applied).
  23622. * @param subMeshes The submeshes to render
  23623. */
  23624. RenderingGroup.renderUnsorted = function (subMeshes) {
  23625. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23626. var submesh = subMeshes.data[subIndex];
  23627. submesh.render(false);
  23628. }
  23629. };
  23630. /**
  23631. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23632. * are rendered back to front if in the same alpha index.
  23633. *
  23634. * @param a The first submesh
  23635. * @param b The second submesh
  23636. * @returns The result of the comparison
  23637. */
  23638. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23639. // Alpha index first
  23640. if (a._alphaIndex > b._alphaIndex) {
  23641. return 1;
  23642. }
  23643. if (a._alphaIndex < b._alphaIndex) {
  23644. return -1;
  23645. }
  23646. // Then distance to camera
  23647. return RenderingGroup.backToFrontSortCompare(a, b);
  23648. };
  23649. /**
  23650. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23651. * are rendered back to front.
  23652. *
  23653. * @param a The first submesh
  23654. * @param b The second submesh
  23655. * @returns The result of the comparison
  23656. */
  23657. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23658. // Then distance to camera
  23659. if (a._distanceToCamera < b._distanceToCamera) {
  23660. return 1;
  23661. }
  23662. if (a._distanceToCamera > b._distanceToCamera) {
  23663. return -1;
  23664. }
  23665. return 0;
  23666. };
  23667. /**
  23668. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23669. * are rendered front to back (prevent overdraw).
  23670. *
  23671. * @param a The first submesh
  23672. * @param b The second submesh
  23673. * @returns The result of the comparison
  23674. */
  23675. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23676. // Then distance to camera
  23677. if (a._distanceToCamera < b._distanceToCamera) {
  23678. return -1;
  23679. }
  23680. if (a._distanceToCamera > b._distanceToCamera) {
  23681. return 1;
  23682. }
  23683. return 0;
  23684. };
  23685. /**
  23686. * Resets the different lists of submeshes to prepare a new frame.
  23687. */
  23688. RenderingGroup.prototype.prepare = function () {
  23689. this._opaqueSubMeshes.reset();
  23690. this._transparentSubMeshes.reset();
  23691. this._alphaTestSubMeshes.reset();
  23692. this._depthOnlySubMeshes.reset();
  23693. this._particleSystems.reset();
  23694. this._spriteManagers.reset();
  23695. this._edgesRenderers.reset();
  23696. };
  23697. RenderingGroup.prototype.dispose = function () {
  23698. this._opaqueSubMeshes.dispose();
  23699. this._transparentSubMeshes.dispose();
  23700. this._alphaTestSubMeshes.dispose();
  23701. this._depthOnlySubMeshes.dispose();
  23702. this._particleSystems.dispose();
  23703. this._spriteManagers.dispose();
  23704. this._edgesRenderers.dispose();
  23705. };
  23706. /**
  23707. * Inserts the submesh in its correct queue depending on its material.
  23708. * @param subMesh The submesh to dispatch
  23709. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23710. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23711. */
  23712. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23713. // Get mesh and materials if not provided
  23714. if (mesh === undefined) {
  23715. mesh = subMesh.getMesh();
  23716. }
  23717. if (material === undefined) {
  23718. material = subMesh.getMaterial();
  23719. }
  23720. if (material === null || material === undefined) {
  23721. return;
  23722. }
  23723. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23724. this._transparentSubMeshes.push(subMesh);
  23725. }
  23726. else if (material.needAlphaTesting()) { // Alpha test
  23727. if (material.needDepthPrePass) {
  23728. this._depthOnlySubMeshes.push(subMesh);
  23729. }
  23730. this._alphaTestSubMeshes.push(subMesh);
  23731. }
  23732. else {
  23733. if (material.needDepthPrePass) {
  23734. this._depthOnlySubMeshes.push(subMesh);
  23735. }
  23736. this._opaqueSubMeshes.push(subMesh); // Opaque
  23737. }
  23738. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  23739. this._edgesRenderers.push(mesh._edgesRenderer);
  23740. }
  23741. };
  23742. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23743. this._spriteManagers.push(spriteManager);
  23744. };
  23745. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23746. this._particleSystems.push(particleSystem);
  23747. };
  23748. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23749. if (this._particleSystems.length === 0) {
  23750. return;
  23751. }
  23752. // Particles
  23753. var activeCamera = this._scene.activeCamera;
  23754. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23755. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23756. var particleSystem = this._particleSystems.data[particleIndex];
  23757. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23758. continue;
  23759. }
  23760. var emitter = particleSystem.emitter;
  23761. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23762. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23763. }
  23764. }
  23765. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23766. };
  23767. RenderingGroup.prototype._renderSprites = function () {
  23768. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23769. return;
  23770. }
  23771. // Sprites
  23772. var activeCamera = this._scene.activeCamera;
  23773. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23774. for (var id = 0; id < this._spriteManagers.length; id++) {
  23775. var spriteManager = this._spriteManagers.data[id];
  23776. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23777. spriteManager.render();
  23778. }
  23779. }
  23780. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23781. };
  23782. return RenderingGroup;
  23783. }());
  23784. BABYLON.RenderingGroup = RenderingGroup;
  23785. })(BABYLON || (BABYLON = {}));
  23786. //# sourceMappingURL=babylon.renderingGroup.js.map
  23787. var BABYLON;
  23788. (function (BABYLON) {
  23789. /**
  23790. * Groups all the scene component constants in one place to ease maintenance.
  23791. * @hidden
  23792. */
  23793. var SceneComponentConstants = /** @class */ (function () {
  23794. function SceneComponentConstants() {
  23795. }
  23796. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23797. SceneComponentConstants.NAME_LAYER = "Layer";
  23798. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23799. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23800. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23801. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23802. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  23803. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  23804. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  23805. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  23806. SceneComponentConstants.NAME_SPRITE = "Sprite";
  23807. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  23808. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  23809. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  23810. SceneComponentConstants.NAME_OCTREE = "Octree";
  23811. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  23812. SceneComponentConstants.NAME_AUDIO = "Audio";
  23813. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23814. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23815. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23816. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23817. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23818. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23819. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23820. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  23821. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  23822. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23823. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  23824. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  23825. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  23826. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  23827. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23828. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23829. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23830. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23831. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  23832. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  23833. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  23834. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  23835. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  23836. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  23837. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  23838. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  23839. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  23840. return SceneComponentConstants;
  23841. }());
  23842. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23843. /**
  23844. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23845. * @hidden
  23846. */
  23847. var Stage = /** @class */ (function (_super) {
  23848. __extends(Stage, _super);
  23849. /**
  23850. * Hide ctor from the rest of the world.
  23851. * @param items The items to add.
  23852. */
  23853. function Stage(items) {
  23854. return _super.apply(this, items) || this;
  23855. }
  23856. /**
  23857. * Creates a new Stage.
  23858. * @returns A new instance of a Stage
  23859. */
  23860. Stage.Create = function () {
  23861. return Object.create(Stage.prototype);
  23862. };
  23863. /**
  23864. * Registers a step in an ordered way in the targeted stage.
  23865. * @param index Defines the position to register the step in
  23866. * @param component Defines the component attached to the step
  23867. * @param action Defines the action to launch during the step
  23868. */
  23869. Stage.prototype.registerStep = function (index, component, action) {
  23870. var i = 0;
  23871. var maxIndex = Number.MAX_VALUE;
  23872. for (; i < this.length && i < maxIndex; i++) {
  23873. var step = this[i];
  23874. maxIndex = step.index;
  23875. }
  23876. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23877. };
  23878. /**
  23879. * Clears all the steps from the stage.
  23880. */
  23881. Stage.prototype.clear = function () {
  23882. this.length = 0;
  23883. };
  23884. return Stage;
  23885. }(Array));
  23886. BABYLON.Stage = Stage;
  23887. })(BABYLON || (BABYLON = {}));
  23888. //# sourceMappingURL=babylon.sceneComponent.js.map
  23889. var BABYLON;
  23890. (function (BABYLON) {
  23891. /**
  23892. * Base class of the scene acting as a container for the different elements composing a scene.
  23893. * This class is dynamically extended by the different components of the scene increasing
  23894. * flexibility and reducing coupling
  23895. */
  23896. var AbstractScene = /** @class */ (function () {
  23897. function AbstractScene() {
  23898. /**
  23899. * Gets the list of root nodes (ie. nodes with no parent)
  23900. */
  23901. this.rootNodes = new Array();
  23902. /** All of the cameras added to this scene
  23903. * @see http://doc.babylonjs.com/babylon101/cameras
  23904. */
  23905. this.cameras = new Array();
  23906. /**
  23907. * All of the lights added to this scene
  23908. * @see http://doc.babylonjs.com/babylon101/lights
  23909. */
  23910. this.lights = new Array();
  23911. /**
  23912. * All of the (abstract) meshes added to this scene
  23913. */
  23914. this.meshes = new Array();
  23915. /**
  23916. * The list of skeletons added to the scene
  23917. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23918. */
  23919. this.skeletons = new Array();
  23920. /**
  23921. * All of the particle systems added to this scene
  23922. * @see http://doc.babylonjs.com/babylon101/particles
  23923. */
  23924. this.particleSystems = new Array();
  23925. /**
  23926. * Gets a list of Animations associated with the scene
  23927. */
  23928. this.animations = [];
  23929. /**
  23930. * All of the animation groups added to this scene
  23931. * @see http://doc.babylonjs.com/how_to/group
  23932. */
  23933. this.animationGroups = new Array();
  23934. /**
  23935. * All of the multi-materials added to this scene
  23936. * @see http://doc.babylonjs.com/how_to/multi_materials
  23937. */
  23938. this.multiMaterials = new Array();
  23939. /**
  23940. * All of the materials added to this scene
  23941. * @see http://doc.babylonjs.com/babylon101/materials
  23942. */
  23943. this.materials = new Array();
  23944. /**
  23945. * The list of morph target managers added to the scene
  23946. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23947. */
  23948. this.morphTargetManagers = new Array();
  23949. /**
  23950. * The list of geometries used in the scene.
  23951. */
  23952. this.geometries = new Array();
  23953. /**
  23954. * All of the tranform nodes added to this scene
  23955. * @see http://doc.babylonjs.com/how_to/transformnode
  23956. */
  23957. this.transformNodes = new Array();
  23958. /**
  23959. * ActionManagers available on the scene.
  23960. */
  23961. this.actionManagers = new Array();
  23962. /**
  23963. * Textures to keep.
  23964. */
  23965. this.textures = new Array();
  23966. }
  23967. /**
  23968. * Adds a parser in the list of available ones
  23969. * @param name Defines the name of the parser
  23970. * @param parser Defines the parser to add
  23971. */
  23972. AbstractScene.AddParser = function (name, parser) {
  23973. this._BabylonFileParsers[name] = parser;
  23974. };
  23975. /**
  23976. * Gets a general parser from the list of avaialble ones
  23977. * @param name Defines the name of the parser
  23978. * @returns the requested parser or null
  23979. */
  23980. AbstractScene.GetParser = function (name) {
  23981. if (this._BabylonFileParsers[name]) {
  23982. return this._BabylonFileParsers[name];
  23983. }
  23984. return null;
  23985. };
  23986. /**
  23987. * Adds n individual parser in the list of available ones
  23988. * @param name Defines the name of the parser
  23989. * @param parser Defines the parser to add
  23990. */
  23991. AbstractScene.AddIndividualParser = function (name, parser) {
  23992. this._IndividualBabylonFileParsers[name] = parser;
  23993. };
  23994. /**
  23995. * Gets an individual parser from the list of avaialble ones
  23996. * @param name Defines the name of the parser
  23997. * @returns the requested parser or null
  23998. */
  23999. AbstractScene.GetIndividualParser = function (name) {
  24000. if (this._IndividualBabylonFileParsers[name]) {
  24001. return this._IndividualBabylonFileParsers[name];
  24002. }
  24003. return null;
  24004. };
  24005. /**
  24006. * Parser json data and populate both a scene and its associated container object
  24007. * @param jsonData Defines the data to parse
  24008. * @param scene Defines the scene to parse the data for
  24009. * @param container Defines the container attached to the parsing sequence
  24010. * @param rootUrl Defines the root url of the data
  24011. */
  24012. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24013. for (var parserName in this._BabylonFileParsers) {
  24014. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24015. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24016. }
  24017. }
  24018. };
  24019. /**
  24020. * Stores the list of available parsers in the application.
  24021. */
  24022. AbstractScene._BabylonFileParsers = {};
  24023. /**
  24024. * Stores the list of available individual parsers in the application.
  24025. */
  24026. AbstractScene._IndividualBabylonFileParsers = {};
  24027. return AbstractScene;
  24028. }());
  24029. BABYLON.AbstractScene = AbstractScene;
  24030. })(BABYLON || (BABYLON = {}));
  24031. //# sourceMappingURL=babylon.abstractScene.js.map
  24032. var BABYLON;
  24033. (function (BABYLON) {
  24034. /** @hidden */
  24035. var ClickInfo = /** @class */ (function () {
  24036. function ClickInfo() {
  24037. this._singleClick = false;
  24038. this._doubleClick = false;
  24039. this._hasSwiped = false;
  24040. this._ignore = false;
  24041. }
  24042. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24043. get: function () {
  24044. return this._singleClick;
  24045. },
  24046. set: function (b) {
  24047. this._singleClick = b;
  24048. },
  24049. enumerable: true,
  24050. configurable: true
  24051. });
  24052. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24053. get: function () {
  24054. return this._doubleClick;
  24055. },
  24056. set: function (b) {
  24057. this._doubleClick = b;
  24058. },
  24059. enumerable: true,
  24060. configurable: true
  24061. });
  24062. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24063. get: function () {
  24064. return this._hasSwiped;
  24065. },
  24066. set: function (b) {
  24067. this._hasSwiped = b;
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24073. get: function () {
  24074. return this._ignore;
  24075. },
  24076. set: function (b) {
  24077. this._ignore = b;
  24078. },
  24079. enumerable: true,
  24080. configurable: true
  24081. });
  24082. return ClickInfo;
  24083. }());
  24084. /**
  24085. * This class is used by the onRenderingGroupObservable
  24086. */
  24087. var RenderingGroupInfo = /** @class */ (function () {
  24088. function RenderingGroupInfo() {
  24089. }
  24090. return RenderingGroupInfo;
  24091. }());
  24092. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24093. /**
  24094. * Represents a scene to be rendered by the engine.
  24095. * @see http://doc.babylonjs.com/features/scene
  24096. */
  24097. var Scene = /** @class */ (function (_super) {
  24098. __extends(Scene, _super);
  24099. /**
  24100. * Creates a new Scene
  24101. * @param engine defines the engine to use to render this scene
  24102. */
  24103. function Scene(engine) {
  24104. var _this = _super.call(this) || this;
  24105. // Members
  24106. /**
  24107. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24108. */
  24109. _this.autoClear = true;
  24110. /**
  24111. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24112. */
  24113. _this.autoClearDepthAndStencil = true;
  24114. /**
  24115. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24116. */
  24117. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24118. /**
  24119. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24120. */
  24121. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24122. _this._forceWireframe = false;
  24123. _this._forcePointsCloud = false;
  24124. /**
  24125. * Gets or sets a boolean indicating if animations are enabled
  24126. */
  24127. _this.animationsEnabled = true;
  24128. _this._animationPropertiesOverride = null;
  24129. /**
  24130. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24131. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24132. */
  24133. _this.useConstantAnimationDeltaTime = false;
  24134. /**
  24135. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24136. * Please note that it requires to run a ray cast through the scene on every frame
  24137. */
  24138. _this.constantlyUpdateMeshUnderPointer = false;
  24139. /**
  24140. * Defines the HTML cursor to use when hovering over interactive elements
  24141. */
  24142. _this.hoverCursor = "pointer";
  24143. /**
  24144. * Defines the HTML default cursor to use (empty by default)
  24145. */
  24146. _this.defaultCursor = "";
  24147. /**
  24148. * This is used to call preventDefault() on pointer down
  24149. * in order to block unwanted artifacts like system double clicks
  24150. */
  24151. _this.preventDefaultOnPointerDown = true;
  24152. // Metadata
  24153. /**
  24154. * Gets or sets user defined metadata
  24155. */
  24156. _this.metadata = null;
  24157. /**
  24158. * Use this array to add regular expressions used to disable offline support for specific urls
  24159. */
  24160. _this.disableOfflineSupportExceptionRules = new Array();
  24161. /**
  24162. * An event triggered when the scene is disposed.
  24163. */
  24164. _this.onDisposeObservable = new BABYLON.Observable();
  24165. _this._onDisposeObserver = null;
  24166. /**
  24167. * An event triggered before rendering the scene (right after animations and physics)
  24168. */
  24169. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24170. _this._onBeforeRenderObserver = null;
  24171. /**
  24172. * An event triggered after rendering the scene
  24173. */
  24174. _this.onAfterRenderObservable = new BABYLON.Observable();
  24175. _this._onAfterRenderObserver = null;
  24176. /**
  24177. * An event triggered before animating the scene
  24178. */
  24179. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24180. /**
  24181. * An event triggered after animations processing
  24182. */
  24183. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24184. /**
  24185. * An event triggered before draw calls are ready to be sent
  24186. */
  24187. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24188. /**
  24189. * An event triggered after draw calls have been sent
  24190. */
  24191. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24192. /**
  24193. * An event triggered when the scene is ready
  24194. */
  24195. _this.onReadyObservable = new BABYLON.Observable();
  24196. /**
  24197. * An event triggered before rendering a camera
  24198. */
  24199. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24200. _this._onBeforeCameraRenderObserver = null;
  24201. /**
  24202. * An event triggered after rendering a camera
  24203. */
  24204. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24205. _this._onAfterCameraRenderObserver = null;
  24206. /**
  24207. * An event triggered when active meshes evaluation is about to start
  24208. */
  24209. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24210. /**
  24211. * An event triggered when active meshes evaluation is done
  24212. */
  24213. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24214. /**
  24215. * An event triggered when particles rendering is about to start
  24216. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24217. */
  24218. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24219. /**
  24220. * An event triggered when particles rendering is done
  24221. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24222. */
  24223. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24224. /**
  24225. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24226. */
  24227. _this.onDataLoadedObservable = new BABYLON.Observable();
  24228. /**
  24229. * An event triggered when a camera is created
  24230. */
  24231. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24232. /**
  24233. * An event triggered when a camera is removed
  24234. */
  24235. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24236. /**
  24237. * An event triggered when a light is created
  24238. */
  24239. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24240. /**
  24241. * An event triggered when a light is removed
  24242. */
  24243. _this.onLightRemovedObservable = new BABYLON.Observable();
  24244. /**
  24245. * An event triggered when a geometry is created
  24246. */
  24247. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24248. /**
  24249. * An event triggered when a geometry is removed
  24250. */
  24251. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24252. /**
  24253. * An event triggered when a transform node is created
  24254. */
  24255. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24256. /**
  24257. * An event triggered when a transform node is removed
  24258. */
  24259. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24260. /**
  24261. * An event triggered when a mesh is created
  24262. */
  24263. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24264. /**
  24265. * An event triggered when a mesh is removed
  24266. */
  24267. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24268. /**
  24269. * An event triggered when render targets are about to be rendered
  24270. * Can happen multiple times per frame.
  24271. */
  24272. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24273. /**
  24274. * An event triggered when render targets were rendered.
  24275. * Can happen multiple times per frame.
  24276. */
  24277. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24278. /**
  24279. * An event triggered before calculating deterministic simulation step
  24280. */
  24281. _this.onBeforeStepObservable = new BABYLON.Observable();
  24282. /**
  24283. * An event triggered after calculating deterministic simulation step
  24284. */
  24285. _this.onAfterStepObservable = new BABYLON.Observable();
  24286. /**
  24287. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24288. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24289. * 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)
  24290. */
  24291. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24292. /**
  24293. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24294. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24295. * 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)
  24296. */
  24297. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24298. /**
  24299. * This Observable will when a mesh has been imported into the scene.
  24300. */
  24301. _this.onMeshImportedObservable = new BABYLON.Observable();
  24302. // Animations
  24303. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24304. /**
  24305. * 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).
  24306. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24307. */
  24308. _this.onPrePointerObservable = new BABYLON.Observable();
  24309. /**
  24310. * Observable event triggered each time an input event is received from the rendering canvas
  24311. */
  24312. _this.onPointerObservable = new BABYLON.Observable();
  24313. _this._meshPickProceed = false;
  24314. _this._currentPickResult = null;
  24315. _this._previousPickResult = null;
  24316. _this._totalPointersPressed = 0;
  24317. _this._doubleClickOccured = false;
  24318. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24319. _this.cameraToUseForPointers = null;
  24320. _this._pointerX = 0;
  24321. _this._pointerY = 0;
  24322. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24323. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24324. _this._startingPointerTime = 0;
  24325. _this._previousStartingPointerTime = 0;
  24326. _this._pointerCaptures = {};
  24327. // Deterministic lockstep
  24328. _this._timeAccumulator = 0;
  24329. _this._currentStepId = 0;
  24330. _this._currentInternalStep = 0;
  24331. // Keyboard
  24332. /**
  24333. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24334. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24335. */
  24336. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24337. /**
  24338. * Observable event triggered each time an keyboard event is received from the hosting window
  24339. */
  24340. _this.onKeyboardObservable = new BABYLON.Observable();
  24341. // Coordinates system
  24342. _this._useRightHandedSystem = false;
  24343. // Fog
  24344. _this._fogEnabled = true;
  24345. _this._fogMode = Scene.FOGMODE_NONE;
  24346. /**
  24347. * Gets or sets the fog color to use
  24348. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24349. */
  24350. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24351. /**
  24352. * Gets or sets the fog density to use
  24353. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24354. */
  24355. _this.fogDensity = 0.1;
  24356. /**
  24357. * Gets or sets the fog start distance to use
  24358. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24359. */
  24360. _this.fogStart = 0;
  24361. /**
  24362. * Gets or sets the fog end distance to use
  24363. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24364. */
  24365. _this.fogEnd = 1000.0;
  24366. // Lights
  24367. _this._shadowsEnabled = true;
  24368. _this._lightsEnabled = true;
  24369. /** All of the active cameras added to this scene. */
  24370. _this.activeCameras = new Array();
  24371. // Textures
  24372. _this._texturesEnabled = true;
  24373. // Particles
  24374. /**
  24375. * Gets or sets a boolean indicating if particles are enabled on this scene
  24376. */
  24377. _this.particlesEnabled = true;
  24378. // Sprites
  24379. /**
  24380. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24381. */
  24382. _this.spritesEnabled = true;
  24383. // Skeletons
  24384. _this._skeletonsEnabled = true;
  24385. // Lens flares
  24386. /**
  24387. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24388. */
  24389. _this.lensFlaresEnabled = true;
  24390. // Collisions
  24391. /**
  24392. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24393. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24394. */
  24395. _this.collisionsEnabled = true;
  24396. /**
  24397. * Defines the gravity applied to this scene (used only for collisions)
  24398. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24399. */
  24400. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24401. // Postprocesses
  24402. /**
  24403. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24404. */
  24405. _this.postProcessesEnabled = true;
  24406. /**
  24407. * The list of postprocesses added to the scene
  24408. */
  24409. _this.postProcesses = new Array();
  24410. // Customs render targets
  24411. /**
  24412. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24413. */
  24414. _this.renderTargetsEnabled = true;
  24415. /**
  24416. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24417. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24418. */
  24419. _this.dumpNextRenderTargets = false;
  24420. /**
  24421. * The list of user defined render targets added to the scene
  24422. */
  24423. _this.customRenderTargets = new Array();
  24424. /**
  24425. * Gets the list of meshes imported to the scene through SceneLoader
  24426. */
  24427. _this.importedMeshesFiles = new Array();
  24428. // Probes
  24429. /**
  24430. * Gets or sets a boolean indicating if probes are enabled on this scene
  24431. */
  24432. _this.probesEnabled = true;
  24433. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24434. // Procedural textures
  24435. /**
  24436. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24437. */
  24438. _this.proceduralTexturesEnabled = true;
  24439. // Performance counters
  24440. _this._totalVertices = new BABYLON.PerfCounter();
  24441. /** @hidden */
  24442. _this._activeIndices = new BABYLON.PerfCounter();
  24443. /** @hidden */
  24444. _this._activeParticles = new BABYLON.PerfCounter();
  24445. /** @hidden */
  24446. _this._activeBones = new BABYLON.PerfCounter();
  24447. _this._animationTime = 0;
  24448. /**
  24449. * Gets or sets a general scale for animation speed
  24450. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24451. */
  24452. _this.animationTimeScale = 1;
  24453. _this._renderId = 0;
  24454. _this._frameId = 0;
  24455. _this._executeWhenReadyTimeoutId = -1;
  24456. _this._intermediateRendering = false;
  24457. _this._viewUpdateFlag = -1;
  24458. _this._projectionUpdateFlag = -1;
  24459. _this._alternateViewUpdateFlag = -1;
  24460. _this._alternateProjectionUpdateFlag = -1;
  24461. /** @hidden */
  24462. _this._toBeDisposed = new Array(256);
  24463. _this._activeRequests = new Array();
  24464. _this._pendingData = new Array();
  24465. _this._isDisposed = false;
  24466. /**
  24467. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24468. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24469. */
  24470. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24471. _this._activeMeshes = new BABYLON.SmartArray(256);
  24472. _this._processedMaterials = new BABYLON.SmartArray(256);
  24473. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24474. /** @hidden */
  24475. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24476. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24477. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24478. /** @hidden */
  24479. _this._activeAnimatables = new Array();
  24480. _this._transformMatrix = BABYLON.Matrix.Zero();
  24481. _this._useAlternateCameraConfiguration = false;
  24482. _this._alternateRendering = false;
  24483. /**
  24484. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24485. * This is useful if there are more lights that the maximum simulteanous authorized
  24486. */
  24487. _this.requireLightSorting = false;
  24488. /**
  24489. * @hidden
  24490. * Backing store of defined scene components.
  24491. */
  24492. _this._components = [];
  24493. /**
  24494. * @hidden
  24495. * Backing store of defined scene components.
  24496. */
  24497. _this._serializableComponents = [];
  24498. /**
  24499. * List of components to register on the next registration step.
  24500. */
  24501. _this._transientComponents = [];
  24502. /**
  24503. * @hidden
  24504. * Defines the actions happening before camera updates.
  24505. */
  24506. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24507. /**
  24508. * @hidden
  24509. * Defines the actions happening before clear the canvas.
  24510. */
  24511. _this._beforeClearStage = BABYLON.Stage.Create();
  24512. /**
  24513. * @hidden
  24514. * Defines the actions when collecting render targets for the frame.
  24515. */
  24516. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  24517. /**
  24518. * @hidden
  24519. * Defines the actions happening for one camera in the frame.
  24520. */
  24521. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  24522. /**
  24523. * @hidden
  24524. * Defines the actions happening during the per mesh ready checks.
  24525. */
  24526. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24527. /**
  24528. * @hidden
  24529. * Defines the actions happening before evaluate active mesh checks.
  24530. */
  24531. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24532. /**
  24533. * @hidden
  24534. * Defines the actions happening during the evaluate sub mesh checks.
  24535. */
  24536. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24537. /**
  24538. * @hidden
  24539. * Defines the actions happening during the active mesh stage.
  24540. */
  24541. _this._activeMeshStage = BABYLON.Stage.Create();
  24542. /**
  24543. * @hidden
  24544. * Defines the actions happening during the per camera render target step.
  24545. */
  24546. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24547. /**
  24548. * @hidden
  24549. * Defines the actions happening just before the active camera is drawing.
  24550. */
  24551. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24552. /**
  24553. * @hidden
  24554. * Defines the actions happening just before a rendering group is drawing.
  24555. */
  24556. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24557. /**
  24558. * @hidden
  24559. * Defines the actions happening just before a mesh is drawing.
  24560. */
  24561. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  24562. /**
  24563. * @hidden
  24564. * Defines the actions happening just after a mesh has been drawn.
  24565. */
  24566. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  24567. /**
  24568. * @hidden
  24569. * Defines the actions happening just after a rendering group has been drawn.
  24570. */
  24571. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24572. /**
  24573. * @hidden
  24574. * Defines the actions happening just after the active camera has been drawn.
  24575. */
  24576. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24577. /**
  24578. * @hidden
  24579. * Defines the actions happening just after rendering all cameras and computing intersections.
  24580. */
  24581. _this._afterRenderStage = BABYLON.Stage.Create();
  24582. /**
  24583. * @hidden
  24584. * Defines the actions happening when a pointer move event happens.
  24585. */
  24586. _this._pointerMoveStage = BABYLON.Stage.Create();
  24587. /**
  24588. * @hidden
  24589. * Defines the actions happening when a pointer down event happens.
  24590. */
  24591. _this._pointerDownStage = BABYLON.Stage.Create();
  24592. /**
  24593. * @hidden
  24594. * Defines the actions happening when a pointer up event happens.
  24595. */
  24596. _this._pointerUpStage = BABYLON.Stage.Create();
  24597. _this._defaultMeshCandidates = {
  24598. data: [],
  24599. length: 0
  24600. };
  24601. _this._defaultSubMeshCandidates = {
  24602. data: [],
  24603. length: 0
  24604. };
  24605. _this._activeMeshesFrozen = false;
  24606. /** @hidden */
  24607. _this._allowPostProcessClearColor = true;
  24608. /**
  24609. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  24610. */
  24611. _this.getDeterministicFrameTime = function () {
  24612. return 1000.0 / 60.0; // frame time in ms
  24613. };
  24614. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24615. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24616. _this.blockMaterialDirtyMechanism = false;
  24617. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24618. _this._engine.scenes.push(_this);
  24619. _this._uid = null;
  24620. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24621. if (BABYLON.PostProcessManager) {
  24622. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24623. }
  24624. if (BABYLON.Tools.IsWindowObjectExist()) {
  24625. _this.attachControl();
  24626. }
  24627. //collision coordinator initialization. For now legacy per default.
  24628. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24629. // Uniform Buffer
  24630. _this._createUbo();
  24631. // Default Image processing definition
  24632. if (BABYLON.ImageProcessingConfiguration) {
  24633. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24634. }
  24635. _this.setDefaultCandidateProviders();
  24636. return _this;
  24637. }
  24638. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24639. /**
  24640. * Texture used in all pbr material as the reflection texture.
  24641. * As in the majority of the scene they are the same (exception for multi room and so on),
  24642. * this is easier to reference from here than from all the materials.
  24643. */
  24644. get: function () {
  24645. return this._environmentTexture;
  24646. },
  24647. /**
  24648. * Texture used in all pbr material as the reflection texture.
  24649. * As in the majority of the scene they are the same (exception for multi room and so on),
  24650. * this is easier to set here than in all the materials.
  24651. */
  24652. set: function (value) {
  24653. if (this._environmentTexture === value) {
  24654. return;
  24655. }
  24656. this._environmentTexture = value;
  24657. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24663. /**
  24664. * Default image processing configuration used either in the rendering
  24665. * Forward main pass or through the imageProcessingPostProcess if present.
  24666. * As in the majority of the scene they are the same (exception for multi camera),
  24667. * this is easier to reference from here than from all the materials and post process.
  24668. *
  24669. * No setter as we it is a shared configuration, you can set the values instead.
  24670. */
  24671. get: function () {
  24672. return this._imageProcessingConfiguration;
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24678. get: function () {
  24679. return this._forceWireframe;
  24680. },
  24681. /**
  24682. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24683. */
  24684. set: function (value) {
  24685. if (this._forceWireframe === value) {
  24686. return;
  24687. }
  24688. this._forceWireframe = value;
  24689. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24690. },
  24691. enumerable: true,
  24692. configurable: true
  24693. });
  24694. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24695. get: function () {
  24696. return this._forcePointsCloud;
  24697. },
  24698. /**
  24699. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24700. */
  24701. set: function (value) {
  24702. if (this._forcePointsCloud === value) {
  24703. return;
  24704. }
  24705. this._forcePointsCloud = value;
  24706. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24707. },
  24708. enumerable: true,
  24709. configurable: true
  24710. });
  24711. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24712. /**
  24713. * Gets or sets the animation properties override
  24714. */
  24715. get: function () {
  24716. return this._animationPropertiesOverride;
  24717. },
  24718. set: function (value) {
  24719. this._animationPropertiesOverride = value;
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. Object.defineProperty(Scene.prototype, "onDispose", {
  24725. /** Sets a function to be executed when this scene is disposed. */
  24726. set: function (callback) {
  24727. if (this._onDisposeObserver) {
  24728. this.onDisposeObservable.remove(this._onDisposeObserver);
  24729. }
  24730. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. Object.defineProperty(Scene.prototype, "beforeRender", {
  24736. /** Sets a function to be executed before rendering this scene */
  24737. set: function (callback) {
  24738. if (this._onBeforeRenderObserver) {
  24739. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24740. }
  24741. if (callback) {
  24742. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24743. }
  24744. },
  24745. enumerable: true,
  24746. configurable: true
  24747. });
  24748. Object.defineProperty(Scene.prototype, "afterRender", {
  24749. /** Sets a function to be executed after rendering this scene */
  24750. set: function (callback) {
  24751. if (this._onAfterRenderObserver) {
  24752. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24753. }
  24754. if (callback) {
  24755. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24756. }
  24757. },
  24758. enumerable: true,
  24759. configurable: true
  24760. });
  24761. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24762. /** Sets a function to be executed before rendering a camera*/
  24763. set: function (callback) {
  24764. if (this._onBeforeCameraRenderObserver) {
  24765. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24766. }
  24767. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24768. },
  24769. enumerable: true,
  24770. configurable: true
  24771. });
  24772. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24773. /** Sets a function to be executed after rendering a camera*/
  24774. set: function (callback) {
  24775. if (this._onAfterCameraRenderObserver) {
  24776. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24777. }
  24778. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24779. },
  24780. enumerable: true,
  24781. configurable: true
  24782. });
  24783. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24784. /**
  24785. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24786. */
  24787. get: function () {
  24788. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24789. },
  24790. enumerable: true,
  24791. configurable: true
  24792. });
  24793. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24794. get: function () {
  24795. return this._useRightHandedSystem;
  24796. },
  24797. /**
  24798. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24799. */
  24800. set: function (value) {
  24801. if (this._useRightHandedSystem === value) {
  24802. return;
  24803. }
  24804. this._useRightHandedSystem = value;
  24805. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. /**
  24811. * Sets the step Id used by deterministic lock step
  24812. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24813. * @param newStepId defines the step Id
  24814. */
  24815. Scene.prototype.setStepId = function (newStepId) {
  24816. this._currentStepId = newStepId;
  24817. };
  24818. ;
  24819. /**
  24820. * Gets the step Id used by deterministic lock step
  24821. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24822. * @returns the step Id
  24823. */
  24824. Scene.prototype.getStepId = function () {
  24825. return this._currentStepId;
  24826. };
  24827. ;
  24828. /**
  24829. * Gets the internal step used by deterministic lock step
  24830. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24831. * @returns the internal step
  24832. */
  24833. Scene.prototype.getInternalStep = function () {
  24834. return this._currentInternalStep;
  24835. };
  24836. ;
  24837. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24838. get: function () {
  24839. return this._fogEnabled;
  24840. },
  24841. /**
  24842. * Gets or sets a boolean indicating if fog is enabled on this scene
  24843. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24844. */
  24845. set: function (value) {
  24846. if (this._fogEnabled === value) {
  24847. return;
  24848. }
  24849. this._fogEnabled = value;
  24850. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24851. },
  24852. enumerable: true,
  24853. configurable: true
  24854. });
  24855. Object.defineProperty(Scene.prototype, "fogMode", {
  24856. get: function () {
  24857. return this._fogMode;
  24858. },
  24859. /**
  24860. * Gets or sets the fog mode to use
  24861. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24862. */
  24863. set: function (value) {
  24864. if (this._fogMode === value) {
  24865. return;
  24866. }
  24867. this._fogMode = value;
  24868. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24874. get: function () {
  24875. return this._shadowsEnabled;
  24876. },
  24877. /**
  24878. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24879. */
  24880. set: function (value) {
  24881. if (this._shadowsEnabled === value) {
  24882. return;
  24883. }
  24884. this._shadowsEnabled = value;
  24885. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24886. },
  24887. enumerable: true,
  24888. configurable: true
  24889. });
  24890. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24891. get: function () {
  24892. return this._lightsEnabled;
  24893. },
  24894. /**
  24895. * Gets or sets a boolean indicating if lights are enabled on this scene
  24896. */
  24897. set: function (value) {
  24898. if (this._lightsEnabled === value) {
  24899. return;
  24900. }
  24901. this._lightsEnabled = value;
  24902. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24903. },
  24904. enumerable: true,
  24905. configurable: true
  24906. });
  24907. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24908. /** The default material used on meshes when no material is affected */
  24909. get: function () {
  24910. if (!this._defaultMaterial) {
  24911. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24912. }
  24913. return this._defaultMaterial;
  24914. },
  24915. /** The default material used on meshes when no material is affected */
  24916. set: function (value) {
  24917. this._defaultMaterial = value;
  24918. },
  24919. enumerable: true,
  24920. configurable: true
  24921. });
  24922. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24923. get: function () {
  24924. return this._texturesEnabled;
  24925. },
  24926. /**
  24927. * Gets or sets a boolean indicating if textures are enabled on this scene
  24928. */
  24929. set: function (value) {
  24930. if (this._texturesEnabled === value) {
  24931. return;
  24932. }
  24933. this._texturesEnabled = value;
  24934. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24935. },
  24936. enumerable: true,
  24937. configurable: true
  24938. });
  24939. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24940. get: function () {
  24941. return this._skeletonsEnabled;
  24942. },
  24943. /**
  24944. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24945. */
  24946. set: function (value) {
  24947. if (this._skeletonsEnabled === value) {
  24948. return;
  24949. }
  24950. this._skeletonsEnabled = value;
  24951. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24952. },
  24953. enumerable: true,
  24954. configurable: true
  24955. });
  24956. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24957. /** @hidden */
  24958. get: function () {
  24959. return this._alternateRendering;
  24960. },
  24961. enumerable: true,
  24962. configurable: true
  24963. });
  24964. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24965. /**
  24966. * Gets the list of frustum planes (built from the active camera)
  24967. */
  24968. get: function () {
  24969. return this._frustumPlanes;
  24970. },
  24971. enumerable: true,
  24972. configurable: true
  24973. });
  24974. /**
  24975. * Registers the transient components if needed.
  24976. */
  24977. Scene.prototype._registerTransientComponents = function () {
  24978. // Register components that have been associated lately to the scene.
  24979. if (this._transientComponents.length > 0) {
  24980. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24981. var component = _a[_i];
  24982. component.register();
  24983. }
  24984. this._transientComponents = [];
  24985. }
  24986. };
  24987. /**
  24988. * @hidden
  24989. * Add a component to the scene.
  24990. * Note that the ccomponent could be registered on th next frame if this is called after
  24991. * the register component stage.
  24992. * @param component Defines the component to add to the scene
  24993. */
  24994. Scene.prototype._addComponent = function (component) {
  24995. this._components.push(component);
  24996. this._transientComponents.push(component);
  24997. var serializableComponent = component;
  24998. if (serializableComponent.addFromContainer) {
  24999. this._serializableComponents.push(serializableComponent);
  25000. }
  25001. };
  25002. /**
  25003. * @hidden
  25004. * Gets a component from the scene.
  25005. * @param name defines the name of the component to retrieve
  25006. * @returns the component or null if not present
  25007. */
  25008. Scene.prototype._getComponent = function (name) {
  25009. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25010. var component = _a[_i];
  25011. if (component.name === name) {
  25012. return component;
  25013. }
  25014. }
  25015. return null;
  25016. };
  25017. /**
  25018. * @hidden
  25019. */
  25020. Scene.prototype._getDefaultMeshCandidates = function () {
  25021. this._defaultMeshCandidates.data = this.meshes;
  25022. this._defaultMeshCandidates.length = this.meshes.length;
  25023. return this._defaultMeshCandidates;
  25024. };
  25025. /**
  25026. * @hidden
  25027. */
  25028. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  25029. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  25030. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  25031. return this._defaultSubMeshCandidates;
  25032. };
  25033. /**
  25034. * Sets the default candidate providers for the scene.
  25035. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  25036. * and getCollidingSubMeshCandidates to their default function
  25037. */
  25038. Scene.prototype.setDefaultCandidateProviders = function () {
  25039. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  25040. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25041. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25042. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  25043. };
  25044. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25045. /**
  25046. * Gets a boolean indicating if collisions are processed on a web worker
  25047. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25048. */
  25049. get: function () {
  25050. return this._workerCollisions;
  25051. },
  25052. set: function (enabled) {
  25053. if (!BABYLON.CollisionCoordinatorLegacy) {
  25054. return;
  25055. }
  25056. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25057. this._workerCollisions = enabled;
  25058. if (this.collisionCoordinator) {
  25059. this.collisionCoordinator.destroy();
  25060. }
  25061. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25062. this.collisionCoordinator.init(this);
  25063. },
  25064. enumerable: true,
  25065. configurable: true
  25066. });
  25067. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25068. /**
  25069. * Gets the mesh that is currently under the pointer
  25070. */
  25071. get: function () {
  25072. return this._pointerOverMesh;
  25073. },
  25074. enumerable: true,
  25075. configurable: true
  25076. });
  25077. Object.defineProperty(Scene.prototype, "pointerX", {
  25078. /**
  25079. * Gets the current on-screen X position of the pointer
  25080. */
  25081. get: function () {
  25082. return this._pointerX;
  25083. },
  25084. enumerable: true,
  25085. configurable: true
  25086. });
  25087. Object.defineProperty(Scene.prototype, "pointerY", {
  25088. /**
  25089. * Gets the current on-screen Y position of the pointer
  25090. */
  25091. get: function () {
  25092. return this._pointerY;
  25093. },
  25094. enumerable: true,
  25095. configurable: true
  25096. });
  25097. /**
  25098. * Gets the cached material (ie. the latest rendered one)
  25099. * @returns the cached material
  25100. */
  25101. Scene.prototype.getCachedMaterial = function () {
  25102. return this._cachedMaterial;
  25103. };
  25104. /**
  25105. * Gets the cached effect (ie. the latest rendered one)
  25106. * @returns the cached effect
  25107. */
  25108. Scene.prototype.getCachedEffect = function () {
  25109. return this._cachedEffect;
  25110. };
  25111. /**
  25112. * Gets the cached visibility state (ie. the latest rendered one)
  25113. * @returns the cached visibility state
  25114. */
  25115. Scene.prototype.getCachedVisibility = function () {
  25116. return this._cachedVisibility;
  25117. };
  25118. /**
  25119. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25120. * @param material defines the current material
  25121. * @param effect defines the current effect
  25122. * @param visibility defines the current visibility state
  25123. * @returns true if one parameter is not cached
  25124. */
  25125. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25126. if (visibility === void 0) { visibility = 1; }
  25127. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25128. };
  25129. /**
  25130. * Gets the engine associated with the scene
  25131. * @returns an Engine
  25132. */
  25133. Scene.prototype.getEngine = function () {
  25134. return this._engine;
  25135. };
  25136. /**
  25137. * Gets the total number of vertices rendered per frame
  25138. * @returns the total number of vertices rendered per frame
  25139. */
  25140. Scene.prototype.getTotalVertices = function () {
  25141. return this._totalVertices.current;
  25142. };
  25143. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25144. /**
  25145. * Gets the performance counter for total vertices
  25146. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25147. */
  25148. get: function () {
  25149. return this._totalVertices;
  25150. },
  25151. enumerable: true,
  25152. configurable: true
  25153. });
  25154. /**
  25155. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25156. * @returns the total number of active indices rendered per frame
  25157. */
  25158. Scene.prototype.getActiveIndices = function () {
  25159. return this._activeIndices.current;
  25160. };
  25161. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25162. /**
  25163. * Gets the performance counter for active indices
  25164. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25165. */
  25166. get: function () {
  25167. return this._activeIndices;
  25168. },
  25169. enumerable: true,
  25170. configurable: true
  25171. });
  25172. /**
  25173. * Gets the total number of active particles rendered per frame
  25174. * @returns the total number of active particles rendered per frame
  25175. */
  25176. Scene.prototype.getActiveParticles = function () {
  25177. return this._activeParticles.current;
  25178. };
  25179. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25180. /**
  25181. * Gets the performance counter for active particles
  25182. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25183. */
  25184. get: function () {
  25185. return this._activeParticles;
  25186. },
  25187. enumerable: true,
  25188. configurable: true
  25189. });
  25190. /**
  25191. * Gets the total number of active bones rendered per frame
  25192. * @returns the total number of active bones rendered per frame
  25193. */
  25194. Scene.prototype.getActiveBones = function () {
  25195. return this._activeBones.current;
  25196. };
  25197. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25198. /**
  25199. * Gets the performance counter for active bones
  25200. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25201. */
  25202. get: function () {
  25203. return this._activeBones;
  25204. },
  25205. enumerable: true,
  25206. configurable: true
  25207. });
  25208. /** @hidden */
  25209. Scene.prototype.getInterFramePerfCounter = function () {
  25210. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25211. return 0;
  25212. };
  25213. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25214. /** @hidden */
  25215. get: function () {
  25216. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25217. return null;
  25218. },
  25219. enumerable: true,
  25220. configurable: true
  25221. });
  25222. /** @hidden */
  25223. Scene.prototype.getLastFrameDuration = function () {
  25224. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25225. return 0;
  25226. };
  25227. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25228. /** @hidden */
  25229. get: function () {
  25230. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25231. return null;
  25232. },
  25233. enumerable: true,
  25234. configurable: true
  25235. });
  25236. /** @hidden */
  25237. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25238. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25239. return 0;
  25240. };
  25241. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25242. /** @hidden */
  25243. get: function () {
  25244. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25245. return null;
  25246. },
  25247. enumerable: true,
  25248. configurable: true
  25249. });
  25250. /**
  25251. * Gets the array of active meshes
  25252. * @returns an array of AbstractMesh
  25253. */
  25254. Scene.prototype.getActiveMeshes = function () {
  25255. return this._activeMeshes;
  25256. };
  25257. /** @hidden */
  25258. Scene.prototype.getRenderTargetsDuration = function () {
  25259. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25260. return 0;
  25261. };
  25262. /** @hidden */
  25263. Scene.prototype.getRenderDuration = function () {
  25264. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25265. return 0;
  25266. };
  25267. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25268. /** @hidden */
  25269. get: function () {
  25270. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25271. return null;
  25272. },
  25273. enumerable: true,
  25274. configurable: true
  25275. });
  25276. /** @hidden */
  25277. Scene.prototype.getParticlesDuration = function () {
  25278. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25279. return 0;
  25280. };
  25281. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25282. /** @hidden */
  25283. get: function () {
  25284. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25285. return null;
  25286. },
  25287. enumerable: true,
  25288. configurable: true
  25289. });
  25290. /** @hidden */
  25291. Scene.prototype.getSpritesDuration = function () {
  25292. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25293. return 0;
  25294. };
  25295. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25296. /** @hidden */
  25297. get: function () {
  25298. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25299. return null;
  25300. },
  25301. enumerable: true,
  25302. configurable: true
  25303. });
  25304. /**
  25305. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25306. * @returns a number
  25307. */
  25308. Scene.prototype.getAnimationRatio = function () {
  25309. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25310. };
  25311. /**
  25312. * Gets an unique Id for the current render phase
  25313. * @returns a number
  25314. */
  25315. Scene.prototype.getRenderId = function () {
  25316. return this._renderId;
  25317. };
  25318. /**
  25319. * Gets an unique Id for the current frame
  25320. * @returns a number
  25321. */
  25322. Scene.prototype.getFrameId = function () {
  25323. return this._frameId;
  25324. };
  25325. /** Call this function if you want to manually increment the render Id*/
  25326. Scene.prototype.incrementRenderId = function () {
  25327. this._renderId++;
  25328. };
  25329. Scene.prototype._updatePointerPosition = function (evt) {
  25330. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25331. if (!canvasRect) {
  25332. return;
  25333. }
  25334. this._pointerX = evt.clientX - canvasRect.left;
  25335. this._pointerY = evt.clientY - canvasRect.top;
  25336. this._unTranslatedPointerX = this._pointerX;
  25337. this._unTranslatedPointerY = this._pointerY;
  25338. };
  25339. Scene.prototype._createUbo = function () {
  25340. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25341. this._sceneUbo.addUniform("viewProjection", 16);
  25342. this._sceneUbo.addUniform("view", 16);
  25343. };
  25344. Scene.prototype._createAlternateUbo = function () {
  25345. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25346. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25347. this._alternateSceneUbo.addUniform("view", 16);
  25348. };
  25349. // Pointers handling
  25350. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25351. if (pointerInfo.pickInfo) {
  25352. if (!pointerInfo.pickInfo.ray) {
  25353. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25354. }
  25355. }
  25356. };
  25357. /**
  25358. * Use this method to simulate a pointer move on a mesh
  25359. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25360. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25361. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25362. * @returns the current scene
  25363. */
  25364. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25365. var evt = new PointerEvent("pointermove", pointerEventInit);
  25366. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25367. return this;
  25368. }
  25369. return this._processPointerMove(pickResult, evt);
  25370. };
  25371. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25372. var canvas = this._engine.getRenderingCanvas();
  25373. if (!canvas) {
  25374. return this;
  25375. }
  25376. // Restore pointer
  25377. canvas.style.cursor = this.defaultCursor;
  25378. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  25379. if (isMeshPicked) {
  25380. this.setPointerOverMesh(pickResult.pickedMesh);
  25381. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25382. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25383. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25384. }
  25385. else {
  25386. canvas.style.cursor = this.hoverCursor;
  25387. }
  25388. }
  25389. }
  25390. else {
  25391. this.setPointerOverMesh(null);
  25392. }
  25393. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  25394. var step = _a[_i];
  25395. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  25396. }
  25397. if (pickResult) {
  25398. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25399. if (this.onPointerMove) {
  25400. this.onPointerMove(evt, pickResult, type);
  25401. }
  25402. if (this.onPointerObservable.hasObservers()) {
  25403. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25404. this._setRayOnPointerInfo(pi);
  25405. this.onPointerObservable.notifyObservers(pi, type);
  25406. }
  25407. }
  25408. return this;
  25409. };
  25410. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25411. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25412. if (pickResult) {
  25413. pi.ray = pickResult.ray;
  25414. }
  25415. this.onPrePointerObservable.notifyObservers(pi, type);
  25416. if (pi.skipOnPointerObservable) {
  25417. return true;
  25418. }
  25419. else {
  25420. return false;
  25421. }
  25422. };
  25423. /**
  25424. * Use this method to simulate a pointer down on a mesh
  25425. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25426. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25427. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25428. * @returns the current scene
  25429. */
  25430. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25431. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25432. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25433. return this;
  25434. }
  25435. return this._processPointerDown(pickResult, evt);
  25436. };
  25437. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25438. var _this = this;
  25439. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25440. this._pickedDownMesh = pickResult.pickedMesh;
  25441. var actionManager = pickResult.pickedMesh.actionManager;
  25442. if (actionManager) {
  25443. if (actionManager.hasPickTriggers) {
  25444. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25445. switch (evt.button) {
  25446. case 0:
  25447. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25448. break;
  25449. case 1:
  25450. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25451. break;
  25452. case 2:
  25453. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25454. break;
  25455. }
  25456. }
  25457. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25458. window.setTimeout(function () {
  25459. 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);
  25460. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25461. if (_this._totalPointersPressed !== 0 &&
  25462. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25463. !_this._isPointerSwiping()) {
  25464. _this._startingPointerTime = 0;
  25465. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25466. }
  25467. }
  25468. }, Scene.LongPressDelay);
  25469. }
  25470. }
  25471. }
  25472. else {
  25473. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  25474. var step = _a[_i];
  25475. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25476. }
  25477. }
  25478. if (pickResult) {
  25479. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25480. if (this.onPointerDown) {
  25481. this.onPointerDown(evt, pickResult, type);
  25482. }
  25483. if (this.onPointerObservable.hasObservers()) {
  25484. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25485. this._setRayOnPointerInfo(pi);
  25486. this.onPointerObservable.notifyObservers(pi, type);
  25487. }
  25488. }
  25489. return this;
  25490. };
  25491. /**
  25492. * Use this method to simulate a pointer up on a mesh
  25493. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25494. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25495. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25496. * @returns the current scene
  25497. */
  25498. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25499. var evt = new PointerEvent("pointerup", pointerEventInit);
  25500. var clickInfo = new ClickInfo();
  25501. clickInfo.singleClick = true;
  25502. clickInfo.ignore = true;
  25503. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25504. return this;
  25505. }
  25506. return this._processPointerUp(pickResult, evt, clickInfo);
  25507. };
  25508. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25509. if (pickResult && pickResult && pickResult.pickedMesh) {
  25510. this._pickedUpMesh = pickResult.pickedMesh;
  25511. if (this._pickedDownMesh === this._pickedUpMesh) {
  25512. if (this.onPointerPick) {
  25513. this.onPointerPick(evt, pickResult);
  25514. }
  25515. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25516. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25517. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25518. this._setRayOnPointerInfo(pi);
  25519. this.onPointerObservable.notifyObservers(pi, type_1);
  25520. }
  25521. }
  25522. if (pickResult.pickedMesh.actionManager) {
  25523. if (clickInfo.ignore) {
  25524. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25525. }
  25526. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25527. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25528. }
  25529. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25530. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25531. }
  25532. }
  25533. }
  25534. else {
  25535. if (!clickInfo.ignore) {
  25536. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  25537. var step = _a[_i];
  25538. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  25539. }
  25540. }
  25541. }
  25542. if (this._pickedDownMesh &&
  25543. this._pickedDownMesh.actionManager &&
  25544. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25545. this._pickedDownMesh !== this._pickedUpMesh) {
  25546. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25547. }
  25548. var type = BABYLON.PointerEventTypes.POINTERUP;
  25549. if (this.onPointerObservable.hasObservers()) {
  25550. if (!clickInfo.ignore) {
  25551. if (!clickInfo.hasSwiped) {
  25552. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25553. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25554. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25555. this._setRayOnPointerInfo(pi);
  25556. this.onPointerObservable.notifyObservers(pi, type_2);
  25557. }
  25558. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25559. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25560. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25561. this._setRayOnPointerInfo(pi);
  25562. this.onPointerObservable.notifyObservers(pi, type_3);
  25563. }
  25564. }
  25565. }
  25566. else {
  25567. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25568. this._setRayOnPointerInfo(pi);
  25569. this.onPointerObservable.notifyObservers(pi, type);
  25570. }
  25571. }
  25572. if (this.onPointerUp) {
  25573. this.onPointerUp(evt, pickResult, type);
  25574. }
  25575. return this;
  25576. };
  25577. /**
  25578. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25579. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25580. * @returns true if the pointer was captured
  25581. */
  25582. Scene.prototype.isPointerCaptured = function (pointerId) {
  25583. if (pointerId === void 0) { pointerId = 0; }
  25584. return this._pointerCaptures[pointerId];
  25585. };
  25586. /** @hidden */
  25587. Scene.prototype._isPointerSwiping = function () {
  25588. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  25589. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  25590. };
  25591. /**
  25592. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25593. * @param attachUp defines if you want to attach events to pointerup
  25594. * @param attachDown defines if you want to attach events to pointerdown
  25595. * @param attachMove defines if you want to attach events to pointermove
  25596. */
  25597. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25598. var _this = this;
  25599. if (attachUp === void 0) { attachUp = true; }
  25600. if (attachDown === void 0) { attachDown = true; }
  25601. if (attachMove === void 0) { attachMove = true; }
  25602. this._initActionManager = function (act, clickInfo) {
  25603. if (!_this._meshPickProceed) {
  25604. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25605. _this._currentPickResult = pickResult;
  25606. if (pickResult) {
  25607. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25608. }
  25609. _this._meshPickProceed = true;
  25610. }
  25611. return act;
  25612. };
  25613. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25614. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25615. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25616. btn !== _this._previousButtonPressed) {
  25617. _this._doubleClickOccured = false;
  25618. clickInfo.singleClick = true;
  25619. clickInfo.ignore = false;
  25620. cb(clickInfo, _this._currentPickResult);
  25621. }
  25622. };
  25623. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25624. var clickInfo = new ClickInfo();
  25625. _this._currentPickResult = null;
  25626. var act = null;
  25627. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25628. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25629. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25630. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25631. act = _this._initActionManager(act, clickInfo);
  25632. if (act)
  25633. checkPicking = act.hasPickTriggers;
  25634. }
  25635. if (checkPicking) {
  25636. var btn = evt.button;
  25637. clickInfo.hasSwiped = _this._isPointerSwiping();
  25638. if (!clickInfo.hasSwiped) {
  25639. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25640. if (!checkSingleClickImmediately) {
  25641. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25642. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25643. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25644. act = _this._initActionManager(act, clickInfo);
  25645. if (act)
  25646. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25647. }
  25648. }
  25649. if (checkSingleClickImmediately) {
  25650. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25651. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25652. btn !== _this._previousButtonPressed) {
  25653. clickInfo.singleClick = true;
  25654. cb(clickInfo, _this._currentPickResult);
  25655. }
  25656. }
  25657. // at least one double click is required to be check and exclusive double click is enabled
  25658. else {
  25659. // wait that no double click has been raised during the double click delay
  25660. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25661. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25662. }
  25663. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25664. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25665. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25666. act = _this._initActionManager(act, clickInfo);
  25667. if (act)
  25668. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25669. }
  25670. if (checkDoubleClick) {
  25671. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25672. if (btn === _this._previousButtonPressed &&
  25673. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25674. !_this._doubleClickOccured) {
  25675. // pointer has not moved for 2 clicks, it's a double click
  25676. if (!clickInfo.hasSwiped &&
  25677. !_this._isPointerSwiping()) {
  25678. _this._previousStartingPointerTime = 0;
  25679. _this._doubleClickOccured = true;
  25680. clickInfo.doubleClick = true;
  25681. clickInfo.ignore = false;
  25682. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25683. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25684. }
  25685. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25686. cb(clickInfo, _this._currentPickResult);
  25687. }
  25688. // if the two successive clicks are too far, it's just two simple clicks
  25689. else {
  25690. _this._doubleClickOccured = false;
  25691. _this._previousStartingPointerTime = _this._startingPointerTime;
  25692. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25693. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25694. _this._previousButtonPressed = btn;
  25695. if (Scene.ExclusiveDoubleClickMode) {
  25696. if (_this._previousDelayedSimpleClickTimeout) {
  25697. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25698. }
  25699. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25700. cb(clickInfo, _this._previousPickResult);
  25701. }
  25702. else {
  25703. cb(clickInfo, _this._currentPickResult);
  25704. }
  25705. }
  25706. }
  25707. // just the first click of the double has been raised
  25708. else {
  25709. _this._doubleClickOccured = false;
  25710. _this._previousStartingPointerTime = _this._startingPointerTime;
  25711. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25712. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25713. _this._previousButtonPressed = btn;
  25714. }
  25715. }
  25716. }
  25717. }
  25718. clickInfo.ignore = true;
  25719. cb(clickInfo, _this._currentPickResult);
  25720. };
  25721. this._onPointerMove = function (evt) {
  25722. _this._updatePointerPosition(evt);
  25723. // PreObservable support
  25724. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25725. return;
  25726. }
  25727. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25728. return;
  25729. }
  25730. if (!_this.pointerMovePredicate) {
  25731. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25732. }
  25733. // Meshes
  25734. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25735. _this._processPointerMove(pickResult, evt);
  25736. };
  25737. this._onPointerDown = function (evt) {
  25738. _this._totalPointersPressed++;
  25739. _this._pickedDownMesh = null;
  25740. _this._meshPickProceed = false;
  25741. _this._updatePointerPosition(evt);
  25742. if (_this.preventDefaultOnPointerDown && canvas) {
  25743. evt.preventDefault();
  25744. canvas.focus();
  25745. }
  25746. // PreObservable support
  25747. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25748. return;
  25749. }
  25750. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25751. return;
  25752. }
  25753. _this._pointerCaptures[evt.pointerId] = true;
  25754. _this._startingPointerPosition.x = _this._pointerX;
  25755. _this._startingPointerPosition.y = _this._pointerY;
  25756. _this._startingPointerTime = Date.now();
  25757. if (!_this.pointerDownPredicate) {
  25758. _this.pointerDownPredicate = function (mesh) {
  25759. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25760. };
  25761. }
  25762. // Meshes
  25763. _this._pickedDownMesh = null;
  25764. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25765. _this._processPointerDown(pickResult, evt);
  25766. };
  25767. this._onPointerUp = function (evt) {
  25768. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25769. return; // So we need to test it the pointer down was pressed before.
  25770. }
  25771. _this._totalPointersPressed--;
  25772. _this._pickedUpMesh = null;
  25773. _this._meshPickProceed = false;
  25774. _this._updatePointerPosition(evt);
  25775. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25776. // PreObservable support
  25777. if (_this.onPrePointerObservable.hasObservers()) {
  25778. if (!clickInfo.ignore) {
  25779. if (!clickInfo.hasSwiped) {
  25780. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25781. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25782. return;
  25783. }
  25784. }
  25785. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25786. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25787. return;
  25788. }
  25789. }
  25790. }
  25791. }
  25792. else {
  25793. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25794. return;
  25795. }
  25796. }
  25797. }
  25798. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25799. return;
  25800. }
  25801. _this._pointerCaptures[evt.pointerId] = false;
  25802. if (!_this.pointerUpPredicate) {
  25803. _this.pointerUpPredicate = function (mesh) {
  25804. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25805. };
  25806. }
  25807. // Meshes
  25808. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25809. _this._initActionManager(null, clickInfo);
  25810. }
  25811. if (!pickResult) {
  25812. pickResult = _this._currentPickResult;
  25813. }
  25814. _this._processPointerUp(pickResult, evt, clickInfo);
  25815. _this._previousPickResult = _this._currentPickResult;
  25816. });
  25817. };
  25818. this._onKeyDown = function (evt) {
  25819. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25820. if (_this.onPreKeyboardObservable.hasObservers()) {
  25821. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25822. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25823. if (pi.skipOnPointerObservable) {
  25824. return;
  25825. }
  25826. }
  25827. if (_this.onKeyboardObservable.hasObservers()) {
  25828. var pi = new BABYLON.KeyboardInfo(type, evt);
  25829. _this.onKeyboardObservable.notifyObservers(pi, type);
  25830. }
  25831. if (_this.actionManager) {
  25832. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25833. }
  25834. };
  25835. this._onKeyUp = function (evt) {
  25836. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25837. if (_this.onPreKeyboardObservable.hasObservers()) {
  25838. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25839. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25840. if (pi.skipOnPointerObservable) {
  25841. return;
  25842. }
  25843. }
  25844. if (_this.onKeyboardObservable.hasObservers()) {
  25845. var pi = new BABYLON.KeyboardInfo(type, evt);
  25846. _this.onKeyboardObservable.notifyObservers(pi, type);
  25847. }
  25848. if (_this.actionManager) {
  25849. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25850. }
  25851. };
  25852. var engine = this.getEngine();
  25853. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25854. if (!canvas) {
  25855. return;
  25856. }
  25857. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25858. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25859. });
  25860. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25861. if (!canvas) {
  25862. return;
  25863. }
  25864. canvas.removeEventListener("keydown", _this._onKeyDown);
  25865. canvas.removeEventListener("keyup", _this._onKeyUp);
  25866. });
  25867. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25868. var canvas = this._engine.getRenderingCanvas();
  25869. if (!canvas) {
  25870. return;
  25871. }
  25872. if (attachMove) {
  25873. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25874. // Wheel
  25875. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25876. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25877. }
  25878. if (attachDown) {
  25879. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25880. }
  25881. if (attachUp) {
  25882. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25883. }
  25884. canvas.tabIndex = 1;
  25885. };
  25886. /** Detaches all event handlers*/
  25887. Scene.prototype.detachControl = function () {
  25888. var engine = this.getEngine();
  25889. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25890. var canvas = engine.getRenderingCanvas();
  25891. if (!canvas) {
  25892. return;
  25893. }
  25894. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25895. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25896. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25897. if (this._onCanvasBlurObserver) {
  25898. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25899. }
  25900. if (this._onCanvasFocusObserver) {
  25901. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25902. }
  25903. // Wheel
  25904. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25905. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25906. // Keyboard
  25907. canvas.removeEventListener("keydown", this._onKeyDown);
  25908. canvas.removeEventListener("keyup", this._onKeyUp);
  25909. // Observables
  25910. this.onKeyboardObservable.clear();
  25911. this.onPreKeyboardObservable.clear();
  25912. this.onPointerObservable.clear();
  25913. this.onPrePointerObservable.clear();
  25914. };
  25915. /**
  25916. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25917. * Delay loaded resources are not taking in account
  25918. * @return true if all required resources are ready
  25919. */
  25920. Scene.prototype.isReady = function () {
  25921. if (this._isDisposed) {
  25922. return false;
  25923. }
  25924. if (this._pendingData.length > 0) {
  25925. return false;
  25926. }
  25927. var index;
  25928. var engine = this.getEngine();
  25929. // Geometries
  25930. for (index = 0; index < this.geometries.length; index++) {
  25931. var geometry = this.geometries[index];
  25932. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25933. return false;
  25934. }
  25935. }
  25936. // Meshes
  25937. for (index = 0; index < this.meshes.length; index++) {
  25938. var mesh = this.meshes[index];
  25939. if (!mesh.isEnabled()) {
  25940. continue;
  25941. }
  25942. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25943. continue;
  25944. }
  25945. if (!mesh.isReady(true)) {
  25946. return false;
  25947. }
  25948. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25949. // Is Ready For Mesh
  25950. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25951. var step = _a[_i];
  25952. if (!step.action(mesh, hardwareInstancedRendering)) {
  25953. return false;
  25954. }
  25955. }
  25956. }
  25957. // Post-processes
  25958. if (this.activeCameras && this.activeCameras.length > 0) {
  25959. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25960. var camera = _c[_b];
  25961. if (!camera.isReady(true)) {
  25962. return false;
  25963. }
  25964. }
  25965. }
  25966. else if (this.activeCamera) {
  25967. if (!this.activeCamera.isReady(true)) {
  25968. return false;
  25969. }
  25970. }
  25971. // Particles
  25972. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25973. var particleSystem = _e[_d];
  25974. if (!particleSystem.isReady()) {
  25975. return false;
  25976. }
  25977. }
  25978. return true;
  25979. };
  25980. /** Resets all cached information relative to material (including effect and visibility) */
  25981. Scene.prototype.resetCachedMaterial = function () {
  25982. this._cachedMaterial = null;
  25983. this._cachedEffect = null;
  25984. this._cachedVisibility = null;
  25985. };
  25986. /**
  25987. * Registers a function to be called before every frame render
  25988. * @param func defines the function to register
  25989. */
  25990. Scene.prototype.registerBeforeRender = function (func) {
  25991. this.onBeforeRenderObservable.add(func);
  25992. };
  25993. /**
  25994. * Unregisters a function called before every frame render
  25995. * @param func defines the function to unregister
  25996. */
  25997. Scene.prototype.unregisterBeforeRender = function (func) {
  25998. this.onBeforeRenderObservable.removeCallback(func);
  25999. };
  26000. /**
  26001. * Registers a function to be called after every frame render
  26002. * @param func defines the function to register
  26003. */
  26004. Scene.prototype.registerAfterRender = function (func) {
  26005. this.onAfterRenderObservable.add(func);
  26006. };
  26007. /**
  26008. * Unregisters a function called after every frame render
  26009. * @param func defines the function to unregister
  26010. */
  26011. Scene.prototype.unregisterAfterRender = function (func) {
  26012. this.onAfterRenderObservable.removeCallback(func);
  26013. };
  26014. Scene.prototype._executeOnceBeforeRender = function (func) {
  26015. var _this = this;
  26016. var execFunc = function () {
  26017. func();
  26018. setTimeout(function () {
  26019. _this.unregisterBeforeRender(execFunc);
  26020. });
  26021. };
  26022. this.registerBeforeRender(execFunc);
  26023. };
  26024. /**
  26025. * The provided function will run before render once and will be disposed afterwards.
  26026. * A timeout delay can be provided so that the function will be executed in N ms.
  26027. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26028. * @param func The function to be executed.
  26029. * @param timeout optional delay in ms
  26030. */
  26031. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26032. var _this = this;
  26033. if (timeout !== undefined) {
  26034. setTimeout(function () {
  26035. _this._executeOnceBeforeRender(func);
  26036. }, timeout);
  26037. }
  26038. else {
  26039. this._executeOnceBeforeRender(func);
  26040. }
  26041. };
  26042. /** @hidden */
  26043. Scene.prototype._addPendingData = function (data) {
  26044. this._pendingData.push(data);
  26045. };
  26046. /** @hidden */
  26047. Scene.prototype._removePendingData = function (data) {
  26048. var wasLoading = this.isLoading;
  26049. var index = this._pendingData.indexOf(data);
  26050. if (index !== -1) {
  26051. this._pendingData.splice(index, 1);
  26052. }
  26053. if (wasLoading && !this.isLoading) {
  26054. this.onDataLoadedObservable.notifyObservers(this);
  26055. }
  26056. };
  26057. /**
  26058. * Returns the number of items waiting to be loaded
  26059. * @returns the number of items waiting to be loaded
  26060. */
  26061. Scene.prototype.getWaitingItemsCount = function () {
  26062. return this._pendingData.length;
  26063. };
  26064. Object.defineProperty(Scene.prototype, "isLoading", {
  26065. /**
  26066. * Returns a boolean indicating if the scene is still loading data
  26067. */
  26068. get: function () {
  26069. return this._pendingData.length > 0;
  26070. },
  26071. enumerable: true,
  26072. configurable: true
  26073. });
  26074. /**
  26075. * Registers a function to be executed when the scene is ready
  26076. * @param {Function} func - the function to be executed
  26077. */
  26078. Scene.prototype.executeWhenReady = function (func) {
  26079. var _this = this;
  26080. this.onReadyObservable.add(func);
  26081. if (this._executeWhenReadyTimeoutId !== -1) {
  26082. return;
  26083. }
  26084. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26085. _this._checkIsReady();
  26086. }, 150);
  26087. };
  26088. /**
  26089. * Returns a promise that resolves when the scene is ready
  26090. * @returns A promise that resolves when the scene is ready
  26091. */
  26092. Scene.prototype.whenReadyAsync = function () {
  26093. var _this = this;
  26094. return new Promise(function (resolve) {
  26095. _this.executeWhenReady(function () {
  26096. resolve();
  26097. });
  26098. });
  26099. };
  26100. /** @hidden */
  26101. Scene.prototype._checkIsReady = function () {
  26102. var _this = this;
  26103. this._registerTransientComponents();
  26104. if (this.isReady()) {
  26105. this.onReadyObservable.notifyObservers(this);
  26106. this.onReadyObservable.clear();
  26107. this._executeWhenReadyTimeoutId = -1;
  26108. return;
  26109. }
  26110. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26111. _this._checkIsReady();
  26112. }, 150);
  26113. };
  26114. // Animations
  26115. /**
  26116. * Will start the animation sequence of a given target
  26117. * @param target defines the target
  26118. * @param from defines from which frame should animation start
  26119. * @param to defines until which frame should animation run.
  26120. * @param weight defines the weight to apply to the animation (1.0 by default)
  26121. * @param loop defines if the animation loops
  26122. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26123. * @param onAnimationEnd defines the function to be executed when the animation ends
  26124. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26125. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26126. * @returns the animatable object created for this animation
  26127. */
  26128. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26129. if (weight === void 0) { weight = 1.0; }
  26130. if (speedRatio === void 0) { speedRatio = 1.0; }
  26131. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26132. returnedAnimatable.weight = weight;
  26133. return returnedAnimatable;
  26134. };
  26135. /**
  26136. * Will start the animation sequence of a given target
  26137. * @param target defines the target
  26138. * @param from defines from which frame should animation start
  26139. * @param to defines until which frame should animation run.
  26140. * @param loop defines if the animation loops
  26141. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26142. * @param onAnimationEnd defines the function to be executed when the animation ends
  26143. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26144. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26145. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26146. * @returns the animatable object created for this animation
  26147. */
  26148. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26149. if (speedRatio === void 0) { speedRatio = 1.0; }
  26150. if (stopCurrent === void 0) { stopCurrent = true; }
  26151. if (from > to && speedRatio > 0) {
  26152. speedRatio *= -1;
  26153. }
  26154. if (stopCurrent) {
  26155. this.stopAnimation(target, undefined, targetMask);
  26156. }
  26157. if (!animatable) {
  26158. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26159. }
  26160. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26161. // Local animations
  26162. if (target.animations && shouldRunTargetAnimations) {
  26163. animatable.appendAnimations(target, target.animations);
  26164. }
  26165. // Children animations
  26166. if (target.getAnimatables) {
  26167. var animatables = target.getAnimatables();
  26168. for (var index = 0; index < animatables.length; index++) {
  26169. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26170. }
  26171. }
  26172. animatable.reset();
  26173. return animatable;
  26174. };
  26175. /**
  26176. * Begin a new animation on a given node
  26177. * @param target defines the target where the animation will take place
  26178. * @param animations defines the list of animations to start
  26179. * @param from defines the initial value
  26180. * @param to defines the final value
  26181. * @param loop defines if you want animation to loop (off by default)
  26182. * @param speedRatio defines the speed ratio to apply to all animations
  26183. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26184. * @returns the list of created animatables
  26185. */
  26186. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26187. if (speedRatio === undefined) {
  26188. speedRatio = 1.0;
  26189. }
  26190. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26191. return animatable;
  26192. };
  26193. /**
  26194. * Begin a new animation on a given node and its hierarchy
  26195. * @param target defines the root node where the animation will take place
  26196. * @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.
  26197. * @param animations defines the list of animations to start
  26198. * @param from defines the initial value
  26199. * @param to defines the final value
  26200. * @param loop defines if you want animation to loop (off by default)
  26201. * @param speedRatio defines the speed ratio to apply to all animations
  26202. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26203. * @returns the list of animatables created for all nodes
  26204. */
  26205. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26206. var children = target.getDescendants(directDescendantsOnly);
  26207. var result = [];
  26208. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26209. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26210. var child = children_1[_i];
  26211. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26212. }
  26213. return result;
  26214. };
  26215. /**
  26216. * Gets the animatable associated with a specific target
  26217. * @param target defines the target of the animatable
  26218. * @returns the required animatable if found
  26219. */
  26220. Scene.prototype.getAnimatableByTarget = function (target) {
  26221. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26222. if (this._activeAnimatables[index].target === target) {
  26223. return this._activeAnimatables[index];
  26224. }
  26225. }
  26226. return null;
  26227. };
  26228. /**
  26229. * Gets all animatables associated with a given target
  26230. * @param target defines the target to look animatables for
  26231. * @returns an array of Animatables
  26232. */
  26233. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26234. var result = [];
  26235. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26236. if (this._activeAnimatables[index].target === target) {
  26237. result.push(this._activeAnimatables[index]);
  26238. }
  26239. }
  26240. return result;
  26241. };
  26242. Object.defineProperty(Scene.prototype, "animatables", {
  26243. /**
  26244. * Gets all animatable attached to the scene
  26245. */
  26246. get: function () {
  26247. return this._activeAnimatables;
  26248. },
  26249. enumerable: true,
  26250. configurable: true
  26251. });
  26252. /**
  26253. * Will stop the animation of the given target
  26254. * @param target - the target
  26255. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26256. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  26257. */
  26258. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26259. var animatables = this.getAllAnimatablesByTarget(target);
  26260. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26261. var animatable = animatables_1[_i];
  26262. animatable.stop(animationName, targetMask);
  26263. }
  26264. };
  26265. /**
  26266. * Stops and removes all animations that have been applied to the scene
  26267. */
  26268. Scene.prototype.stopAllAnimations = function () {
  26269. if (this._activeAnimatables) {
  26270. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26271. this._activeAnimatables[i].stop();
  26272. }
  26273. this._activeAnimatables = [];
  26274. }
  26275. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26276. var group = _a[_i];
  26277. group.stop();
  26278. }
  26279. };
  26280. Scene.prototype._animate = function () {
  26281. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26282. return;
  26283. }
  26284. // Getting time
  26285. var now = BABYLON.Tools.Now;
  26286. if (!this._animationTimeLast) {
  26287. if (this._pendingData.length > 0) {
  26288. return;
  26289. }
  26290. this._animationTimeLast = now;
  26291. }
  26292. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26293. this._animationTime += deltaTime;
  26294. this._animationTimeLast = now;
  26295. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26296. this._activeAnimatables[index]._animate(this._animationTime);
  26297. }
  26298. // Late animation bindings
  26299. this._processLateAnimationBindings();
  26300. };
  26301. /** @hidden */
  26302. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26303. var target = runtimeAnimation.target;
  26304. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26305. if (!target._lateAnimationHolders) {
  26306. target._lateAnimationHolders = {};
  26307. }
  26308. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26309. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26310. totalWeight: 0,
  26311. animations: [],
  26312. originalValue: originalValue
  26313. };
  26314. }
  26315. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26316. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26317. };
  26318. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26319. var normalizer = 1.0;
  26320. var finalPosition = BABYLON.Tmp.Vector3[0];
  26321. var finalScaling = BABYLON.Tmp.Vector3[1];
  26322. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26323. var startIndex = 0;
  26324. var originalAnimation = holder.animations[0];
  26325. var originalValue = holder.originalValue;
  26326. var scale = 1;
  26327. if (holder.totalWeight < 1.0) {
  26328. // We need to mix the original value in
  26329. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26330. scale = 1.0 - holder.totalWeight;
  26331. }
  26332. else {
  26333. startIndex = 1;
  26334. // We need to normalize the weights
  26335. normalizer = holder.totalWeight;
  26336. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26337. scale = originalAnimation.weight / normalizer;
  26338. if (scale == 1) {
  26339. return originalAnimation.currentValue;
  26340. }
  26341. }
  26342. finalScaling.scaleInPlace(scale);
  26343. finalPosition.scaleInPlace(scale);
  26344. finalQuaternion.scaleInPlace(scale);
  26345. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26346. var runtimeAnimation = holder.animations[animIndex];
  26347. var scale = runtimeAnimation.weight / normalizer;
  26348. var currentPosition = BABYLON.Tmp.Vector3[2];
  26349. var currentScaling = BABYLON.Tmp.Vector3[3];
  26350. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26351. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26352. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26353. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26354. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26355. }
  26356. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26357. return originalAnimation._workValue;
  26358. };
  26359. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  26360. var originalAnimation = holder.animations[0];
  26361. var originalValue = holder.originalValue;
  26362. if (holder.animations.length === 1) {
  26363. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  26364. return refQuaternion;
  26365. }
  26366. var normalizer = 1.0;
  26367. var quaternions;
  26368. var weights;
  26369. if (holder.totalWeight < 1.0) {
  26370. var scale = 1.0 - holder.totalWeight;
  26371. quaternions = [];
  26372. weights = [];
  26373. quaternions.push(originalValue);
  26374. weights.push(scale);
  26375. }
  26376. else {
  26377. if (holder.animations.length === 2) { // Slerp as soon as we can
  26378. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  26379. return refQuaternion;
  26380. }
  26381. quaternions = [];
  26382. weights = [];
  26383. normalizer = holder.totalWeight;
  26384. }
  26385. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26386. var runtimeAnimation = holder.animations[animIndex];
  26387. quaternions.push(runtimeAnimation.currentValue);
  26388. weights.push(runtimeAnimation.weight / normalizer);
  26389. }
  26390. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26391. var cumulativeAmount = 0;
  26392. var cumulativeQuaternion = null;
  26393. for (var index = 0; index < quaternions.length;) {
  26394. if (!cumulativeQuaternion) {
  26395. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  26396. cumulativeQuaternion = refQuaternion;
  26397. cumulativeAmount = weights[index] + weights[index + 1];
  26398. index += 2;
  26399. continue;
  26400. }
  26401. cumulativeAmount += weights[index];
  26402. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26403. index++;
  26404. }
  26405. return cumulativeQuaternion;
  26406. };
  26407. Scene.prototype._processLateAnimationBindings = function () {
  26408. if (!this._registeredForLateAnimationBindings.length) {
  26409. return;
  26410. }
  26411. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26412. var target = this._registeredForLateAnimationBindings.data[index];
  26413. for (var path in target._lateAnimationHolders) {
  26414. var holder = target._lateAnimationHolders[path];
  26415. var originalAnimation = holder.animations[0];
  26416. var originalValue = holder.originalValue;
  26417. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26418. var finalValue = target[path];
  26419. if (matrixDecomposeMode) {
  26420. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26421. }
  26422. else {
  26423. var quaternionMode = originalValue.w !== undefined;
  26424. if (quaternionMode) {
  26425. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  26426. }
  26427. else {
  26428. var startIndex = 0;
  26429. var normalizer = 1.0;
  26430. if (holder.totalWeight < 1.0) {
  26431. // We need to mix the original value in
  26432. if (originalValue.scale) {
  26433. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26434. }
  26435. else {
  26436. finalValue = originalValue * (1.0 - holder.totalWeight);
  26437. }
  26438. }
  26439. else {
  26440. // We need to normalize the weights
  26441. normalizer = holder.totalWeight;
  26442. var scale_1 = originalAnimation.weight / normalizer;
  26443. if (scale_1 !== 1) {
  26444. if (originalAnimation.currentValue.scale) {
  26445. finalValue = originalAnimation.currentValue.scale(scale_1);
  26446. }
  26447. else {
  26448. finalValue = originalAnimation.currentValue * scale_1;
  26449. }
  26450. }
  26451. else {
  26452. finalValue = originalAnimation.currentValue;
  26453. }
  26454. startIndex = 1;
  26455. }
  26456. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26457. var runtimeAnimation = holder.animations[animIndex];
  26458. var scale = runtimeAnimation.weight / normalizer;
  26459. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26460. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26461. }
  26462. else {
  26463. finalValue += runtimeAnimation.currentValue * scale;
  26464. }
  26465. }
  26466. }
  26467. }
  26468. target[path] = finalValue;
  26469. }
  26470. target._lateAnimationHolders = {};
  26471. }
  26472. this._registeredForLateAnimationBindings.reset();
  26473. };
  26474. // Matrix
  26475. /** @hidden */
  26476. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26477. this._useAlternateCameraConfiguration = active;
  26478. };
  26479. /**
  26480. * Gets the current view matrix
  26481. * @returns a Matrix
  26482. */
  26483. Scene.prototype.getViewMatrix = function () {
  26484. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26485. };
  26486. /**
  26487. * Gets the current projection matrix
  26488. * @returns a Matrix
  26489. */
  26490. Scene.prototype.getProjectionMatrix = function () {
  26491. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26492. };
  26493. /**
  26494. * Gets the current transform matrix
  26495. * @returns a Matrix made of View * Projection
  26496. */
  26497. Scene.prototype.getTransformMatrix = function () {
  26498. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26499. };
  26500. /**
  26501. * Sets the current transform matrix
  26502. * @param view defines the View matrix to use
  26503. * @param projection defines the Projection matrix to use
  26504. */
  26505. Scene.prototype.setTransformMatrix = function (view, projection) {
  26506. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26507. return;
  26508. }
  26509. this._viewUpdateFlag = view.updateFlag;
  26510. this._projectionUpdateFlag = projection.updateFlag;
  26511. this._viewMatrix = view;
  26512. this._projectionMatrix = projection;
  26513. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26514. // Update frustum
  26515. if (!this._frustumPlanes) {
  26516. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26517. }
  26518. else {
  26519. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26520. }
  26521. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26522. var otherCamera = this.activeCamera._alternateCamera;
  26523. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26524. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26525. }
  26526. if (this._sceneUbo.useUbo) {
  26527. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26528. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26529. this._sceneUbo.update();
  26530. }
  26531. };
  26532. /** @hidden */
  26533. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26534. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26535. return;
  26536. }
  26537. this._alternateViewUpdateFlag = view.updateFlag;
  26538. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26539. this._alternateViewMatrix = view;
  26540. this._alternateProjectionMatrix = projection;
  26541. if (!this._alternateTransformMatrix) {
  26542. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26543. }
  26544. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26545. if (!this._alternateSceneUbo) {
  26546. this._createAlternateUbo();
  26547. }
  26548. if (this._alternateSceneUbo.useUbo) {
  26549. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26550. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26551. this._alternateSceneUbo.update();
  26552. }
  26553. };
  26554. /**
  26555. * Gets the uniform buffer used to store scene data
  26556. * @returns a UniformBuffer
  26557. */
  26558. Scene.prototype.getSceneUniformBuffer = function () {
  26559. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26560. };
  26561. /**
  26562. * Gets an unique (relatively to the current scene) Id
  26563. * @returns an unique number for the scene
  26564. */
  26565. Scene.prototype.getUniqueId = function () {
  26566. var result = Scene._uniqueIdCounter;
  26567. Scene._uniqueIdCounter++;
  26568. return result;
  26569. };
  26570. /**
  26571. * Add a mesh to the list of scene's meshes
  26572. * @param newMesh defines the mesh to add
  26573. * @param recursive if all child meshes should also be added to the scene
  26574. */
  26575. Scene.prototype.addMesh = function (newMesh, recursive) {
  26576. var _this = this;
  26577. if (recursive === void 0) { recursive = false; }
  26578. this.meshes.push(newMesh);
  26579. //notify the collision coordinator
  26580. if (this.collisionCoordinator) {
  26581. this.collisionCoordinator.onMeshAdded(newMesh);
  26582. }
  26583. newMesh._resyncLightSources();
  26584. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26585. if (recursive) {
  26586. newMesh.getChildMeshes().forEach(function (m) {
  26587. _this.addMesh(m);
  26588. });
  26589. }
  26590. };
  26591. /**
  26592. * Remove a mesh for the list of scene's meshes
  26593. * @param toRemove defines the mesh to remove
  26594. * @param recursive if all child meshes should also be removed from the scene
  26595. * @returns the index where the mesh was in the mesh list
  26596. */
  26597. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26598. var _this = this;
  26599. if (recursive === void 0) { recursive = false; }
  26600. var index = this.meshes.indexOf(toRemove);
  26601. if (index !== -1) {
  26602. // Remove from the scene if mesh found
  26603. this.meshes.splice(index, 1);
  26604. }
  26605. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26606. if (recursive) {
  26607. toRemove.getChildMeshes().forEach(function (m) {
  26608. _this.removeMesh(m);
  26609. });
  26610. }
  26611. return index;
  26612. };
  26613. /**
  26614. * Add a transform node to the list of scene's transform nodes
  26615. * @param newTransformNode defines the transform node to add
  26616. */
  26617. Scene.prototype.addTransformNode = function (newTransformNode) {
  26618. this.transformNodes.push(newTransformNode);
  26619. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26620. };
  26621. /**
  26622. * Remove a transform node for the list of scene's transform nodes
  26623. * @param toRemove defines the transform node to remove
  26624. * @returns the index where the transform node was in the transform node list
  26625. */
  26626. Scene.prototype.removeTransformNode = function (toRemove) {
  26627. var index = this.transformNodes.indexOf(toRemove);
  26628. if (index !== -1) {
  26629. // Remove from the scene if found
  26630. this.transformNodes.splice(index, 1);
  26631. }
  26632. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26633. return index;
  26634. };
  26635. /**
  26636. * Remove a skeleton for the list of scene's skeletons
  26637. * @param toRemove defines the skeleton to remove
  26638. * @returns the index where the skeleton was in the skeleton list
  26639. */
  26640. Scene.prototype.removeSkeleton = function (toRemove) {
  26641. var index = this.skeletons.indexOf(toRemove);
  26642. if (index !== -1) {
  26643. // Remove from the scene if found
  26644. this.skeletons.splice(index, 1);
  26645. }
  26646. return index;
  26647. };
  26648. /**
  26649. * Remove a morph target for the list of scene's morph targets
  26650. * @param toRemove defines the morph target to remove
  26651. * @returns the index where the morph target was in the morph target list
  26652. */
  26653. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26654. var index = this.morphTargetManagers.indexOf(toRemove);
  26655. if (index !== -1) {
  26656. // Remove from the scene if found
  26657. this.morphTargetManagers.splice(index, 1);
  26658. }
  26659. return index;
  26660. };
  26661. /**
  26662. * Remove a light for the list of scene's lights
  26663. * @param toRemove defines the light to remove
  26664. * @returns the index where the light was in the light list
  26665. */
  26666. Scene.prototype.removeLight = function (toRemove) {
  26667. var index = this.lights.indexOf(toRemove);
  26668. if (index !== -1) {
  26669. // Remove from meshes
  26670. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26671. var mesh = _a[_i];
  26672. mesh._removeLightSource(toRemove);
  26673. }
  26674. // Remove from the scene if mesh found
  26675. this.lights.splice(index, 1);
  26676. this.sortLightsByPriority();
  26677. }
  26678. this.onLightRemovedObservable.notifyObservers(toRemove);
  26679. return index;
  26680. };
  26681. /**
  26682. * Remove a camera for the list of scene's cameras
  26683. * @param toRemove defines the camera to remove
  26684. * @returns the index where the camera was in the camera list
  26685. */
  26686. Scene.prototype.removeCamera = function (toRemove) {
  26687. var index = this.cameras.indexOf(toRemove);
  26688. if (index !== -1) {
  26689. // Remove from the scene if mesh found
  26690. this.cameras.splice(index, 1);
  26691. }
  26692. // Remove from activeCameras
  26693. var index2 = this.activeCameras.indexOf(toRemove);
  26694. if (index2 !== -1) {
  26695. // Remove from the scene if mesh found
  26696. this.activeCameras.splice(index2, 1);
  26697. }
  26698. // Reset the activeCamera
  26699. if (this.activeCamera === toRemove) {
  26700. if (this.cameras.length > 0) {
  26701. this.activeCamera = this.cameras[0];
  26702. }
  26703. else {
  26704. this.activeCamera = null;
  26705. }
  26706. }
  26707. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26708. return index;
  26709. };
  26710. /**
  26711. * Remove a particle system for the list of scene's particle systems
  26712. * @param toRemove defines the particle system to remove
  26713. * @returns the index where the particle system was in the particle system list
  26714. */
  26715. Scene.prototype.removeParticleSystem = function (toRemove) {
  26716. var index = this.particleSystems.indexOf(toRemove);
  26717. if (index !== -1) {
  26718. this.particleSystems.splice(index, 1);
  26719. }
  26720. return index;
  26721. };
  26722. /**
  26723. * Remove a animation for the list of scene's animations
  26724. * @param toRemove defines the animation to remove
  26725. * @returns the index where the animation was in the animation list
  26726. */
  26727. Scene.prototype.removeAnimation = function (toRemove) {
  26728. var index = this.animations.indexOf(toRemove);
  26729. if (index !== -1) {
  26730. this.animations.splice(index, 1);
  26731. }
  26732. return index;
  26733. };
  26734. /**
  26735. * Removes the given animation group from this scene.
  26736. * @param toRemove The animation group to remove
  26737. * @returns The index of the removed animation group
  26738. */
  26739. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26740. var index = this.animationGroups.indexOf(toRemove);
  26741. if (index !== -1) {
  26742. this.animationGroups.splice(index, 1);
  26743. }
  26744. return index;
  26745. };
  26746. /**
  26747. * Removes the given multi-material from this scene.
  26748. * @param toRemove The multi-material to remove
  26749. * @returns The index of the removed multi-material
  26750. */
  26751. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26752. var index = this.multiMaterials.indexOf(toRemove);
  26753. if (index !== -1) {
  26754. this.multiMaterials.splice(index, 1);
  26755. }
  26756. return index;
  26757. };
  26758. /**
  26759. * Removes the given material from this scene.
  26760. * @param toRemove The material to remove
  26761. * @returns The index of the removed material
  26762. */
  26763. Scene.prototype.removeMaterial = function (toRemove) {
  26764. var index = this.materials.indexOf(toRemove);
  26765. if (index !== -1) {
  26766. this.materials.splice(index, 1);
  26767. }
  26768. return index;
  26769. };
  26770. /**
  26771. * Removes the given action manager from this scene.
  26772. * @param toRemove The action manager to remove
  26773. * @returns The index of the removed action manager
  26774. */
  26775. Scene.prototype.removeActionManager = function (toRemove) {
  26776. var index = this.actionManagers.indexOf(toRemove);
  26777. if (index !== -1) {
  26778. this.actionManagers.splice(index, 1);
  26779. }
  26780. return index;
  26781. };
  26782. /**
  26783. * Removes the given texture from this scene.
  26784. * @param toRemove The texture to remove
  26785. * @returns The index of the removed texture
  26786. */
  26787. Scene.prototype.removeTexture = function (toRemove) {
  26788. var index = this.textures.indexOf(toRemove);
  26789. if (index !== -1) {
  26790. this.textures.splice(index, 1);
  26791. }
  26792. return index;
  26793. };
  26794. /**
  26795. * Adds the given light to this scene
  26796. * @param newLight The light to add
  26797. */
  26798. Scene.prototype.addLight = function (newLight) {
  26799. this.lights.push(newLight);
  26800. this.sortLightsByPriority();
  26801. // Add light to all meshes (To support if the light is removed and then readded)
  26802. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26803. var mesh = _a[_i];
  26804. if (mesh._lightSources.indexOf(newLight) === -1) {
  26805. mesh._lightSources.push(newLight);
  26806. mesh._resyncLightSources();
  26807. }
  26808. }
  26809. this.onNewLightAddedObservable.notifyObservers(newLight);
  26810. };
  26811. /**
  26812. * Sorts the list list based on light priorities
  26813. */
  26814. Scene.prototype.sortLightsByPriority = function () {
  26815. if (this.requireLightSorting) {
  26816. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26817. }
  26818. };
  26819. /**
  26820. * Adds the given camera to this scene
  26821. * @param newCamera The camera to add
  26822. */
  26823. Scene.prototype.addCamera = function (newCamera) {
  26824. this.cameras.push(newCamera);
  26825. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26826. };
  26827. /**
  26828. * Adds the given skeleton to this scene
  26829. * @param newSkeleton The skeleton to add
  26830. */
  26831. Scene.prototype.addSkeleton = function (newSkeleton) {
  26832. this.skeletons.push(newSkeleton);
  26833. };
  26834. /**
  26835. * Adds the given particle system to this scene
  26836. * @param newParticleSystem The particle system to add
  26837. */
  26838. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26839. this.particleSystems.push(newParticleSystem);
  26840. };
  26841. /**
  26842. * Adds the given animation to this scene
  26843. * @param newAnimation The animation to add
  26844. */
  26845. Scene.prototype.addAnimation = function (newAnimation) {
  26846. this.animations.push(newAnimation);
  26847. };
  26848. /**
  26849. * Adds the given animation group to this scene.
  26850. * @param newAnimationGroup The animation group to add
  26851. */
  26852. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26853. this.animationGroups.push(newAnimationGroup);
  26854. };
  26855. /**
  26856. * Adds the given multi-material to this scene
  26857. * @param newMultiMaterial The multi-material to add
  26858. */
  26859. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26860. this.multiMaterials.push(newMultiMaterial);
  26861. };
  26862. /**
  26863. * Adds the given material to this scene
  26864. * @param newMaterial The material to add
  26865. */
  26866. Scene.prototype.addMaterial = function (newMaterial) {
  26867. this.materials.push(newMaterial);
  26868. };
  26869. /**
  26870. * Adds the given morph target to this scene
  26871. * @param newMorphTargetManager The morph target to add
  26872. */
  26873. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26874. this.morphTargetManagers.push(newMorphTargetManager);
  26875. };
  26876. /**
  26877. * Adds the given geometry to this scene
  26878. * @param newGeometry The geometry to add
  26879. */
  26880. Scene.prototype.addGeometry = function (newGeometry) {
  26881. this.geometries.push(newGeometry);
  26882. };
  26883. /**
  26884. * Adds the given action manager to this scene
  26885. * @param newActionManager The action manager to add
  26886. */
  26887. Scene.prototype.addActionManager = function (newActionManager) {
  26888. this.actionManagers.push(newActionManager);
  26889. };
  26890. /**
  26891. * Adds the given texture to this scene.
  26892. * @param newTexture The texture to add
  26893. */
  26894. Scene.prototype.addTexture = function (newTexture) {
  26895. this.textures.push(newTexture);
  26896. };
  26897. /**
  26898. * Switch active camera
  26899. * @param newCamera defines the new active camera
  26900. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26901. */
  26902. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26903. if (attachControl === void 0) { attachControl = true; }
  26904. var canvas = this._engine.getRenderingCanvas();
  26905. if (!canvas) {
  26906. return;
  26907. }
  26908. if (this.activeCamera) {
  26909. this.activeCamera.detachControl(canvas);
  26910. }
  26911. this.activeCamera = newCamera;
  26912. if (attachControl) {
  26913. newCamera.attachControl(canvas);
  26914. }
  26915. };
  26916. /**
  26917. * sets the active camera of the scene using its ID
  26918. * @param id defines the camera's ID
  26919. * @return the new active camera or null if none found.
  26920. */
  26921. Scene.prototype.setActiveCameraByID = function (id) {
  26922. var camera = this.getCameraByID(id);
  26923. if (camera) {
  26924. this.activeCamera = camera;
  26925. return camera;
  26926. }
  26927. return null;
  26928. };
  26929. /**
  26930. * sets the active camera of the scene using its name
  26931. * @param name defines the camera's name
  26932. * @returns the new active camera or null if none found.
  26933. */
  26934. Scene.prototype.setActiveCameraByName = function (name) {
  26935. var camera = this.getCameraByName(name);
  26936. if (camera) {
  26937. this.activeCamera = camera;
  26938. return camera;
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * get an animation group using its name
  26944. * @param name defines the material's name
  26945. * @return the animation group or null if none found.
  26946. */
  26947. Scene.prototype.getAnimationGroupByName = function (name) {
  26948. for (var index = 0; index < this.animationGroups.length; index++) {
  26949. if (this.animationGroups[index].name === name) {
  26950. return this.animationGroups[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * get a material using its id
  26957. * @param id defines the material's ID
  26958. * @return the material or null if none found.
  26959. */
  26960. Scene.prototype.getMaterialByID = function (id) {
  26961. for (var index = 0; index < this.materials.length; index++) {
  26962. if (this.materials[index].id === id) {
  26963. return this.materials[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a material using its name
  26970. * @param name defines the material's name
  26971. * @return the material or null if none found.
  26972. */
  26973. Scene.prototype.getMaterialByName = function (name) {
  26974. for (var index = 0; index < this.materials.length; index++) {
  26975. if (this.materials[index].name === name) {
  26976. return this.materials[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Gets a camera using its id
  26983. * @param id defines the id to look for
  26984. * @returns the camera or null if not found
  26985. */
  26986. Scene.prototype.getCameraByID = function (id) {
  26987. for (var index = 0; index < this.cameras.length; index++) {
  26988. if (this.cameras[index].id === id) {
  26989. return this.cameras[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. /**
  26995. * Gets a camera using its unique id
  26996. * @param uniqueId defines the unique id to look for
  26997. * @returns the camera or null if not found
  26998. */
  26999. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27000. for (var index = 0; index < this.cameras.length; index++) {
  27001. if (this.cameras[index].uniqueId === uniqueId) {
  27002. return this.cameras[index];
  27003. }
  27004. }
  27005. return null;
  27006. };
  27007. /**
  27008. * Gets a camera using its name
  27009. * @param name defines the camera's name
  27010. * @return the camera or null if none found.
  27011. */
  27012. Scene.prototype.getCameraByName = function (name) {
  27013. for (var index = 0; index < this.cameras.length; index++) {
  27014. if (this.cameras[index].name === name) {
  27015. return this.cameras[index];
  27016. }
  27017. }
  27018. return null;
  27019. };
  27020. /**
  27021. * Gets a bone using its id
  27022. * @param id defines the bone's id
  27023. * @return the bone or null if not found
  27024. */
  27025. Scene.prototype.getBoneByID = function (id) {
  27026. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27027. var skeleton = this.skeletons[skeletonIndex];
  27028. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27029. if (skeleton.bones[boneIndex].id === id) {
  27030. return skeleton.bones[boneIndex];
  27031. }
  27032. }
  27033. }
  27034. return null;
  27035. };
  27036. /**
  27037. * Gets a bone using its id
  27038. * @param name defines the bone's name
  27039. * @return the bone or null if not found
  27040. */
  27041. Scene.prototype.getBoneByName = function (name) {
  27042. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27043. var skeleton = this.skeletons[skeletonIndex];
  27044. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27045. if (skeleton.bones[boneIndex].name === name) {
  27046. return skeleton.bones[boneIndex];
  27047. }
  27048. }
  27049. }
  27050. return null;
  27051. };
  27052. /**
  27053. * Gets a light node using its name
  27054. * @param name defines the the light's name
  27055. * @return the light or null if none found.
  27056. */
  27057. Scene.prototype.getLightByName = function (name) {
  27058. for (var index = 0; index < this.lights.length; index++) {
  27059. if (this.lights[index].name === name) {
  27060. return this.lights[index];
  27061. }
  27062. }
  27063. return null;
  27064. };
  27065. /**
  27066. * Gets a light node using its id
  27067. * @param id defines the light's id
  27068. * @return the light or null if none found.
  27069. */
  27070. Scene.prototype.getLightByID = function (id) {
  27071. for (var index = 0; index < this.lights.length; index++) {
  27072. if (this.lights[index].id === id) {
  27073. return this.lights[index];
  27074. }
  27075. }
  27076. return null;
  27077. };
  27078. /**
  27079. * Gets a light node using its scene-generated unique ID
  27080. * @param uniqueId defines the light's unique id
  27081. * @return the light or null if none found.
  27082. */
  27083. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27084. for (var index = 0; index < this.lights.length; index++) {
  27085. if (this.lights[index].uniqueId === uniqueId) {
  27086. return this.lights[index];
  27087. }
  27088. }
  27089. return null;
  27090. };
  27091. /**
  27092. * Gets a particle system by id
  27093. * @param id defines the particle system id
  27094. * @return the corresponding system or null if none found
  27095. */
  27096. Scene.prototype.getParticleSystemByID = function (id) {
  27097. for (var index = 0; index < this.particleSystems.length; index++) {
  27098. if (this.particleSystems[index].id === id) {
  27099. return this.particleSystems[index];
  27100. }
  27101. }
  27102. return null;
  27103. };
  27104. /**
  27105. * Gets a geometry using its ID
  27106. * @param id defines the geometry's id
  27107. * @return the geometry or null if none found.
  27108. */
  27109. Scene.prototype.getGeometryByID = function (id) {
  27110. for (var index = 0; index < this.geometries.length; index++) {
  27111. if (this.geometries[index].id === id) {
  27112. return this.geometries[index];
  27113. }
  27114. }
  27115. return null;
  27116. };
  27117. /**
  27118. * Add a new geometry to this scene
  27119. * @param geometry defines the geometry to be added to the scene.
  27120. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27121. * @return a boolean defining if the geometry was added or not
  27122. */
  27123. Scene.prototype.pushGeometry = function (geometry, force) {
  27124. if (!force && this.getGeometryByID(geometry.id)) {
  27125. return false;
  27126. }
  27127. this.geometries.push(geometry);
  27128. //notify the collision coordinator
  27129. if (this.collisionCoordinator) {
  27130. this.collisionCoordinator.onGeometryAdded(geometry);
  27131. }
  27132. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27133. return true;
  27134. };
  27135. /**
  27136. * Removes an existing geometry
  27137. * @param geometry defines the geometry to be removed from the scene
  27138. * @return a boolean defining if the geometry was removed or not
  27139. */
  27140. Scene.prototype.removeGeometry = function (geometry) {
  27141. var index = this.geometries.indexOf(geometry);
  27142. if (index > -1) {
  27143. this.geometries.splice(index, 1);
  27144. //notify the collision coordinator
  27145. if (this.collisionCoordinator) {
  27146. this.collisionCoordinator.onGeometryDeleted(geometry);
  27147. }
  27148. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27149. return true;
  27150. }
  27151. return false;
  27152. };
  27153. /**
  27154. * Gets the list of geometries attached to the scene
  27155. * @returns an array of Geometry
  27156. */
  27157. Scene.prototype.getGeometries = function () {
  27158. return this.geometries;
  27159. };
  27160. /**
  27161. * Gets the first added mesh found of a given ID
  27162. * @param id defines the id to search for
  27163. * @return the mesh found or null if not found at all
  27164. */
  27165. Scene.prototype.getMeshByID = function (id) {
  27166. for (var index = 0; index < this.meshes.length; index++) {
  27167. if (this.meshes[index].id === id) {
  27168. return this.meshes[index];
  27169. }
  27170. }
  27171. return null;
  27172. };
  27173. /**
  27174. * Gets a list of meshes using their id
  27175. * @param id defines the id to search for
  27176. * @returns a list of meshes
  27177. */
  27178. Scene.prototype.getMeshesByID = function (id) {
  27179. return this.meshes.filter(function (m) {
  27180. return m.id === id;
  27181. });
  27182. };
  27183. /**
  27184. * Gets the first added transform node found of a given ID
  27185. * @param id defines the id to search for
  27186. * @return the found transform node or null if not found at all.
  27187. */
  27188. Scene.prototype.getTransformNodeByID = function (id) {
  27189. for (var index = 0; index < this.transformNodes.length; index++) {
  27190. if (this.transformNodes[index].id === id) {
  27191. return this.transformNodes[index];
  27192. }
  27193. }
  27194. return null;
  27195. };
  27196. /**
  27197. * Gets a list of transform nodes using their id
  27198. * @param id defines the id to search for
  27199. * @returns a list of transform nodes
  27200. */
  27201. Scene.prototype.getTransformNodesByID = function (id) {
  27202. return this.transformNodes.filter(function (m) {
  27203. return m.id === id;
  27204. });
  27205. };
  27206. /**
  27207. * Gets a mesh with its auto-generated unique id
  27208. * @param uniqueId defines the unique id to search for
  27209. * @return the found mesh or null if not found at all.
  27210. */
  27211. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27212. for (var index = 0; index < this.meshes.length; index++) {
  27213. if (this.meshes[index].uniqueId === uniqueId) {
  27214. return this.meshes[index];
  27215. }
  27216. }
  27217. return null;
  27218. };
  27219. /**
  27220. * Gets a the last added mesh using a given id
  27221. * @param id defines the id to search for
  27222. * @return the found mesh or null if not found at all.
  27223. */
  27224. Scene.prototype.getLastMeshByID = function (id) {
  27225. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27226. if (this.meshes[index].id === id) {
  27227. return this.meshes[index];
  27228. }
  27229. }
  27230. return null;
  27231. };
  27232. /**
  27233. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27234. * @param id defines the id to search for
  27235. * @return the found node or null if not found at all
  27236. */
  27237. Scene.prototype.getLastEntryByID = function (id) {
  27238. var index;
  27239. for (index = this.meshes.length - 1; index >= 0; index--) {
  27240. if (this.meshes[index].id === id) {
  27241. return this.meshes[index];
  27242. }
  27243. }
  27244. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27245. if (this.transformNodes[index].id === id) {
  27246. return this.transformNodes[index];
  27247. }
  27248. }
  27249. for (index = this.cameras.length - 1; index >= 0; index--) {
  27250. if (this.cameras[index].id === id) {
  27251. return this.cameras[index];
  27252. }
  27253. }
  27254. for (index = this.lights.length - 1; index >= 0; index--) {
  27255. if (this.lights[index].id === id) {
  27256. return this.lights[index];
  27257. }
  27258. }
  27259. return null;
  27260. };
  27261. /**
  27262. * Gets a node (Mesh, Camera, Light) using a given id
  27263. * @param id defines the id to search for
  27264. * @return the found node or null if not found at all
  27265. */
  27266. Scene.prototype.getNodeByID = function (id) {
  27267. var mesh = this.getMeshByID(id);
  27268. if (mesh) {
  27269. return mesh;
  27270. }
  27271. var light = this.getLightByID(id);
  27272. if (light) {
  27273. return light;
  27274. }
  27275. var camera = this.getCameraByID(id);
  27276. if (camera) {
  27277. return camera;
  27278. }
  27279. var bone = this.getBoneByID(id);
  27280. return bone;
  27281. };
  27282. /**
  27283. * Gets a node (Mesh, Camera, Light) using a given name
  27284. * @param name defines the name to search for
  27285. * @return the found node or null if not found at all.
  27286. */
  27287. Scene.prototype.getNodeByName = function (name) {
  27288. var mesh = this.getMeshByName(name);
  27289. if (mesh) {
  27290. return mesh;
  27291. }
  27292. var light = this.getLightByName(name);
  27293. if (light) {
  27294. return light;
  27295. }
  27296. var camera = this.getCameraByName(name);
  27297. if (camera) {
  27298. return camera;
  27299. }
  27300. var bone = this.getBoneByName(name);
  27301. return bone;
  27302. };
  27303. /**
  27304. * Gets a mesh using a given name
  27305. * @param name defines the name to search for
  27306. * @return the found mesh or null if not found at all.
  27307. */
  27308. Scene.prototype.getMeshByName = function (name) {
  27309. for (var index = 0; index < this.meshes.length; index++) {
  27310. if (this.meshes[index].name === name) {
  27311. return this.meshes[index];
  27312. }
  27313. }
  27314. return null;
  27315. };
  27316. /**
  27317. * Gets a transform node using a given name
  27318. * @param name defines the name to search for
  27319. * @return the found transform node or null if not found at all.
  27320. */
  27321. Scene.prototype.getTransformNodeByName = function (name) {
  27322. for (var index = 0; index < this.transformNodes.length; index++) {
  27323. if (this.transformNodes[index].name === name) {
  27324. return this.transformNodes[index];
  27325. }
  27326. }
  27327. return null;
  27328. };
  27329. /**
  27330. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27331. * @param id defines the id to search for
  27332. * @return the found skeleton or null if not found at all.
  27333. */
  27334. Scene.prototype.getLastSkeletonByID = function (id) {
  27335. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27336. if (this.skeletons[index].id === id) {
  27337. return this.skeletons[index];
  27338. }
  27339. }
  27340. return null;
  27341. };
  27342. /**
  27343. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27344. * @param id defines the id to search for
  27345. * @return the found skeleton or null if not found at all.
  27346. */
  27347. Scene.prototype.getSkeletonById = function (id) {
  27348. for (var index = 0; index < this.skeletons.length; index++) {
  27349. if (this.skeletons[index].id === id) {
  27350. return this.skeletons[index];
  27351. }
  27352. }
  27353. return null;
  27354. };
  27355. /**
  27356. * Gets a skeleton using a given name
  27357. * @param name defines the name to search for
  27358. * @return the found skeleton or null if not found at all.
  27359. */
  27360. Scene.prototype.getSkeletonByName = function (name) {
  27361. for (var index = 0; index < this.skeletons.length; index++) {
  27362. if (this.skeletons[index].name === name) {
  27363. return this.skeletons[index];
  27364. }
  27365. }
  27366. return null;
  27367. };
  27368. /**
  27369. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27370. * @param id defines the id to search for
  27371. * @return the found morph target manager or null if not found at all.
  27372. */
  27373. Scene.prototype.getMorphTargetManagerById = function (id) {
  27374. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27375. if (this.morphTargetManagers[index].uniqueId === id) {
  27376. return this.morphTargetManagers[index];
  27377. }
  27378. }
  27379. return null;
  27380. };
  27381. /**
  27382. * Gets a boolean indicating if the given mesh is active
  27383. * @param mesh defines the mesh to look for
  27384. * @returns true if the mesh is in the active list
  27385. */
  27386. Scene.prototype.isActiveMesh = function (mesh) {
  27387. return (this._activeMeshes.indexOf(mesh) !== -1);
  27388. };
  27389. Object.defineProperty(Scene.prototype, "uid", {
  27390. /**
  27391. * Return a unique id as a string which can serve as an identifier for the scene
  27392. */
  27393. get: function () {
  27394. if (!this._uid) {
  27395. this._uid = BABYLON.Tools.RandomId();
  27396. }
  27397. return this._uid;
  27398. },
  27399. enumerable: true,
  27400. configurable: true
  27401. });
  27402. /**
  27403. * Add an externaly attached data from its key.
  27404. * This method call will fail and return false, if such key already exists.
  27405. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27406. * @param key the unique key that identifies the data
  27407. * @param data the data object to associate to the key for this Engine instance
  27408. * @return true if no such key were already present and the data was added successfully, false otherwise
  27409. */
  27410. Scene.prototype.addExternalData = function (key, data) {
  27411. if (!this._externalData) {
  27412. this._externalData = new BABYLON.StringDictionary();
  27413. }
  27414. return this._externalData.add(key, data);
  27415. };
  27416. /**
  27417. * Get an externaly attached data from its key
  27418. * @param key the unique key that identifies the data
  27419. * @return the associated data, if present (can be null), or undefined if not present
  27420. */
  27421. Scene.prototype.getExternalData = function (key) {
  27422. if (!this._externalData) {
  27423. return null;
  27424. }
  27425. return this._externalData.get(key);
  27426. };
  27427. /**
  27428. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27429. * @param key the unique key that identifies the data
  27430. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27431. * @return the associated data, can be null if the factory returned null.
  27432. */
  27433. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27434. if (!this._externalData) {
  27435. this._externalData = new BABYLON.StringDictionary();
  27436. }
  27437. return this._externalData.getOrAddWithFactory(key, factory);
  27438. };
  27439. /**
  27440. * Remove an externaly attached data from the Engine instance
  27441. * @param key the unique key that identifies the data
  27442. * @return true if the data was successfully removed, false if it doesn't exist
  27443. */
  27444. Scene.prototype.removeExternalData = function (key) {
  27445. return this._externalData.remove(key);
  27446. };
  27447. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27448. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27449. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27450. var step = _a[_i];
  27451. step.action(mesh, subMesh);
  27452. }
  27453. var material = subMesh.getMaterial();
  27454. if (material !== null && material !== undefined) {
  27455. // Render targets
  27456. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  27457. if (this._processedMaterials.indexOf(material) === -1) {
  27458. this._processedMaterials.push(material);
  27459. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27460. }
  27461. }
  27462. // Dispatch
  27463. this._activeIndices.addCount(subMesh.indexCount, false);
  27464. this._renderingManager.dispatch(subMesh, mesh, material);
  27465. }
  27466. }
  27467. };
  27468. /**
  27469. * Clear the processed materials smart array preventing retention point in material dispose.
  27470. */
  27471. Scene.prototype.freeProcessedMaterials = function () {
  27472. this._processedMaterials.dispose();
  27473. };
  27474. /**
  27475. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27476. */
  27477. Scene.prototype.freeActiveMeshes = function () {
  27478. this._activeMeshes.dispose();
  27479. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27480. this.activeCamera._activeMeshes.dispose();
  27481. }
  27482. if (this.activeCameras) {
  27483. for (var i = 0; i < this.activeCameras.length; i++) {
  27484. var activeCamera = this.activeCameras[i];
  27485. if (activeCamera && activeCamera._activeMeshes) {
  27486. activeCamera._activeMeshes.dispose();
  27487. }
  27488. }
  27489. }
  27490. };
  27491. /**
  27492. * Clear the info related to rendering groups preventing retention points during dispose.
  27493. */
  27494. Scene.prototype.freeRenderingGroups = function () {
  27495. if (this._renderingManager) {
  27496. this._renderingManager.freeRenderingGroups();
  27497. }
  27498. if (this.textures) {
  27499. for (var i = 0; i < this.textures.length; i++) {
  27500. var texture = this.textures[i];
  27501. if (texture && texture.renderList) {
  27502. texture.freeRenderingGroups();
  27503. }
  27504. }
  27505. }
  27506. };
  27507. /** @hidden */
  27508. Scene.prototype._isInIntermediateRendering = function () {
  27509. return this._intermediateRendering;
  27510. };
  27511. /**
  27512. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27513. * @returns the current scene
  27514. */
  27515. Scene.prototype.freezeActiveMeshes = function () {
  27516. if (!this.activeCamera) {
  27517. return this;
  27518. }
  27519. if (!this._frustumPlanes) {
  27520. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27521. }
  27522. this._evaluateActiveMeshes();
  27523. this._activeMeshesFrozen = true;
  27524. return this;
  27525. };
  27526. /**
  27527. * Use this function to restart evaluating active meshes on every frame
  27528. * @returns the current scene
  27529. */
  27530. Scene.prototype.unfreezeActiveMeshes = function () {
  27531. this._activeMeshesFrozen = false;
  27532. return this;
  27533. };
  27534. Scene.prototype._evaluateActiveMeshes = function () {
  27535. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27536. return;
  27537. }
  27538. if (!this.activeCamera) {
  27539. return;
  27540. }
  27541. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27542. this.activeCamera._activeMeshes.reset();
  27543. this._activeMeshes.reset();
  27544. this._renderingManager.reset();
  27545. this._processedMaterials.reset();
  27546. this._activeParticleSystems.reset();
  27547. this._activeSkeletons.reset();
  27548. this._softwareSkinnedMeshes.reset();
  27549. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27550. var step = _a[_i];
  27551. step.action();
  27552. }
  27553. // Determine mesh candidates
  27554. var meshes = this.getActiveMeshCandidates();
  27555. // Check each mesh
  27556. var len = meshes.length;
  27557. for (var i = 0; i < len; i++) {
  27558. var mesh = meshes.data[i];
  27559. if (mesh.isBlocked) {
  27560. continue;
  27561. }
  27562. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27563. if (!mesh.isReady() || !mesh.isEnabled()) {
  27564. continue;
  27565. }
  27566. mesh.computeWorldMatrix();
  27567. // Intersections
  27568. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  27569. this._meshesForIntersections.pushNoDuplicate(mesh);
  27570. }
  27571. // Switch to current LOD
  27572. var meshLOD = mesh.getLOD(this.activeCamera);
  27573. if (meshLOD === undefined || meshLOD === null) {
  27574. continue;
  27575. }
  27576. mesh._preActivate();
  27577. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27578. this._activeMeshes.push(mesh);
  27579. this.activeCamera._activeMeshes.push(mesh);
  27580. mesh._activate(this._renderId);
  27581. if (meshLOD !== mesh) {
  27582. meshLOD._activate(this._renderId);
  27583. }
  27584. this._activeMesh(mesh, meshLOD);
  27585. }
  27586. }
  27587. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27588. // Particle systems
  27589. if (this.particlesEnabled) {
  27590. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27591. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27592. var particleSystem = this.particleSystems[particleIndex];
  27593. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27594. continue;
  27595. }
  27596. var emitter = particleSystem.emitter;
  27597. if (!emitter.position || emitter.isEnabled()) {
  27598. this._activeParticleSystems.push(particleSystem);
  27599. particleSystem.animate();
  27600. this._renderingManager.dispatchParticles(particleSystem);
  27601. }
  27602. }
  27603. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27604. }
  27605. };
  27606. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27607. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27608. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27609. mesh.skeleton.prepare();
  27610. }
  27611. if (!mesh.computeBonesUsingShaders) {
  27612. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27613. }
  27614. }
  27615. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27616. var step = _a[_i];
  27617. step.action(sourceMesh, mesh);
  27618. }
  27619. if (mesh !== undefined && mesh !== null
  27620. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27621. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  27622. var len = subMeshes.length;
  27623. for (var i = 0; i < len; i++) {
  27624. var subMesh = subMeshes.data[i];
  27625. this._evaluateSubMesh(subMesh, mesh);
  27626. }
  27627. }
  27628. };
  27629. /**
  27630. * Update the transform matrix to update from the current active camera
  27631. * @param force defines a boolean used to force the update even if cache is up to date
  27632. */
  27633. Scene.prototype.updateTransformMatrix = function (force) {
  27634. if (!this.activeCamera) {
  27635. return;
  27636. }
  27637. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27638. };
  27639. /**
  27640. * 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)
  27641. * @param alternateCamera defines the camera to use
  27642. */
  27643. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27644. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27645. };
  27646. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27647. if (camera && camera._skipRendering) {
  27648. return;
  27649. }
  27650. var engine = this._engine;
  27651. this.activeCamera = camera;
  27652. if (!this.activeCamera)
  27653. throw new Error("Active camera not set");
  27654. // Viewport
  27655. engine.setViewport(this.activeCamera.viewport);
  27656. // Camera
  27657. this.resetCachedMaterial();
  27658. this._renderId++;
  27659. this.updateTransformMatrix();
  27660. if (camera._alternateCamera) {
  27661. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27662. this._alternateRendering = true;
  27663. }
  27664. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27665. // Meshes
  27666. this._evaluateActiveMeshes();
  27667. // Software skinning
  27668. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27669. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27670. mesh.applySkeleton(mesh.skeleton);
  27671. }
  27672. // Render targets
  27673. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27674. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27675. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27676. }
  27677. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27678. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27679. }
  27680. // Collects render targets from external components.
  27681. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  27682. var step = _a[_i];
  27683. step.action(this._renderTargets);
  27684. }
  27685. if (this.renderTargetsEnabled) {
  27686. this._intermediateRendering = true;
  27687. if (this._renderTargets.length > 0) {
  27688. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27689. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27690. var renderTarget = this._renderTargets.data[renderIndex];
  27691. if (renderTarget._shouldRender()) {
  27692. this._renderId++;
  27693. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27694. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27695. }
  27696. }
  27697. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27698. this._renderId++;
  27699. }
  27700. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  27701. var step = _c[_b];
  27702. step.action(this.activeCamera);
  27703. }
  27704. this._intermediateRendering = false;
  27705. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27706. }
  27707. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27708. // Prepare Frame
  27709. if (this.postProcessManager) {
  27710. this.postProcessManager._prepareFrame();
  27711. }
  27712. // Before Camera Draw
  27713. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  27714. var step = _e[_d];
  27715. step.action(this.activeCamera);
  27716. }
  27717. // Render
  27718. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27719. this._renderingManager.render(null, null, true, true);
  27720. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27721. // After Camera Draw
  27722. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  27723. var step = _g[_f];
  27724. step.action(this.activeCamera);
  27725. }
  27726. // Finalize frame
  27727. if (this.postProcessManager) {
  27728. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27729. }
  27730. // Reset some special arrays
  27731. this._renderTargets.reset();
  27732. this._alternateRendering = false;
  27733. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27734. };
  27735. Scene.prototype._processSubCameras = function (camera) {
  27736. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27737. this._renderForCamera(camera);
  27738. return;
  27739. }
  27740. // rig cameras
  27741. for (var index = 0; index < camera._rigCameras.length; index++) {
  27742. this._renderForCamera(camera._rigCameras[index], camera);
  27743. }
  27744. this.activeCamera = camera;
  27745. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27746. };
  27747. Scene.prototype._checkIntersections = function () {
  27748. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27749. var sourceMesh = this._meshesForIntersections.data[index];
  27750. if (!sourceMesh.actionManager) {
  27751. continue;
  27752. }
  27753. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27754. var action = sourceMesh.actionManager.actions[actionIndex];
  27755. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27756. var parameters = action.getTriggerParameter();
  27757. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27758. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27759. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27760. if (areIntersecting && currentIntersectionInProgress === -1) {
  27761. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27762. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27763. sourceMesh._intersectionsInProgress.push(otherMesh);
  27764. }
  27765. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27766. sourceMesh._intersectionsInProgress.push(otherMesh);
  27767. }
  27768. }
  27769. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27770. //They intersected, and now they don't.
  27771. //is this trigger an exit trigger? execute an event.
  27772. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27773. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27774. }
  27775. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27776. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27777. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27778. return otherMesh === parameterMesh;
  27779. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27780. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27781. }
  27782. }
  27783. }
  27784. }
  27785. }
  27786. };
  27787. /** @hidden */
  27788. Scene.prototype._advancePhysicsEngineStep = function (step) {
  27789. // Do nothing. Code will be replaced if physics engine component is referenced
  27790. };
  27791. /**
  27792. * Render the scene
  27793. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27794. */
  27795. Scene.prototype.render = function (updateCameras) {
  27796. if (updateCameras === void 0) { updateCameras = true; }
  27797. if (this.isDisposed) {
  27798. return;
  27799. }
  27800. this._frameId++;
  27801. // Register components that have been associated lately to the scene.
  27802. this._registerTransientComponents();
  27803. this._activeParticles.fetchNewFrame();
  27804. this._totalVertices.fetchNewFrame();
  27805. this._activeIndices.fetchNewFrame();
  27806. this._activeBones.fetchNewFrame();
  27807. this._meshesForIntersections.reset();
  27808. this.resetCachedMaterial();
  27809. this.onBeforeAnimationsObservable.notifyObservers(this);
  27810. // Actions
  27811. if (this.actionManager) {
  27812. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27813. }
  27814. if (this._engine.isDeterministicLockStep()) {
  27815. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27816. var defaultFPS = (60.0 / 1000.0);
  27817. var defaultFrameTime = this.getDeterministicFrameTime();
  27818. var stepsTaken = 0;
  27819. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27820. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27821. internalSteps = Math.min(internalSteps, maxSubSteps);
  27822. do {
  27823. this.onBeforeStepObservable.notifyObservers(this);
  27824. // Animations
  27825. this._animationRatio = defaultFrameTime * defaultFPS;
  27826. this._animate();
  27827. this.onAfterAnimationsObservable.notifyObservers(this);
  27828. // Physics
  27829. this._advancePhysicsEngineStep(defaultFrameTime);
  27830. this.onAfterStepObservable.notifyObservers(this);
  27831. this._currentStepId++;
  27832. stepsTaken++;
  27833. deltaTime -= defaultFrameTime;
  27834. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27835. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27836. }
  27837. else {
  27838. // Animations
  27839. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27840. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27841. this._animate();
  27842. this.onAfterAnimationsObservable.notifyObservers(this);
  27843. // Physics
  27844. this._advancePhysicsEngineStep(deltaTime);
  27845. }
  27846. // Before camera update steps
  27847. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27848. var step = _a[_i];
  27849. step.action();
  27850. }
  27851. // Update Cameras
  27852. if (updateCameras) {
  27853. if (this.activeCameras.length > 0) {
  27854. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27855. var camera = this.activeCameras[cameraIndex];
  27856. camera.update();
  27857. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27858. // rig cameras
  27859. for (var index = 0; index < camera._rigCameras.length; index++) {
  27860. camera._rigCameras[index].update();
  27861. }
  27862. }
  27863. }
  27864. }
  27865. else if (this.activeCamera) {
  27866. this.activeCamera.update();
  27867. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27868. // rig cameras
  27869. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27870. this.activeCamera._rigCameras[index].update();
  27871. }
  27872. }
  27873. }
  27874. }
  27875. // Before render
  27876. this.onBeforeRenderObservable.notifyObservers(this);
  27877. // Customs render targets
  27878. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27879. var engine = this.getEngine();
  27880. var currentActiveCamera = this.activeCamera;
  27881. if (this.renderTargetsEnabled) {
  27882. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27883. this._intermediateRendering = true;
  27884. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27885. var renderTarget = this.customRenderTargets[customIndex];
  27886. if (renderTarget._shouldRender()) {
  27887. this._renderId++;
  27888. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27889. if (!this.activeCamera)
  27890. throw new Error("Active camera not set");
  27891. // Viewport
  27892. engine.setViewport(this.activeCamera.viewport);
  27893. // Camera
  27894. this.updateTransformMatrix();
  27895. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27896. }
  27897. }
  27898. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27899. this._intermediateRendering = false;
  27900. this._renderId++;
  27901. }
  27902. // Restore back buffer
  27903. if (this.customRenderTargets.length > 0) {
  27904. engine.restoreDefaultFramebuffer();
  27905. }
  27906. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27907. this.activeCamera = currentActiveCamera;
  27908. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  27909. var step = _c[_b];
  27910. step.action();
  27911. }
  27912. // Clear
  27913. if (this.autoClearDepthAndStencil || this.autoClear) {
  27914. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27915. }
  27916. // Collects render targets from external components.
  27917. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  27918. var step = _e[_d];
  27919. step.action(this._renderTargets);
  27920. }
  27921. // Multi-cameras?
  27922. if (this.activeCameras.length > 0) {
  27923. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27924. if (cameraIndex > 0) {
  27925. this._engine.clear(null, false, true, true);
  27926. }
  27927. this._processSubCameras(this.activeCameras[cameraIndex]);
  27928. }
  27929. }
  27930. else {
  27931. if (!this.activeCamera) {
  27932. throw new Error("No camera defined");
  27933. }
  27934. this._processSubCameras(this.activeCamera);
  27935. }
  27936. // Intersection checks
  27937. this._checkIntersections();
  27938. // Executes the after render stage actions.
  27939. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  27940. var step = _g[_f];
  27941. step.action();
  27942. }
  27943. // After render
  27944. if (this.afterRender) {
  27945. this.afterRender();
  27946. }
  27947. this.onAfterRenderObservable.notifyObservers(this);
  27948. // Cleaning
  27949. if (this._toBeDisposed.length) {
  27950. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27951. var data = this._toBeDisposed[index];
  27952. if (data) {
  27953. data.dispose();
  27954. }
  27955. }
  27956. this._toBeDisposed = [];
  27957. }
  27958. if (this.dumpNextRenderTargets) {
  27959. this.dumpNextRenderTargets = false;
  27960. }
  27961. this._activeBones.addCount(0, true);
  27962. this._activeIndices.addCount(0, true);
  27963. this._activeParticles.addCount(0, true);
  27964. };
  27965. /**
  27966. * Freeze all materials
  27967. * A frozen material will not be updatable but should be faster to render
  27968. */
  27969. Scene.prototype.freezeMaterials = function () {
  27970. for (var i = 0; i < this.materials.length; i++) {
  27971. this.materials[i].freeze();
  27972. }
  27973. };
  27974. /**
  27975. * Unfreeze all materials
  27976. * A frozen material will not be updatable but should be faster to render
  27977. */
  27978. Scene.prototype.unfreezeMaterials = function () {
  27979. for (var i = 0; i < this.materials.length; i++) {
  27980. this.materials[i].unfreeze();
  27981. }
  27982. };
  27983. /**
  27984. * Releases all held ressources
  27985. */
  27986. Scene.prototype.dispose = function () {
  27987. this.beforeRender = null;
  27988. this.afterRender = null;
  27989. this.skeletons = [];
  27990. this.morphTargetManagers = [];
  27991. this._transientComponents = [];
  27992. this._isReadyForMeshStage.clear();
  27993. this._beforeEvaluateActiveMeshStage.clear();
  27994. this._evaluateSubMeshStage.clear();
  27995. this._activeMeshStage.clear();
  27996. this._cameraDrawRenderTargetStage.clear();
  27997. this._beforeCameraDrawStage.clear();
  27998. this._beforeRenderingGroupDrawStage.clear();
  27999. this._beforeRenderingMeshStage.clear();
  28000. this._afterRenderingMeshStage.clear();
  28001. this._afterRenderingGroupDrawStage.clear();
  28002. this._afterCameraDrawStage.clear();
  28003. this._afterRenderStage.clear();
  28004. this._beforeCameraUpdateStage.clear();
  28005. this._beforeClearStage.clear();
  28006. this._gatherRenderTargetsStage.clear();
  28007. this._gatherActiveCameraRenderTargetsStage.clear();
  28008. this._pointerMoveStage.clear();
  28009. this._pointerDownStage.clear();
  28010. this._pointerUpStage.clear();
  28011. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28012. var component = _a[_i];
  28013. component.dispose();
  28014. }
  28015. this.importedMeshesFiles = new Array();
  28016. this.stopAllAnimations();
  28017. this.resetCachedMaterial();
  28018. // Smart arrays
  28019. if (this.activeCamera) {
  28020. this.activeCamera._activeMeshes.dispose();
  28021. this.activeCamera = null;
  28022. }
  28023. this._activeMeshes.dispose();
  28024. this._renderingManager.dispose();
  28025. this._processedMaterials.dispose();
  28026. this._activeParticleSystems.dispose();
  28027. this._activeSkeletons.dispose();
  28028. this._softwareSkinnedMeshes.dispose();
  28029. this._renderTargets.dispose();
  28030. this._registeredForLateAnimationBindings.dispose();
  28031. this._meshesForIntersections.dispose();
  28032. this._toBeDisposed = [];
  28033. // Abort active requests
  28034. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28035. var request = _c[_b];
  28036. request.abort();
  28037. }
  28038. // Events
  28039. this.onDisposeObservable.notifyObservers(this);
  28040. this.onDisposeObservable.clear();
  28041. this.onBeforeRenderObservable.clear();
  28042. this.onAfterRenderObservable.clear();
  28043. this.onBeforeRenderTargetsRenderObservable.clear();
  28044. this.onAfterRenderTargetsRenderObservable.clear();
  28045. this.onAfterStepObservable.clear();
  28046. this.onBeforeStepObservable.clear();
  28047. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28048. this.onAfterActiveMeshesEvaluationObservable.clear();
  28049. this.onBeforeParticlesRenderingObservable.clear();
  28050. this.onAfterParticlesRenderingObservable.clear();
  28051. this.onBeforeDrawPhaseObservable.clear();
  28052. this.onAfterDrawPhaseObservable.clear();
  28053. this.onBeforeAnimationsObservable.clear();
  28054. this.onAfterAnimationsObservable.clear();
  28055. this.onDataLoadedObservable.clear();
  28056. this.onBeforeRenderingGroupObservable.clear();
  28057. this.onAfterRenderingGroupObservable.clear();
  28058. this.onMeshImportedObservable.clear();
  28059. this.detachControl();
  28060. // Detach cameras
  28061. var canvas = this._engine.getRenderingCanvas();
  28062. if (canvas) {
  28063. var index;
  28064. for (index = 0; index < this.cameras.length; index++) {
  28065. this.cameras[index].detachControl(canvas);
  28066. }
  28067. }
  28068. // Release animation groups
  28069. while (this.animationGroups.length) {
  28070. this.animationGroups[0].dispose();
  28071. }
  28072. // Release lights
  28073. while (this.lights.length) {
  28074. this.lights[0].dispose();
  28075. }
  28076. // Release meshes
  28077. while (this.meshes.length) {
  28078. this.meshes[0].dispose(true);
  28079. }
  28080. while (this.transformNodes.length) {
  28081. this.removeTransformNode(this.transformNodes[0]);
  28082. }
  28083. // Release cameras
  28084. while (this.cameras.length) {
  28085. this.cameras[0].dispose();
  28086. }
  28087. // Release materials
  28088. if (this.defaultMaterial) {
  28089. this.defaultMaterial.dispose();
  28090. }
  28091. while (this.multiMaterials.length) {
  28092. this.multiMaterials[0].dispose();
  28093. }
  28094. while (this.materials.length) {
  28095. this.materials[0].dispose();
  28096. }
  28097. // Release particles
  28098. while (this.particleSystems.length) {
  28099. this.particleSystems[0].dispose();
  28100. }
  28101. // Release postProcesses
  28102. while (this.postProcesses.length) {
  28103. this.postProcesses[0].dispose();
  28104. }
  28105. // Release textures
  28106. while (this.textures.length) {
  28107. this.textures[0].dispose();
  28108. }
  28109. // Release UBO
  28110. this._sceneUbo.dispose();
  28111. if (this._alternateSceneUbo) {
  28112. this._alternateSceneUbo.dispose();
  28113. }
  28114. // Post-processes
  28115. this.postProcessManager.dispose();
  28116. // Remove from engine
  28117. index = this._engine.scenes.indexOf(this);
  28118. if (index > -1) {
  28119. this._engine.scenes.splice(index, 1);
  28120. }
  28121. this._engine.wipeCaches(true);
  28122. this._isDisposed = true;
  28123. };
  28124. Object.defineProperty(Scene.prototype, "isDisposed", {
  28125. /**
  28126. * Gets if the scene is already disposed
  28127. */
  28128. get: function () {
  28129. return this._isDisposed;
  28130. },
  28131. enumerable: true,
  28132. configurable: true
  28133. });
  28134. /**
  28135. * Call this function to reduce memory footprint of the scene.
  28136. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28137. */
  28138. Scene.prototype.clearCachedVertexData = function () {
  28139. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28140. var mesh = this.meshes[meshIndex];
  28141. var geometry = mesh.geometry;
  28142. if (geometry) {
  28143. geometry._indices = [];
  28144. for (var vbName in geometry._vertexBuffers) {
  28145. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28146. continue;
  28147. }
  28148. geometry._vertexBuffers[vbName]._buffer._data = null;
  28149. }
  28150. }
  28151. }
  28152. };
  28153. /**
  28154. * This function will remove the local cached buffer data from texture.
  28155. * It will save memory but will prevent the texture from being rebuilt
  28156. */
  28157. Scene.prototype.cleanCachedTextureBuffer = function () {
  28158. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28159. var baseTexture = _a[_i];
  28160. var buffer = baseTexture._buffer;
  28161. if (buffer) {
  28162. baseTexture._buffer = null;
  28163. }
  28164. }
  28165. };
  28166. /**
  28167. * Get the world extend vectors with an optional filter
  28168. *
  28169. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28170. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28171. */
  28172. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28173. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28174. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28175. filterPredicate = filterPredicate || (function () { return true; });
  28176. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28177. mesh.computeWorldMatrix(true);
  28178. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28179. return;
  28180. }
  28181. var boundingInfo = mesh.getBoundingInfo();
  28182. var minBox = boundingInfo.boundingBox.minimumWorld;
  28183. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28184. BABYLON.Tools.CheckExtends(minBox, min, max);
  28185. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28186. });
  28187. return {
  28188. min: min,
  28189. max: max
  28190. };
  28191. };
  28192. // Picking
  28193. /**
  28194. * Creates a ray that can be used to pick in the scene
  28195. * @param x defines the x coordinate of the origin (on-screen)
  28196. * @param y defines the y coordinate of the origin (on-screen)
  28197. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28198. * @param camera defines the camera to use for the picking
  28199. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28200. * @returns a Ray
  28201. */
  28202. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28203. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28204. var result = BABYLON.Ray.Zero();
  28205. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28206. return result;
  28207. };
  28208. /**
  28209. * Creates a ray that can be used to pick in the scene
  28210. * @param x defines the x coordinate of the origin (on-screen)
  28211. * @param y defines the y coordinate of the origin (on-screen)
  28212. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28213. * @param result defines the ray where to store the picking ray
  28214. * @param camera defines the camera to use for the picking
  28215. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28216. * @returns the current scene
  28217. */
  28218. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28219. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28220. var engine = this._engine;
  28221. if (!camera) {
  28222. if (!this.activeCamera)
  28223. throw new Error("Active camera not set");
  28224. camera = this.activeCamera;
  28225. }
  28226. var cameraViewport = camera.viewport;
  28227. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28228. // Moving coordinates to local viewport world
  28229. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28230. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28231. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28232. return this;
  28233. };
  28234. /**
  28235. * Creates a ray that can be used to pick in the scene
  28236. * @param x defines the x coordinate of the origin (on-screen)
  28237. * @param y defines the y coordinate of the origin (on-screen)
  28238. * @param camera defines the camera to use for the picking
  28239. * @returns a Ray
  28240. */
  28241. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28242. var result = BABYLON.Ray.Zero();
  28243. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28244. return result;
  28245. };
  28246. /**
  28247. * Creates a ray that can be used to pick in the scene
  28248. * @param x defines the x coordinate of the origin (on-screen)
  28249. * @param y defines the y coordinate of the origin (on-screen)
  28250. * @param result defines the ray where to store the picking ray
  28251. * @param camera defines the camera to use for the picking
  28252. * @returns the current scene
  28253. */
  28254. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28255. if (!BABYLON.PickingInfo) {
  28256. return this;
  28257. }
  28258. var engine = this._engine;
  28259. if (!camera) {
  28260. if (!this.activeCamera)
  28261. throw new Error("Active camera not set");
  28262. camera = this.activeCamera;
  28263. }
  28264. var cameraViewport = camera.viewport;
  28265. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28266. var identity = BABYLON.Matrix.Identity();
  28267. // Moving coordinates to local viewport world
  28268. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28269. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28270. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28271. return this;
  28272. };
  28273. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28274. if (!BABYLON.PickingInfo) {
  28275. return null;
  28276. }
  28277. var pickingInfo = null;
  28278. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28279. var mesh = this.meshes[meshIndex];
  28280. if (predicate) {
  28281. if (!predicate(mesh)) {
  28282. continue;
  28283. }
  28284. }
  28285. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28286. continue;
  28287. }
  28288. var world = mesh.getWorldMatrix();
  28289. var ray = rayFunction(world);
  28290. var result = mesh.intersects(ray, fastCheck);
  28291. if (!result || !result.hit)
  28292. continue;
  28293. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28294. continue;
  28295. pickingInfo = result;
  28296. if (fastCheck) {
  28297. break;
  28298. }
  28299. }
  28300. return pickingInfo || new BABYLON.PickingInfo();
  28301. };
  28302. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28303. if (!BABYLON.PickingInfo) {
  28304. return null;
  28305. }
  28306. var pickingInfos = new Array();
  28307. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28308. var mesh = this.meshes[meshIndex];
  28309. if (predicate) {
  28310. if (!predicate(mesh)) {
  28311. continue;
  28312. }
  28313. }
  28314. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28315. continue;
  28316. }
  28317. var world = mesh.getWorldMatrix();
  28318. var ray = rayFunction(world);
  28319. var result = mesh.intersects(ray, false);
  28320. if (!result || !result.hit)
  28321. continue;
  28322. pickingInfos.push(result);
  28323. }
  28324. return pickingInfos;
  28325. };
  28326. /** Launch a ray to try to pick a mesh in the scene
  28327. * @param x position on screen
  28328. * @param y position on screen
  28329. * @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
  28330. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28331. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28332. * @returns a PickingInfo
  28333. */
  28334. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28335. var _this = this;
  28336. if (!BABYLON.PickingInfo) {
  28337. return null;
  28338. }
  28339. var result = this._internalPick(function (world) {
  28340. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28341. return _this._tempPickingRay;
  28342. }, predicate, fastCheck);
  28343. if (result) {
  28344. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28345. }
  28346. return result;
  28347. };
  28348. /** Use the given ray to pick a mesh in the scene
  28349. * @param ray The ray to use to pick meshes
  28350. * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
  28351. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28352. * @returns a PickingInfo
  28353. */
  28354. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28355. var _this = this;
  28356. var result = this._internalPick(function (world) {
  28357. if (!_this._pickWithRayInverseMatrix) {
  28358. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28359. }
  28360. world.invertToRef(_this._pickWithRayInverseMatrix);
  28361. if (!_this._cachedRayForTransform) {
  28362. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28363. }
  28364. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28365. return _this._cachedRayForTransform;
  28366. }, predicate, fastCheck);
  28367. if (result) {
  28368. result.ray = ray;
  28369. }
  28370. return result;
  28371. };
  28372. /**
  28373. * Launch a ray to try to pick a mesh in the scene
  28374. * @param x X position on screen
  28375. * @param y Y position on screen
  28376. * @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
  28377. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28378. * @returns an array of PickingInfo
  28379. */
  28380. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28381. var _this = this;
  28382. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28383. };
  28384. /**
  28385. * Launch a ray to try to pick a mesh in the scene
  28386. * @param ray Ray to use
  28387. * @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
  28388. * @returns an array of PickingInfo
  28389. */
  28390. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28391. var _this = this;
  28392. return this._internalMultiPick(function (world) {
  28393. if (!_this._pickWithRayInverseMatrix) {
  28394. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28395. }
  28396. world.invertToRef(_this._pickWithRayInverseMatrix);
  28397. if (!_this._cachedRayForTransform) {
  28398. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28399. }
  28400. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28401. return _this._cachedRayForTransform;
  28402. }, predicate);
  28403. };
  28404. /**
  28405. * Force the value of meshUnderPointer
  28406. * @param mesh defines the mesh to use
  28407. */
  28408. Scene.prototype.setPointerOverMesh = function (mesh) {
  28409. if (this._pointerOverMesh === mesh) {
  28410. return;
  28411. }
  28412. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28413. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28414. }
  28415. this._pointerOverMesh = mesh;
  28416. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28417. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28418. }
  28419. };
  28420. /**
  28421. * Gets the mesh under the pointer
  28422. * @returns a Mesh or null if no mesh is under the pointer
  28423. */
  28424. Scene.prototype.getPointerOverMesh = function () {
  28425. return this._pointerOverMesh;
  28426. };
  28427. // Misc.
  28428. /** @hidden */
  28429. Scene.prototype._rebuildGeometries = function () {
  28430. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28431. var geometry = _a[_i];
  28432. geometry._rebuild();
  28433. }
  28434. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28435. var mesh = _c[_b];
  28436. mesh._rebuild();
  28437. }
  28438. if (this.postProcessManager) {
  28439. this.postProcessManager._rebuild();
  28440. }
  28441. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28442. var component = _e[_d];
  28443. component.rebuild();
  28444. }
  28445. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28446. var system = _g[_f];
  28447. system.rebuild();
  28448. }
  28449. };
  28450. /** @hidden */
  28451. Scene.prototype._rebuildTextures = function () {
  28452. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28453. var texture = _a[_i];
  28454. texture._rebuild();
  28455. }
  28456. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28457. };
  28458. // Tags
  28459. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28460. if (tagsQuery === undefined) {
  28461. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28462. return list;
  28463. }
  28464. var listByTags = [];
  28465. forEach = forEach || (function (item) { return; });
  28466. for (var i in list) {
  28467. var item = list[i];
  28468. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28469. listByTags.push(item);
  28470. forEach(item);
  28471. }
  28472. }
  28473. return listByTags;
  28474. };
  28475. /**
  28476. * Get a list of meshes by tags
  28477. * @param tagsQuery defines the tags query to use
  28478. * @param forEach defines a predicate used to filter results
  28479. * @returns an array of Mesh
  28480. */
  28481. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28482. return this._getByTags(this.meshes, tagsQuery, forEach);
  28483. };
  28484. /**
  28485. * Get a list of cameras by tags
  28486. * @param tagsQuery defines the tags query to use
  28487. * @param forEach defines a predicate used to filter results
  28488. * @returns an array of Camera
  28489. */
  28490. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28491. return this._getByTags(this.cameras, tagsQuery, forEach);
  28492. };
  28493. /**
  28494. * Get a list of lights by tags
  28495. * @param tagsQuery defines the tags query to use
  28496. * @param forEach defines a predicate used to filter results
  28497. * @returns an array of Light
  28498. */
  28499. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28500. return this._getByTags(this.lights, tagsQuery, forEach);
  28501. };
  28502. /**
  28503. * Get a list of materials by tags
  28504. * @param tagsQuery defines the tags query to use
  28505. * @param forEach defines a predicate used to filter results
  28506. * @returns an array of Material
  28507. */
  28508. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28509. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28510. };
  28511. /**
  28512. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28513. * This allowed control for front to back rendering or reversly depending of the special needs.
  28514. *
  28515. * @param renderingGroupId The rendering group id corresponding to its index
  28516. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28517. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28518. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28519. */
  28520. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28521. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28522. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28523. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28524. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28525. };
  28526. /**
  28527. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28528. *
  28529. * @param renderingGroupId The rendering group id corresponding to its index
  28530. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28531. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28532. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28533. */
  28534. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28535. if (depth === void 0) { depth = true; }
  28536. if (stencil === void 0) { stencil = true; }
  28537. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28538. };
  28539. /**
  28540. * Gets the current auto clear configuration for one rendering group of the rendering
  28541. * manager.
  28542. * @param index the rendering group index to get the information for
  28543. * @returns The auto clear setup for the requested rendering group
  28544. */
  28545. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  28546. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  28547. };
  28548. /**
  28549. * Will flag all materials as dirty to trigger new shader compilation
  28550. * @param flag defines the flag used to specify which material part must be marked as dirty
  28551. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28552. */
  28553. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28554. if (this.blockMaterialDirtyMechanism) {
  28555. return;
  28556. }
  28557. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28558. var material = _a[_i];
  28559. if (predicate && !predicate(material)) {
  28560. continue;
  28561. }
  28562. material.markAsDirty(flag);
  28563. }
  28564. };
  28565. /** @hidden */
  28566. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28567. var _this = this;
  28568. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28569. this._activeRequests.push(request);
  28570. request.onCompleteObservable.add(function (request) {
  28571. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28572. });
  28573. return request;
  28574. };
  28575. /** @hidden */
  28576. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28577. var _this = this;
  28578. return new Promise(function (resolve, reject) {
  28579. _this._loadFile(url, function (data) {
  28580. resolve(data);
  28581. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28582. reject(exception);
  28583. });
  28584. });
  28585. };
  28586. // Statics
  28587. Scene._uniqueIdCounter = 0;
  28588. /** The fog is deactivated */
  28589. Scene.FOGMODE_NONE = 0;
  28590. /** The fog density is following an exponential function */
  28591. Scene.FOGMODE_EXP = 1;
  28592. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  28593. Scene.FOGMODE_EXP2 = 2;
  28594. /** The fog density is following a linear function. */
  28595. Scene.FOGMODE_LINEAR = 3;
  28596. /**
  28597. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28598. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28599. */
  28600. Scene.MinDeltaTime = 1.0;
  28601. /**
  28602. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28603. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28604. */
  28605. Scene.MaxDeltaTime = 1000.0;
  28606. /** The distance in pixel that you have to move to prevent some events */
  28607. Scene.DragMovementThreshold = 10; // in pixels
  28608. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28609. Scene.LongPressDelay = 500; // in milliseconds
  28610. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28611. Scene.DoubleClickDelay = 300; // in milliseconds
  28612. /** If you need to check double click without raising a single click at first click, enable this flag */
  28613. Scene.ExclusiveDoubleClickMode = false;
  28614. return Scene;
  28615. }(BABYLON.AbstractScene));
  28616. BABYLON.Scene = Scene;
  28617. })(BABYLON || (BABYLON = {}));
  28618. //# sourceMappingURL=babylon.scene.js.map
  28619. var BABYLON;
  28620. (function (BABYLON) {
  28621. /**
  28622. * Set of assets to keep when moving a scene into an asset container.
  28623. */
  28624. var KeepAssets = /** @class */ (function (_super) {
  28625. __extends(KeepAssets, _super);
  28626. function KeepAssets() {
  28627. return _super !== null && _super.apply(this, arguments) || this;
  28628. }
  28629. return KeepAssets;
  28630. }(BABYLON.AbstractScene));
  28631. BABYLON.KeepAssets = KeepAssets;
  28632. /**
  28633. * Container with a set of assets that can be added or removed from a scene.
  28634. */
  28635. var AssetContainer = /** @class */ (function (_super) {
  28636. __extends(AssetContainer, _super);
  28637. /**
  28638. * Instantiates an AssetContainer.
  28639. * @param scene The scene the AssetContainer belongs to.
  28640. */
  28641. function AssetContainer(scene) {
  28642. var _this = _super.call(this) || this;
  28643. _this.scene = scene;
  28644. return _this;
  28645. }
  28646. /**
  28647. * Adds all the assets from the container to the scene.
  28648. */
  28649. AssetContainer.prototype.addAllToScene = function () {
  28650. var _this = this;
  28651. this.cameras.forEach(function (o) {
  28652. _this.scene.addCamera(o);
  28653. });
  28654. this.lights.forEach(function (o) {
  28655. _this.scene.addLight(o);
  28656. });
  28657. this.meshes.forEach(function (o) {
  28658. _this.scene.addMesh(o);
  28659. });
  28660. this.skeletons.forEach(function (o) {
  28661. _this.scene.addSkeleton(o);
  28662. });
  28663. this.animations.forEach(function (o) {
  28664. _this.scene.addAnimation(o);
  28665. });
  28666. this.animationGroups.forEach(function (o) {
  28667. _this.scene.addAnimationGroup(o);
  28668. });
  28669. this.multiMaterials.forEach(function (o) {
  28670. _this.scene.addMultiMaterial(o);
  28671. });
  28672. this.materials.forEach(function (o) {
  28673. _this.scene.addMaterial(o);
  28674. });
  28675. this.morphTargetManagers.forEach(function (o) {
  28676. _this.scene.addMorphTargetManager(o);
  28677. });
  28678. this.geometries.forEach(function (o) {
  28679. _this.scene.addGeometry(o);
  28680. });
  28681. this.transformNodes.forEach(function (o) {
  28682. _this.scene.addTransformNode(o);
  28683. });
  28684. this.actionManagers.forEach(function (o) {
  28685. _this.scene.addActionManager(o);
  28686. });
  28687. this.textures.forEach(function (o) {
  28688. _this.scene.addTexture(o);
  28689. });
  28690. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28691. var component = _a[_i];
  28692. component.addFromContainer(this.scene);
  28693. }
  28694. };
  28695. /**
  28696. * Removes all the assets in the container from the scene
  28697. */
  28698. AssetContainer.prototype.removeAllFromScene = function () {
  28699. var _this = this;
  28700. this.cameras.forEach(function (o) {
  28701. _this.scene.removeCamera(o);
  28702. });
  28703. this.lights.forEach(function (o) {
  28704. _this.scene.removeLight(o);
  28705. });
  28706. this.meshes.forEach(function (o) {
  28707. _this.scene.removeMesh(o);
  28708. });
  28709. this.skeletons.forEach(function (o) {
  28710. _this.scene.removeSkeleton(o);
  28711. });
  28712. this.animations.forEach(function (o) {
  28713. _this.scene.removeAnimation(o);
  28714. });
  28715. this.animationGroups.forEach(function (o) {
  28716. _this.scene.removeAnimationGroup(o);
  28717. });
  28718. this.multiMaterials.forEach(function (o) {
  28719. _this.scene.removeMultiMaterial(o);
  28720. });
  28721. this.materials.forEach(function (o) {
  28722. _this.scene.removeMaterial(o);
  28723. });
  28724. this.morphTargetManagers.forEach(function (o) {
  28725. _this.scene.removeMorphTargetManager(o);
  28726. });
  28727. this.geometries.forEach(function (o) {
  28728. _this.scene.removeGeometry(o);
  28729. });
  28730. this.transformNodes.forEach(function (o) {
  28731. _this.scene.removeTransformNode(o);
  28732. });
  28733. this.actionManagers.forEach(function (o) {
  28734. _this.scene.removeActionManager(o);
  28735. });
  28736. this.textures.forEach(function (o) {
  28737. _this.scene.removeTexture(o);
  28738. });
  28739. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  28740. var component = _a[_i];
  28741. component.removeFromContainer(this.scene);
  28742. }
  28743. };
  28744. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28745. if (!sourceAssets) {
  28746. return;
  28747. }
  28748. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28749. var asset = sourceAssets_1[_i];
  28750. var move = true;
  28751. if (keepAssets) {
  28752. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28753. var keepAsset = keepAssets_1[_a];
  28754. if (asset === keepAsset) {
  28755. move = false;
  28756. break;
  28757. }
  28758. }
  28759. }
  28760. if (move) {
  28761. targetAssets.push(asset);
  28762. }
  28763. }
  28764. };
  28765. /**
  28766. * Removes all the assets contained in the scene and adds them to the container.
  28767. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28768. */
  28769. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28770. if (keepAssets === undefined) {
  28771. keepAssets = new KeepAssets();
  28772. }
  28773. for (var key in this) {
  28774. if (this.hasOwnProperty(key)) {
  28775. this[key] = this[key] || [];
  28776. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  28777. }
  28778. }
  28779. this.removeAllFromScene();
  28780. };
  28781. /**
  28782. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  28783. * @returns the root mesh
  28784. */
  28785. AssetContainer.prototype.createRootMesh = function () {
  28786. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  28787. this.meshes.forEach(function (m) {
  28788. if (!m.parent) {
  28789. rootMesh.addChild(m);
  28790. }
  28791. });
  28792. this.meshes.unshift(rootMesh);
  28793. return rootMesh;
  28794. };
  28795. return AssetContainer;
  28796. }(BABYLON.AbstractScene));
  28797. BABYLON.AssetContainer = AssetContainer;
  28798. })(BABYLON || (BABYLON = {}));
  28799. //# sourceMappingURL=babylon.assetContainer.js.map
  28800. var BABYLON;
  28801. (function (BABYLON) {
  28802. var Buffer = /** @class */ (function () {
  28803. /**
  28804. * Constructor
  28805. * @param engine the engine
  28806. * @param data the data to use for this buffer
  28807. * @param updatable whether the data is updatable
  28808. * @param stride the stride (optional)
  28809. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28810. * @param instanced whether the buffer is instanced (optional)
  28811. * @param useBytes set to true if the stride in in bytes (optional)
  28812. */
  28813. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28814. if (stride === void 0) { stride = 0; }
  28815. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28816. if (instanced === void 0) { instanced = false; }
  28817. if (useBytes === void 0) { useBytes = false; }
  28818. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28819. this._engine = engine.getScene().getEngine();
  28820. }
  28821. else {
  28822. this._engine = engine;
  28823. }
  28824. this._updatable = updatable;
  28825. this._instanced = instanced;
  28826. this._data = data;
  28827. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28828. if (!postponeInternalCreation) { // by default
  28829. this.create();
  28830. }
  28831. }
  28832. /**
  28833. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28834. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28835. * @param offset defines offset in the buffer (0 by default)
  28836. * @param size defines the size in floats of attributes (position is 3 for instance)
  28837. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28838. * @param instanced defines if the vertex buffer contains indexed data
  28839. * @param useBytes defines if the offset and stride are in bytes
  28840. * @returns the new vertex buffer
  28841. */
  28842. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28843. if (useBytes === void 0) { useBytes = false; }
  28844. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28845. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28846. // a lot of these parameters are ignored as they are overriden by the buffer
  28847. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28848. };
  28849. // Properties
  28850. Buffer.prototype.isUpdatable = function () {
  28851. return this._updatable;
  28852. };
  28853. Buffer.prototype.getData = function () {
  28854. return this._data;
  28855. };
  28856. Buffer.prototype.getBuffer = function () {
  28857. return this._buffer;
  28858. };
  28859. /**
  28860. * Gets the stride in float32 units (i.e. byte stride / 4).
  28861. * May not be an integer if the byte stride is not divisible by 4.
  28862. * DEPRECATED. Use byteStride instead.
  28863. * @returns the stride in float32 units
  28864. */
  28865. Buffer.prototype.getStrideSize = function () {
  28866. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28867. };
  28868. // Methods
  28869. Buffer.prototype.create = function (data) {
  28870. if (data === void 0) { data = null; }
  28871. if (!data && this._buffer) {
  28872. return; // nothing to do
  28873. }
  28874. data = data || this._data;
  28875. if (!data) {
  28876. return;
  28877. }
  28878. if (!this._buffer) { // create buffer
  28879. if (this._updatable) {
  28880. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28881. this._data = data;
  28882. }
  28883. else {
  28884. this._buffer = this._engine.createVertexBuffer(data);
  28885. }
  28886. }
  28887. else if (this._updatable) { // update buffer
  28888. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28889. this._data = data;
  28890. }
  28891. };
  28892. /** @hidden */
  28893. Buffer.prototype._rebuild = function () {
  28894. this._buffer = null;
  28895. this.create(this._data);
  28896. };
  28897. Buffer.prototype.update = function (data) {
  28898. this.create(data);
  28899. };
  28900. /**
  28901. * Updates the data directly.
  28902. * @param data the new data
  28903. * @param offset the new offset
  28904. * @param vertexCount the vertex count (optional)
  28905. * @param useBytes set to true if the offset is in bytes
  28906. */
  28907. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28908. if (useBytes === void 0) { useBytes = false; }
  28909. if (!this._buffer) {
  28910. return;
  28911. }
  28912. if (this._updatable) { // update buffer
  28913. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28914. this._data = null;
  28915. }
  28916. };
  28917. Buffer.prototype.dispose = function () {
  28918. if (!this._buffer) {
  28919. return;
  28920. }
  28921. if (this._engine._releaseBuffer(this._buffer)) {
  28922. this._buffer = null;
  28923. }
  28924. };
  28925. return Buffer;
  28926. }());
  28927. BABYLON.Buffer = Buffer;
  28928. })(BABYLON || (BABYLON = {}));
  28929. //# sourceMappingURL=babylon.buffer.js.map
  28930. var BABYLON;
  28931. (function (BABYLON) {
  28932. var VertexBuffer = /** @class */ (function () {
  28933. /**
  28934. * Constructor
  28935. * @param engine the engine
  28936. * @param data the data to use for this vertex buffer
  28937. * @param kind the vertex buffer kind
  28938. * @param updatable whether the data is updatable
  28939. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28940. * @param stride the stride (optional)
  28941. * @param instanced whether the buffer is instanced (optional)
  28942. * @param offset the offset of the data (optional)
  28943. * @param size the number of components (optional)
  28944. * @param type the type of the component (optional)
  28945. * @param normalized whether the data contains normalized data (optional)
  28946. * @param useBytes set to true if stride and offset are in bytes (optional)
  28947. */
  28948. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28949. if (normalized === void 0) { normalized = false; }
  28950. if (useBytes === void 0) { useBytes = false; }
  28951. if (data instanceof BABYLON.Buffer) {
  28952. this._buffer = data;
  28953. this._ownsBuffer = false;
  28954. }
  28955. else {
  28956. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28957. this._ownsBuffer = true;
  28958. }
  28959. this._kind = kind;
  28960. if (type == undefined) {
  28961. var data_1 = this.getData();
  28962. this.type = VertexBuffer.FLOAT;
  28963. if (data_1 instanceof Int8Array)
  28964. this.type = VertexBuffer.BYTE;
  28965. else if (data_1 instanceof Uint8Array)
  28966. this.type = VertexBuffer.UNSIGNED_BYTE;
  28967. else if (data_1 instanceof Int16Array)
  28968. this.type = VertexBuffer.SHORT;
  28969. else if (data_1 instanceof Uint16Array)
  28970. this.type = VertexBuffer.UNSIGNED_SHORT;
  28971. else if (data_1 instanceof Int32Array)
  28972. this.type = VertexBuffer.INT;
  28973. else if (data_1 instanceof Uint32Array)
  28974. this.type = VertexBuffer.UNSIGNED_INT;
  28975. }
  28976. else {
  28977. this.type = type;
  28978. }
  28979. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28980. if (useBytes) {
  28981. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28982. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28983. this.byteOffset = offset || 0;
  28984. }
  28985. else {
  28986. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28987. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28988. this.byteOffset = (offset || 0) * typeByteLength;
  28989. }
  28990. this.normalized = normalized;
  28991. this._instanced = instanced !== undefined ? instanced : false;
  28992. this._instanceDivisor = instanced ? 1 : 0;
  28993. }
  28994. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28995. /**
  28996. * Gets or sets the instance divisor when in instanced mode
  28997. */
  28998. get: function () {
  28999. return this._instanceDivisor;
  29000. },
  29001. set: function (value) {
  29002. this._instanceDivisor = value;
  29003. if (value == 0) {
  29004. this._instanced = false;
  29005. }
  29006. else {
  29007. this._instanced = true;
  29008. }
  29009. },
  29010. enumerable: true,
  29011. configurable: true
  29012. });
  29013. /** @hidden */
  29014. VertexBuffer.prototype._rebuild = function () {
  29015. if (!this._buffer) {
  29016. return;
  29017. }
  29018. this._buffer._rebuild();
  29019. };
  29020. /**
  29021. * Returns the kind of the VertexBuffer (string).
  29022. */
  29023. VertexBuffer.prototype.getKind = function () {
  29024. return this._kind;
  29025. };
  29026. // Properties
  29027. /**
  29028. * Boolean : is the VertexBuffer updatable ?
  29029. */
  29030. VertexBuffer.prototype.isUpdatable = function () {
  29031. return this._buffer.isUpdatable();
  29032. };
  29033. /**
  29034. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29035. */
  29036. VertexBuffer.prototype.getData = function () {
  29037. return this._buffer.getData();
  29038. };
  29039. /**
  29040. * Returns the WebGLBuffer associated to the VertexBuffer.
  29041. */
  29042. VertexBuffer.prototype.getBuffer = function () {
  29043. return this._buffer.getBuffer();
  29044. };
  29045. /**
  29046. * Returns the stride as a multiple of the type byte length.
  29047. * DEPRECATED. Use byteStride instead.
  29048. */
  29049. VertexBuffer.prototype.getStrideSize = function () {
  29050. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29051. };
  29052. /**
  29053. * Returns the offset as a multiple of the type byte length.
  29054. * DEPRECATED. Use byteOffset instead.
  29055. */
  29056. VertexBuffer.prototype.getOffset = function () {
  29057. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29058. };
  29059. /**
  29060. * Returns the number of components per vertex attribute (integer).
  29061. */
  29062. VertexBuffer.prototype.getSize = function () {
  29063. return this._size;
  29064. };
  29065. /**
  29066. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29067. */
  29068. VertexBuffer.prototype.getIsInstanced = function () {
  29069. return this._instanced;
  29070. };
  29071. /**
  29072. * Returns the instancing divisor, zero for non-instanced (integer).
  29073. */
  29074. VertexBuffer.prototype.getInstanceDivisor = function () {
  29075. return this._instanceDivisor;
  29076. };
  29077. // Methods
  29078. /**
  29079. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29080. * Returns the created WebGLBuffer.
  29081. */
  29082. VertexBuffer.prototype.create = function (data) {
  29083. return this._buffer.create(data);
  29084. };
  29085. /**
  29086. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29087. * This function will create a new buffer if the current one is not updatable
  29088. * Returns the updated WebGLBuffer.
  29089. */
  29090. VertexBuffer.prototype.update = function (data) {
  29091. return this._buffer.update(data);
  29092. };
  29093. /**
  29094. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29095. * Returns the directly updated WebGLBuffer.
  29096. * @param data the new data
  29097. * @param offset the new offset
  29098. * @param useBytes set to true if the offset is in bytes
  29099. */
  29100. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29101. if (useBytes === void 0) { useBytes = false; }
  29102. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29103. };
  29104. /**
  29105. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29106. */
  29107. VertexBuffer.prototype.dispose = function () {
  29108. if (this._ownsBuffer) {
  29109. this._buffer.dispose();
  29110. }
  29111. };
  29112. /**
  29113. * Enumerates each value of this vertex buffer as numbers.
  29114. * @param count the number of values to enumerate
  29115. * @param callback the callback function called for each value
  29116. */
  29117. VertexBuffer.prototype.forEach = function (count, callback) {
  29118. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29119. };
  29120. Object.defineProperty(VertexBuffer, "PositionKind", {
  29121. get: function () {
  29122. return VertexBuffer._PositionKind;
  29123. },
  29124. enumerable: true,
  29125. configurable: true
  29126. });
  29127. Object.defineProperty(VertexBuffer, "NormalKind", {
  29128. get: function () {
  29129. return VertexBuffer._NormalKind;
  29130. },
  29131. enumerable: true,
  29132. configurable: true
  29133. });
  29134. Object.defineProperty(VertexBuffer, "TangentKind", {
  29135. get: function () {
  29136. return VertexBuffer._TangentKind;
  29137. },
  29138. enumerable: true,
  29139. configurable: true
  29140. });
  29141. Object.defineProperty(VertexBuffer, "UVKind", {
  29142. get: function () {
  29143. return VertexBuffer._UVKind;
  29144. },
  29145. enumerable: true,
  29146. configurable: true
  29147. });
  29148. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29149. get: function () {
  29150. return VertexBuffer._UV2Kind;
  29151. },
  29152. enumerable: true,
  29153. configurable: true
  29154. });
  29155. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29156. get: function () {
  29157. return VertexBuffer._UV3Kind;
  29158. },
  29159. enumerable: true,
  29160. configurable: true
  29161. });
  29162. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29163. get: function () {
  29164. return VertexBuffer._UV4Kind;
  29165. },
  29166. enumerable: true,
  29167. configurable: true
  29168. });
  29169. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29170. get: function () {
  29171. return VertexBuffer._UV5Kind;
  29172. },
  29173. enumerable: true,
  29174. configurable: true
  29175. });
  29176. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29177. get: function () {
  29178. return VertexBuffer._UV6Kind;
  29179. },
  29180. enumerable: true,
  29181. configurable: true
  29182. });
  29183. Object.defineProperty(VertexBuffer, "ColorKind", {
  29184. get: function () {
  29185. return VertexBuffer._ColorKind;
  29186. },
  29187. enumerable: true,
  29188. configurable: true
  29189. });
  29190. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29191. get: function () {
  29192. return VertexBuffer._MatricesIndicesKind;
  29193. },
  29194. enumerable: true,
  29195. configurable: true
  29196. });
  29197. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29198. get: function () {
  29199. return VertexBuffer._MatricesWeightsKind;
  29200. },
  29201. enumerable: true,
  29202. configurable: true
  29203. });
  29204. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29205. get: function () {
  29206. return VertexBuffer._MatricesIndicesExtraKind;
  29207. },
  29208. enumerable: true,
  29209. configurable: true
  29210. });
  29211. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29212. get: function () {
  29213. return VertexBuffer._MatricesWeightsExtraKind;
  29214. },
  29215. enumerable: true,
  29216. configurable: true
  29217. });
  29218. /**
  29219. * Deduces the stride given a kind.
  29220. * @param kind The kind string to deduce
  29221. * @returns The deduced stride
  29222. */
  29223. VertexBuffer.DeduceStride = function (kind) {
  29224. switch (kind) {
  29225. case VertexBuffer.UVKind:
  29226. case VertexBuffer.UV2Kind:
  29227. case VertexBuffer.UV3Kind:
  29228. case VertexBuffer.UV4Kind:
  29229. case VertexBuffer.UV5Kind:
  29230. case VertexBuffer.UV6Kind:
  29231. return 2;
  29232. case VertexBuffer.NormalKind:
  29233. case VertexBuffer.PositionKind:
  29234. return 3;
  29235. case VertexBuffer.ColorKind:
  29236. case VertexBuffer.MatricesIndicesKind:
  29237. case VertexBuffer.MatricesIndicesExtraKind:
  29238. case VertexBuffer.MatricesWeightsKind:
  29239. case VertexBuffer.MatricesWeightsExtraKind:
  29240. case VertexBuffer.TangentKind:
  29241. return 4;
  29242. default:
  29243. throw new Error("Invalid kind '" + kind + "'");
  29244. }
  29245. };
  29246. /**
  29247. * Gets the byte length of the given type.
  29248. * @param type the type
  29249. * @returns the number of bytes
  29250. */
  29251. VertexBuffer.GetTypeByteLength = function (type) {
  29252. switch (type) {
  29253. case VertexBuffer.BYTE:
  29254. case VertexBuffer.UNSIGNED_BYTE:
  29255. return 1;
  29256. case VertexBuffer.SHORT:
  29257. case VertexBuffer.UNSIGNED_SHORT:
  29258. return 2;
  29259. case VertexBuffer.INT:
  29260. case VertexBuffer.FLOAT:
  29261. return 4;
  29262. default:
  29263. throw new Error("Invalid type '" + type + "'");
  29264. }
  29265. };
  29266. /**
  29267. * Enumerates each value of the given parameters as numbers.
  29268. * @param data the data to enumerate
  29269. * @param byteOffset the byte offset of the data
  29270. * @param byteStride the byte stride of the data
  29271. * @param componentCount the number of components per element
  29272. * @param componentType the type of the component
  29273. * @param count the total number of components
  29274. * @param normalized whether the data is normalized
  29275. * @param callback the callback function called for each value
  29276. */
  29277. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29278. if (data instanceof Array) {
  29279. var offset = byteOffset / 4;
  29280. var stride = byteStride / 4;
  29281. for (var index = 0; index < count; index += componentCount) {
  29282. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29283. callback(data[offset + componentIndex], index + componentIndex);
  29284. }
  29285. offset += stride;
  29286. }
  29287. }
  29288. else {
  29289. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29290. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29291. for (var index = 0; index < count; index += componentCount) {
  29292. var componentByteOffset = byteOffset;
  29293. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29294. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29295. callback(value, index + componentIndex);
  29296. componentByteOffset += componentByteLength;
  29297. }
  29298. byteOffset += byteStride;
  29299. }
  29300. }
  29301. };
  29302. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29303. switch (type) {
  29304. case VertexBuffer.BYTE: {
  29305. var value = dataView.getInt8(byteOffset);
  29306. if (normalized) {
  29307. value = Math.max(value / 127, -1);
  29308. }
  29309. return value;
  29310. }
  29311. case VertexBuffer.UNSIGNED_BYTE: {
  29312. var value = dataView.getUint8(byteOffset);
  29313. if (normalized) {
  29314. value = value / 255;
  29315. }
  29316. return value;
  29317. }
  29318. case VertexBuffer.SHORT: {
  29319. var value = dataView.getInt16(byteOffset, true);
  29320. if (normalized) {
  29321. value = Math.max(value / 16383, -1);
  29322. }
  29323. return value;
  29324. }
  29325. case VertexBuffer.UNSIGNED_SHORT: {
  29326. var value = dataView.getUint16(byteOffset, true);
  29327. if (normalized) {
  29328. value = value / 65535;
  29329. }
  29330. return value;
  29331. }
  29332. case VertexBuffer.FLOAT: {
  29333. return dataView.getFloat32(byteOffset, true);
  29334. }
  29335. default: {
  29336. throw new Error("Invalid component type " + type);
  29337. }
  29338. }
  29339. };
  29340. /**
  29341. * The byte type.
  29342. */
  29343. VertexBuffer.BYTE = 5120;
  29344. /**
  29345. * The unsigned byte type.
  29346. */
  29347. VertexBuffer.UNSIGNED_BYTE = 5121;
  29348. /**
  29349. * The short type.
  29350. */
  29351. VertexBuffer.SHORT = 5122;
  29352. /**
  29353. * The unsigned short type.
  29354. */
  29355. VertexBuffer.UNSIGNED_SHORT = 5123;
  29356. /**
  29357. * The integer type.
  29358. */
  29359. VertexBuffer.INT = 5124;
  29360. /**
  29361. * The unsigned integer type.
  29362. */
  29363. VertexBuffer.UNSIGNED_INT = 5125;
  29364. /**
  29365. * The float type.
  29366. */
  29367. VertexBuffer.FLOAT = 5126;
  29368. // Enums
  29369. VertexBuffer._PositionKind = "position";
  29370. VertexBuffer._NormalKind = "normal";
  29371. VertexBuffer._TangentKind = "tangent";
  29372. VertexBuffer._UVKind = "uv";
  29373. VertexBuffer._UV2Kind = "uv2";
  29374. VertexBuffer._UV3Kind = "uv3";
  29375. VertexBuffer._UV4Kind = "uv4";
  29376. VertexBuffer._UV5Kind = "uv5";
  29377. VertexBuffer._UV6Kind = "uv6";
  29378. VertexBuffer._ColorKind = "color";
  29379. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29380. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29381. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29382. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29383. return VertexBuffer;
  29384. }());
  29385. BABYLON.VertexBuffer = VertexBuffer;
  29386. })(BABYLON || (BABYLON = {}));
  29387. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29388. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29389. var BABYLON;
  29390. (function (BABYLON) {
  29391. /**
  29392. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29393. */
  29394. var DummyInternalTextureTracker = /** @class */ (function () {
  29395. function DummyInternalTextureTracker() {
  29396. /**
  29397. * Gets or set the previous tracker in the list
  29398. */
  29399. this.previous = null;
  29400. /**
  29401. * Gets or set the next tracker in the list
  29402. */
  29403. this.next = null;
  29404. }
  29405. return DummyInternalTextureTracker;
  29406. }());
  29407. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29408. })(BABYLON || (BABYLON = {}));
  29409. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29410. var BABYLON;
  29411. (function (BABYLON) {
  29412. /**
  29413. * Class used to store data associated with WebGL texture data for the engine
  29414. * This class should not be used directly
  29415. */
  29416. var InternalTexture = /** @class */ (function () {
  29417. /**
  29418. * Creates a new InternalTexture
  29419. * @param engine defines the engine to use
  29420. * @param dataSource defines the type of data that will be used
  29421. */
  29422. function InternalTexture(engine, dataSource) {
  29423. /**
  29424. * Observable called when the texture is loaded
  29425. */
  29426. this.onLoadedObservable = new BABYLON.Observable();
  29427. /**
  29428. * Gets or set the previous tracker in the list
  29429. */
  29430. this.previous = null;
  29431. /**
  29432. * Gets or set the next tracker in the list
  29433. */
  29434. this.next = null;
  29435. // Private
  29436. /** @hidden */
  29437. this._initialSlot = -1;
  29438. /** @hidden */
  29439. this._designatedSlot = -1;
  29440. /** @hidden */
  29441. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29442. /** @hidden */
  29443. this._comparisonFunction = 0;
  29444. /** @hidden */
  29445. this._sphericalPolynomial = null;
  29446. /** @hidden */
  29447. this._lodGenerationScale = 0;
  29448. /** @hidden */
  29449. this._lodGenerationOffset = 0;
  29450. /** @hidden */
  29451. this._isRGBD = false;
  29452. /** @hidden */
  29453. this._references = 1;
  29454. this._engine = engine;
  29455. this._dataSource = dataSource;
  29456. this._webGLTexture = engine._createTexture();
  29457. }
  29458. /**
  29459. * Gets the Engine the texture belongs to.
  29460. * @returns The babylon engine
  29461. */
  29462. InternalTexture.prototype.getEngine = function () {
  29463. return this._engine;
  29464. };
  29465. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29466. /**
  29467. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29468. */
  29469. get: function () {
  29470. return this._dataSource;
  29471. },
  29472. enumerable: true,
  29473. configurable: true
  29474. });
  29475. /**
  29476. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29477. */
  29478. InternalTexture.prototype.incrementReferences = function () {
  29479. this._references++;
  29480. };
  29481. /**
  29482. * Change the size of the texture (not the size of the content)
  29483. * @param width defines the new width
  29484. * @param height defines the new height
  29485. * @param depth defines the new depth (1 by default)
  29486. */
  29487. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29488. if (depth === void 0) { depth = 1; }
  29489. this.width = width;
  29490. this.height = height;
  29491. this.depth = depth;
  29492. this.baseWidth = width;
  29493. this.baseHeight = height;
  29494. this.baseDepth = depth;
  29495. this._size = width * height * depth;
  29496. };
  29497. /** @hidden */
  29498. InternalTexture.prototype._rebuild = function () {
  29499. var _this = this;
  29500. var proxy;
  29501. this.isReady = false;
  29502. this._cachedCoordinatesMode = null;
  29503. this._cachedWrapU = null;
  29504. this._cachedWrapV = null;
  29505. this._cachedAnisotropicFilteringLevel = null;
  29506. switch (this._dataSource) {
  29507. case InternalTexture.DATASOURCE_TEMP:
  29508. return;
  29509. case InternalTexture.DATASOURCE_URL:
  29510. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29511. _this.isReady = true;
  29512. }, null, this._buffer, undefined, this.format);
  29513. proxy._swapAndDie(this);
  29514. return;
  29515. case InternalTexture.DATASOURCE_RAW:
  29516. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29517. proxy._swapAndDie(this);
  29518. this.isReady = true;
  29519. return;
  29520. case InternalTexture.DATASOURCE_RAW3D:
  29521. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29522. proxy._swapAndDie(this);
  29523. this.isReady = true;
  29524. return;
  29525. case InternalTexture.DATASOURCE_DYNAMIC:
  29526. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29527. proxy._swapAndDie(this);
  29528. // The engine will make sure to update content so no need to flag it as isReady = true
  29529. return;
  29530. case InternalTexture.DATASOURCE_RENDERTARGET:
  29531. var options = new BABYLON.RenderTargetCreationOptions();
  29532. options.generateDepthBuffer = this._generateDepthBuffer;
  29533. options.generateMipMaps = this.generateMipMaps;
  29534. options.generateStencilBuffer = this._generateStencilBuffer;
  29535. options.samplingMode = this.samplingMode;
  29536. options.type = this.type;
  29537. if (this.isCube) {
  29538. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29539. }
  29540. else {
  29541. var size = {
  29542. width: this.width,
  29543. height: this.height
  29544. };
  29545. proxy = this._engine.createRenderTargetTexture(size, options);
  29546. }
  29547. proxy._swapAndDie(this);
  29548. this.isReady = true;
  29549. return;
  29550. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29551. var depthTextureOptions = {
  29552. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29553. comparisonFunction: this._comparisonFunction,
  29554. generateStencil: this._generateStencilBuffer,
  29555. isCube: this.isCube
  29556. };
  29557. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29558. proxy._swapAndDie(this);
  29559. this.isReady = true;
  29560. return;
  29561. case InternalTexture.DATASOURCE_CUBE:
  29562. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29563. _this.isReady = true;
  29564. }, null, this.format, this._extension);
  29565. proxy._swapAndDie(this);
  29566. return;
  29567. case InternalTexture.DATASOURCE_CUBERAW:
  29568. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29569. proxy._swapAndDie(this);
  29570. this.isReady = true;
  29571. return;
  29572. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  29573. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29574. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  29575. _this.isReady = true;
  29576. });
  29577. proxy._swapAndDie(this);
  29578. return;
  29579. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29580. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29581. if (proxy) {
  29582. proxy._swapAndDie(_this);
  29583. }
  29584. _this.isReady = true;
  29585. }, null, this.format, this._extension);
  29586. proxy._sphericalPolynomial = this._sphericalPolynomial;
  29587. return;
  29588. }
  29589. };
  29590. /** @hidden */
  29591. InternalTexture.prototype._swapAndDie = function (target) {
  29592. target._webGLTexture = this._webGLTexture;
  29593. if (this._framebuffer) {
  29594. target._framebuffer = this._framebuffer;
  29595. }
  29596. if (this._depthStencilBuffer) {
  29597. target._depthStencilBuffer = this._depthStencilBuffer;
  29598. }
  29599. if (this._lodTextureHigh) {
  29600. if (target._lodTextureHigh) {
  29601. target._lodTextureHigh.dispose();
  29602. }
  29603. target._lodTextureHigh = this._lodTextureHigh;
  29604. }
  29605. if (this._lodTextureMid) {
  29606. if (target._lodTextureMid) {
  29607. target._lodTextureMid.dispose();
  29608. }
  29609. target._lodTextureMid = this._lodTextureMid;
  29610. }
  29611. if (this._lodTextureLow) {
  29612. if (target._lodTextureLow) {
  29613. target._lodTextureLow.dispose();
  29614. }
  29615. target._lodTextureLow = this._lodTextureLow;
  29616. }
  29617. var cache = this._engine.getLoadedTexturesCache();
  29618. var index = cache.indexOf(this);
  29619. if (index !== -1) {
  29620. cache.splice(index, 1);
  29621. }
  29622. };
  29623. /**
  29624. * Dispose the current allocated resources
  29625. */
  29626. InternalTexture.prototype.dispose = function () {
  29627. if (!this._webGLTexture) {
  29628. return;
  29629. }
  29630. this._references--;
  29631. if (this._references === 0) {
  29632. this._engine._releaseTexture(this);
  29633. this._webGLTexture = null;
  29634. this.previous = null;
  29635. this.next = null;
  29636. }
  29637. };
  29638. /**
  29639. * The source of the texture data is unknown
  29640. */
  29641. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29642. /**
  29643. * Texture data comes from an URL
  29644. */
  29645. InternalTexture.DATASOURCE_URL = 1;
  29646. /**
  29647. * Texture data is only used for temporary storage
  29648. */
  29649. InternalTexture.DATASOURCE_TEMP = 2;
  29650. /**
  29651. * Texture data comes from raw data (ArrayBuffer)
  29652. */
  29653. InternalTexture.DATASOURCE_RAW = 3;
  29654. /**
  29655. * Texture content is dynamic (video or dynamic texture)
  29656. */
  29657. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29658. /**
  29659. * Texture content is generated by rendering to it
  29660. */
  29661. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29662. /**
  29663. * Texture content is part of a multi render target process
  29664. */
  29665. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29666. /**
  29667. * Texture data comes from a cube data file
  29668. */
  29669. InternalTexture.DATASOURCE_CUBE = 7;
  29670. /**
  29671. * Texture data comes from a raw cube data
  29672. */
  29673. InternalTexture.DATASOURCE_CUBERAW = 8;
  29674. /**
  29675. * Texture data come from a prefiltered cube data file
  29676. */
  29677. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29678. /**
  29679. * Texture content is raw 3D data
  29680. */
  29681. InternalTexture.DATASOURCE_RAW3D = 10;
  29682. /**
  29683. * Texture content is a depth texture
  29684. */
  29685. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29686. /**
  29687. * Texture data comes from a raw cube data encoded with RGBD
  29688. */
  29689. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  29690. return InternalTexture;
  29691. }());
  29692. BABYLON.InternalTexture = InternalTexture;
  29693. })(BABYLON || (BABYLON = {}));
  29694. //# sourceMappingURL=babylon.internalTexture.js.map
  29695. var BABYLON;
  29696. (function (BABYLON) {
  29697. var BaseTexture = /** @class */ (function () {
  29698. function BaseTexture(scene) {
  29699. this._hasAlpha = false;
  29700. this.getAlphaFromRGB = false;
  29701. this.level = 1;
  29702. this.coordinatesIndex = 0;
  29703. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29704. /**
  29705. * | Value | Type | Description |
  29706. * | ----- | ------------------ | ----------- |
  29707. * | 0 | CLAMP_ADDRESSMODE | |
  29708. * | 1 | WRAP_ADDRESSMODE | |
  29709. * | 2 | MIRROR_ADDRESSMODE | |
  29710. */
  29711. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29712. /**
  29713. * | Value | Type | Description |
  29714. * | ----- | ------------------ | ----------- |
  29715. * | 0 | CLAMP_ADDRESSMODE | |
  29716. * | 1 | WRAP_ADDRESSMODE | |
  29717. * | 2 | MIRROR_ADDRESSMODE | |
  29718. */
  29719. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29720. /**
  29721. * | Value | Type | Description |
  29722. * | ----- | ------------------ | ----------- |
  29723. * | 0 | CLAMP_ADDRESSMODE | |
  29724. * | 1 | WRAP_ADDRESSMODE | |
  29725. * | 2 | MIRROR_ADDRESSMODE | |
  29726. */
  29727. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29728. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29729. this.isCube = false;
  29730. this.is3D = false;
  29731. this.gammaSpace = true;
  29732. this.invertZ = false;
  29733. this.lodLevelInAlpha = false;
  29734. this.isRenderTarget = false;
  29735. this.animations = new Array();
  29736. /**
  29737. * An event triggered when the texture is disposed.
  29738. */
  29739. this.onDisposeObservable = new BABYLON.Observable();
  29740. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29741. this._cachedSize = BABYLON.Size.Zero();
  29742. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29743. if (this._scene) {
  29744. this._scene.textures.push(this);
  29745. }
  29746. this._uid = null;
  29747. }
  29748. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29749. get: function () {
  29750. return this._hasAlpha;
  29751. },
  29752. set: function (value) {
  29753. if (this._hasAlpha === value) {
  29754. return;
  29755. }
  29756. this._hasAlpha = value;
  29757. if (this._scene) {
  29758. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29759. }
  29760. },
  29761. enumerable: true,
  29762. configurable: true
  29763. });
  29764. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29765. get: function () {
  29766. return this._coordinatesMode;
  29767. },
  29768. /**
  29769. * How a texture is mapped.
  29770. *
  29771. * | Value | Type | Description |
  29772. * | ----- | ----------------------------------- | ----------- |
  29773. * | 0 | EXPLICIT_MODE | |
  29774. * | 1 | SPHERICAL_MODE | |
  29775. * | 2 | PLANAR_MODE | |
  29776. * | 3 | CUBIC_MODE | |
  29777. * | 4 | PROJECTION_MODE | |
  29778. * | 5 | SKYBOX_MODE | |
  29779. * | 6 | INVCUBIC_MODE | |
  29780. * | 7 | EQUIRECTANGULAR_MODE | |
  29781. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29782. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29783. */
  29784. set: function (value) {
  29785. if (this._coordinatesMode === value) {
  29786. return;
  29787. }
  29788. this._coordinatesMode = value;
  29789. if (this._scene) {
  29790. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29791. }
  29792. },
  29793. enumerable: true,
  29794. configurable: true
  29795. });
  29796. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  29797. /**
  29798. * Gets whether or not the texture contains RGBD data.
  29799. */
  29800. get: function () {
  29801. return this._texture != null && this._texture._isRGBD;
  29802. },
  29803. enumerable: true,
  29804. configurable: true
  29805. });
  29806. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  29807. get: function () {
  29808. if (this._texture)
  29809. return this._texture._lodGenerationOffset;
  29810. return 0.0;
  29811. },
  29812. set: function (value) {
  29813. if (this._texture)
  29814. this._texture._lodGenerationOffset = value;
  29815. },
  29816. enumerable: true,
  29817. configurable: true
  29818. });
  29819. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  29820. get: function () {
  29821. if (this._texture)
  29822. return this._texture._lodGenerationScale;
  29823. return 0.0;
  29824. },
  29825. set: function (value) {
  29826. if (this._texture)
  29827. this._texture._lodGenerationScale = value;
  29828. },
  29829. enumerable: true,
  29830. configurable: true
  29831. });
  29832. Object.defineProperty(BaseTexture.prototype, "uid", {
  29833. get: function () {
  29834. if (!this._uid) {
  29835. this._uid = BABYLON.Tools.RandomId();
  29836. }
  29837. return this._uid;
  29838. },
  29839. enumerable: true,
  29840. configurable: true
  29841. });
  29842. BaseTexture.prototype.toString = function () {
  29843. return this.name;
  29844. };
  29845. BaseTexture.prototype.getClassName = function () {
  29846. return "BaseTexture";
  29847. };
  29848. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29849. set: function (callback) {
  29850. if (this._onDisposeObserver) {
  29851. this.onDisposeObservable.remove(this._onDisposeObserver);
  29852. }
  29853. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29854. },
  29855. enumerable: true,
  29856. configurable: true
  29857. });
  29858. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29859. get: function () {
  29860. return true;
  29861. },
  29862. enumerable: true,
  29863. configurable: true
  29864. });
  29865. BaseTexture.prototype.getScene = function () {
  29866. return this._scene;
  29867. };
  29868. BaseTexture.prototype.getTextureMatrix = function () {
  29869. return BABYLON.Matrix.IdentityReadOnly;
  29870. };
  29871. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29872. return BABYLON.Matrix.IdentityReadOnly;
  29873. };
  29874. BaseTexture.prototype.getInternalTexture = function () {
  29875. return this._texture;
  29876. };
  29877. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29878. return !this.isBlocking || this.isReady();
  29879. };
  29880. BaseTexture.prototype.isReady = function () {
  29881. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29882. this.delayLoad();
  29883. return false;
  29884. }
  29885. if (this._texture) {
  29886. return this._texture.isReady;
  29887. }
  29888. return false;
  29889. };
  29890. BaseTexture.prototype.getSize = function () {
  29891. if (this._texture) {
  29892. if (this._texture.width) {
  29893. this._cachedSize.width = this._texture.width;
  29894. this._cachedSize.height = this._texture.height;
  29895. return this._cachedSize;
  29896. }
  29897. if (this._texture._size) {
  29898. this._cachedSize.width = this._texture._size;
  29899. this._cachedSize.height = this._texture._size;
  29900. return this._cachedSize;
  29901. }
  29902. }
  29903. return this._cachedSize;
  29904. };
  29905. BaseTexture.prototype.getBaseSize = function () {
  29906. if (!this.isReady() || !this._texture)
  29907. return BABYLON.Size.Zero();
  29908. if (this._texture._size) {
  29909. return new BABYLON.Size(this._texture._size, this._texture._size);
  29910. }
  29911. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29912. };
  29913. BaseTexture.prototype.scale = function (ratio) {
  29914. };
  29915. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29916. get: function () {
  29917. return false;
  29918. },
  29919. enumerable: true,
  29920. configurable: true
  29921. });
  29922. /** @hidden */
  29923. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29924. if (!this._scene) {
  29925. return null;
  29926. }
  29927. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29928. for (var index = 0; index < texturesCache.length; index++) {
  29929. var texturesCacheEntry = texturesCache[index];
  29930. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29931. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29932. texturesCacheEntry.incrementReferences();
  29933. return texturesCacheEntry;
  29934. }
  29935. }
  29936. }
  29937. return null;
  29938. };
  29939. /** @hidden */
  29940. BaseTexture.prototype._rebuild = function () {
  29941. };
  29942. BaseTexture.prototype.delayLoad = function () {
  29943. };
  29944. BaseTexture.prototype.clone = function () {
  29945. return null;
  29946. };
  29947. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29948. get: function () {
  29949. if (!this._texture) {
  29950. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29951. }
  29952. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29953. },
  29954. enumerable: true,
  29955. configurable: true
  29956. });
  29957. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29958. get: function () {
  29959. if (!this._texture) {
  29960. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29961. }
  29962. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29963. },
  29964. enumerable: true,
  29965. configurable: true
  29966. });
  29967. /**
  29968. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  29969. * This will returns an RGBA array buffer containing either in values (0-255) or
  29970. * float values (0-1) depending of the underlying buffer type.
  29971. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  29972. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  29973. * @param buffer defines a user defined buffer to fill with data (can be null)
  29974. * @returns The Array buffer containing the pixels data.
  29975. */
  29976. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  29977. if (faceIndex === void 0) { faceIndex = 0; }
  29978. if (level === void 0) { level = 0; }
  29979. if (buffer === void 0) { buffer = null; }
  29980. if (!this._texture) {
  29981. return null;
  29982. }
  29983. var size = this.getSize();
  29984. var width = size.width;
  29985. var height = size.height;
  29986. var scene = this.getScene();
  29987. if (!scene) {
  29988. return null;
  29989. }
  29990. var engine = scene.getEngine();
  29991. if (level != 0) {
  29992. width = width / Math.pow(2, level);
  29993. height = height / Math.pow(2, level);
  29994. width = Math.round(width);
  29995. height = Math.round(height);
  29996. }
  29997. if (this._texture.isCube) {
  29998. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  29999. }
  30000. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  30001. };
  30002. BaseTexture.prototype.releaseInternalTexture = function () {
  30003. if (this._texture) {
  30004. this._texture.dispose();
  30005. this._texture = null;
  30006. }
  30007. };
  30008. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30009. get: function () {
  30010. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30011. return null;
  30012. }
  30013. if (!this._texture._sphericalPolynomial) {
  30014. this._texture._sphericalPolynomial =
  30015. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30016. }
  30017. return this._texture._sphericalPolynomial;
  30018. },
  30019. set: function (value) {
  30020. if (this._texture) {
  30021. this._texture._sphericalPolynomial = value;
  30022. }
  30023. },
  30024. enumerable: true,
  30025. configurable: true
  30026. });
  30027. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30028. get: function () {
  30029. if (this._texture) {
  30030. return this._texture._lodTextureHigh;
  30031. }
  30032. return null;
  30033. },
  30034. enumerable: true,
  30035. configurable: true
  30036. });
  30037. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30038. get: function () {
  30039. if (this._texture) {
  30040. return this._texture._lodTextureMid;
  30041. }
  30042. return null;
  30043. },
  30044. enumerable: true,
  30045. configurable: true
  30046. });
  30047. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30048. get: function () {
  30049. if (this._texture) {
  30050. return this._texture._lodTextureLow;
  30051. }
  30052. return null;
  30053. },
  30054. enumerable: true,
  30055. configurable: true
  30056. });
  30057. BaseTexture.prototype.dispose = function () {
  30058. if (!this._scene) {
  30059. return;
  30060. }
  30061. // Animations
  30062. this._scene.stopAnimation(this);
  30063. // Remove from scene
  30064. this._scene._removePendingData(this);
  30065. var index = this._scene.textures.indexOf(this);
  30066. if (index >= 0) {
  30067. this._scene.textures.splice(index, 1);
  30068. }
  30069. if (this._texture === undefined) {
  30070. return;
  30071. }
  30072. // Release
  30073. this.releaseInternalTexture();
  30074. // Callback
  30075. this.onDisposeObservable.notifyObservers(this);
  30076. this.onDisposeObservable.clear();
  30077. };
  30078. BaseTexture.prototype.serialize = function () {
  30079. if (!this.name) {
  30080. return null;
  30081. }
  30082. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30083. // Animations
  30084. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30085. return serializationObject;
  30086. };
  30087. BaseTexture.WhenAllReady = function (textures, callback) {
  30088. var numRemaining = textures.length;
  30089. if (numRemaining === 0) {
  30090. callback();
  30091. return;
  30092. }
  30093. var _loop_1 = function () {
  30094. texture = textures[i];
  30095. if (texture.isReady()) {
  30096. if (--numRemaining === 0) {
  30097. callback();
  30098. }
  30099. }
  30100. else {
  30101. onLoadObservable = texture.onLoadObservable;
  30102. var onLoadCallback_1 = function () {
  30103. onLoadObservable.removeCallback(onLoadCallback_1);
  30104. if (--numRemaining === 0) {
  30105. callback();
  30106. }
  30107. };
  30108. onLoadObservable.add(onLoadCallback_1);
  30109. }
  30110. };
  30111. var texture, onLoadObservable;
  30112. for (var i = 0; i < textures.length; i++) {
  30113. _loop_1();
  30114. }
  30115. };
  30116. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30117. __decorate([
  30118. BABYLON.serialize()
  30119. ], BaseTexture.prototype, "name", void 0);
  30120. __decorate([
  30121. BABYLON.serialize("hasAlpha")
  30122. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30123. __decorate([
  30124. BABYLON.serialize()
  30125. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30126. __decorate([
  30127. BABYLON.serialize()
  30128. ], BaseTexture.prototype, "level", void 0);
  30129. __decorate([
  30130. BABYLON.serialize()
  30131. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30132. __decorate([
  30133. BABYLON.serialize("coordinatesMode")
  30134. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30135. __decorate([
  30136. BABYLON.serialize()
  30137. ], BaseTexture.prototype, "wrapU", void 0);
  30138. __decorate([
  30139. BABYLON.serialize()
  30140. ], BaseTexture.prototype, "wrapV", void 0);
  30141. __decorate([
  30142. BABYLON.serialize()
  30143. ], BaseTexture.prototype, "wrapR", void 0);
  30144. __decorate([
  30145. BABYLON.serialize()
  30146. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30147. __decorate([
  30148. BABYLON.serialize()
  30149. ], BaseTexture.prototype, "isCube", void 0);
  30150. __decorate([
  30151. BABYLON.serialize()
  30152. ], BaseTexture.prototype, "is3D", void 0);
  30153. __decorate([
  30154. BABYLON.serialize()
  30155. ], BaseTexture.prototype, "gammaSpace", void 0);
  30156. __decorate([
  30157. BABYLON.serialize()
  30158. ], BaseTexture.prototype, "invertZ", void 0);
  30159. __decorate([
  30160. BABYLON.serialize()
  30161. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30162. __decorate([
  30163. BABYLON.serialize()
  30164. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30165. __decorate([
  30166. BABYLON.serialize()
  30167. ], BaseTexture.prototype, "lodGenerationScale", null);
  30168. __decorate([
  30169. BABYLON.serialize()
  30170. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30171. return BaseTexture;
  30172. }());
  30173. BABYLON.BaseTexture = BaseTexture;
  30174. })(BABYLON || (BABYLON = {}));
  30175. //# sourceMappingURL=babylon.baseTexture.js.map
  30176. var BABYLON;
  30177. (function (BABYLON) {
  30178. var Texture = /** @class */ (function (_super) {
  30179. __extends(Texture, _super);
  30180. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30181. if (noMipmap === void 0) { noMipmap = false; }
  30182. if (invertY === void 0) { invertY = true; }
  30183. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30184. if (onLoad === void 0) { onLoad = null; }
  30185. if (onError === void 0) { onError = null; }
  30186. if (buffer === void 0) { buffer = null; }
  30187. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30188. var _this = _super.call(this, scene) || this;
  30189. _this.uOffset = 0;
  30190. _this.vOffset = 0;
  30191. _this.uScale = 1.0;
  30192. _this.vScale = 1.0;
  30193. _this.uAng = 0;
  30194. _this.vAng = 0;
  30195. _this.wAng = 0;
  30196. /**
  30197. * Defines the center of rotation (U)
  30198. */
  30199. _this.uRotationCenter = 0.5;
  30200. /**
  30201. * Defines the center of rotation (V)
  30202. */
  30203. _this.vRotationCenter = 0.5;
  30204. /**
  30205. * Defines the center of rotation (W)
  30206. */
  30207. _this.wRotationCenter = 0.5;
  30208. _this._isBlocking = true;
  30209. _this.name = url || "";
  30210. _this.url = url;
  30211. _this._noMipmap = noMipmap;
  30212. _this._invertY = invertY;
  30213. _this._samplingMode = samplingMode;
  30214. _this._buffer = buffer;
  30215. _this._deleteBuffer = deleteBuffer;
  30216. if (format) {
  30217. _this._format = format;
  30218. }
  30219. scene = _this.getScene();
  30220. if (!scene) {
  30221. return _this;
  30222. }
  30223. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30224. var load = function () {
  30225. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30226. _this.onLoadObservable.notifyObservers(_this);
  30227. }
  30228. if (onLoad) {
  30229. onLoad();
  30230. }
  30231. if (!_this.isBlocking && scene) {
  30232. scene.resetCachedMaterial();
  30233. }
  30234. };
  30235. if (!_this.url) {
  30236. _this._delayedOnLoad = load;
  30237. _this._delayedOnError = onError;
  30238. return _this;
  30239. }
  30240. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30241. if (!_this._texture) {
  30242. if (!scene.useDelayedTextureLoading) {
  30243. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30244. if (deleteBuffer) {
  30245. delete _this._buffer;
  30246. }
  30247. }
  30248. else {
  30249. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30250. _this._delayedOnLoad = load;
  30251. _this._delayedOnError = onError;
  30252. }
  30253. }
  30254. else {
  30255. if (_this._texture.isReady) {
  30256. BABYLON.Tools.SetImmediate(function () { return load(); });
  30257. }
  30258. else {
  30259. _this._texture.onLoadedObservable.add(load);
  30260. }
  30261. }
  30262. return _this;
  30263. }
  30264. Object.defineProperty(Texture.prototype, "noMipmap", {
  30265. get: function () {
  30266. return this._noMipmap;
  30267. },
  30268. enumerable: true,
  30269. configurable: true
  30270. });
  30271. Object.defineProperty(Texture.prototype, "isBlocking", {
  30272. get: function () {
  30273. return this._isBlocking;
  30274. },
  30275. set: function (value) {
  30276. this._isBlocking = value;
  30277. },
  30278. enumerable: true,
  30279. configurable: true
  30280. });
  30281. Object.defineProperty(Texture.prototype, "samplingMode", {
  30282. get: function () {
  30283. return this._samplingMode;
  30284. },
  30285. enumerable: true,
  30286. configurable: true
  30287. });
  30288. /**
  30289. * Update the url (and optional buffer) of this texture if url was null during construction.
  30290. * @param url the url of the texture
  30291. * @param buffer the buffer of the texture (defaults to null)
  30292. */
  30293. Texture.prototype.updateURL = function (url, buffer) {
  30294. if (buffer === void 0) { buffer = null; }
  30295. if (this.url) {
  30296. throw new Error("URL is already set");
  30297. }
  30298. this.url = url;
  30299. this._buffer = buffer;
  30300. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30301. this.delayLoad();
  30302. };
  30303. Texture.prototype.delayLoad = function () {
  30304. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30305. return;
  30306. }
  30307. var scene = this.getScene();
  30308. if (!scene) {
  30309. return;
  30310. }
  30311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30312. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30313. if (!this._texture) {
  30314. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30315. if (this._deleteBuffer) {
  30316. delete this._buffer;
  30317. }
  30318. }
  30319. else {
  30320. if (this._delayedOnLoad) {
  30321. if (this._texture.isReady) {
  30322. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30323. }
  30324. else {
  30325. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30326. }
  30327. }
  30328. }
  30329. this._delayedOnLoad = null;
  30330. this._delayedOnError = null;
  30331. };
  30332. /**
  30333. * Default is Trilinear mode.
  30334. *
  30335. * | Value | Type | Description |
  30336. * | ----- | ------------------ | ----------- |
  30337. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30338. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30339. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30340. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30341. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30342. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30343. * | 7 | NEAREST_LINEAR | |
  30344. * | 8 | NEAREST_NEAREST | |
  30345. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30346. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30347. * | 11 | LINEAR_LINEAR | |
  30348. * | 12 | LINEAR_NEAREST | |
  30349. *
  30350. * > _mag_: magnification filter (close to the viewer)
  30351. * > _min_: minification filter (far from the viewer)
  30352. * > _mip_: filter used between mip map levels
  30353. *
  30354. */
  30355. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30356. if (!this._texture) {
  30357. return;
  30358. }
  30359. var scene = this.getScene();
  30360. if (!scene) {
  30361. return;
  30362. }
  30363. this._samplingMode = samplingMode;
  30364. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30365. };
  30366. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30367. x *= this.uScale;
  30368. y *= this.vScale;
  30369. x -= this.uRotationCenter * this.uScale;
  30370. y -= this.vRotationCenter * this.vScale;
  30371. z -= this.wRotationCenter;
  30372. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30373. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30374. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30375. t.z += this.wRotationCenter;
  30376. };
  30377. Texture.prototype.getTextureMatrix = function () {
  30378. var _this = this;
  30379. if (this.uOffset === this._cachedUOffset &&
  30380. this.vOffset === this._cachedVOffset &&
  30381. this.uScale === this._cachedUScale &&
  30382. this.vScale === this._cachedVScale &&
  30383. this.uAng === this._cachedUAng &&
  30384. this.vAng === this._cachedVAng &&
  30385. this.wAng === this._cachedWAng) {
  30386. return this._cachedTextureMatrix;
  30387. }
  30388. this._cachedUOffset = this.uOffset;
  30389. this._cachedVOffset = this.vOffset;
  30390. this._cachedUScale = this.uScale;
  30391. this._cachedVScale = this.vScale;
  30392. this._cachedUAng = this.uAng;
  30393. this._cachedVAng = this.vAng;
  30394. this._cachedWAng = this.wAng;
  30395. if (!this._cachedTextureMatrix) {
  30396. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30397. this._rowGenerationMatrix = new BABYLON.Matrix();
  30398. this._t0 = BABYLON.Vector3.Zero();
  30399. this._t1 = BABYLON.Vector3.Zero();
  30400. this._t2 = BABYLON.Vector3.Zero();
  30401. }
  30402. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30403. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30404. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30405. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30406. this._t1.subtractInPlace(this._t0);
  30407. this._t2.subtractInPlace(this._t0);
  30408. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30409. this._cachedTextureMatrix.m[0] = this._t1.x;
  30410. this._cachedTextureMatrix.m[1] = this._t1.y;
  30411. this._cachedTextureMatrix.m[2] = this._t1.z;
  30412. this._cachedTextureMatrix.m[4] = this._t2.x;
  30413. this._cachedTextureMatrix.m[5] = this._t2.y;
  30414. this._cachedTextureMatrix.m[6] = this._t2.z;
  30415. this._cachedTextureMatrix.m[8] = this._t0.x;
  30416. this._cachedTextureMatrix.m[9] = this._t0.y;
  30417. this._cachedTextureMatrix.m[10] = this._t0.z;
  30418. var scene = this.getScene();
  30419. if (!scene) {
  30420. return this._cachedTextureMatrix;
  30421. }
  30422. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30423. return mat.hasTexture(_this);
  30424. });
  30425. return this._cachedTextureMatrix;
  30426. };
  30427. Texture.prototype.getReflectionTextureMatrix = function () {
  30428. var _this = this;
  30429. var scene = this.getScene();
  30430. if (!scene) {
  30431. return this._cachedTextureMatrix;
  30432. }
  30433. if (this.uOffset === this._cachedUOffset &&
  30434. this.vOffset === this._cachedVOffset &&
  30435. this.uScale === this._cachedUScale &&
  30436. this.vScale === this._cachedVScale &&
  30437. this.coordinatesMode === this._cachedCoordinatesMode) {
  30438. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30439. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30440. return this._cachedTextureMatrix;
  30441. }
  30442. }
  30443. else {
  30444. return this._cachedTextureMatrix;
  30445. }
  30446. }
  30447. if (!this._cachedTextureMatrix) {
  30448. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30449. }
  30450. if (!this._projectionModeMatrix) {
  30451. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30452. }
  30453. this._cachedUOffset = this.uOffset;
  30454. this._cachedVOffset = this.vOffset;
  30455. this._cachedUScale = this.uScale;
  30456. this._cachedVScale = this.vScale;
  30457. this._cachedCoordinatesMode = this.coordinatesMode;
  30458. switch (this.coordinatesMode) {
  30459. case Texture.PLANAR_MODE:
  30460. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30461. this._cachedTextureMatrix[0] = this.uScale;
  30462. this._cachedTextureMatrix[5] = this.vScale;
  30463. this._cachedTextureMatrix[12] = this.uOffset;
  30464. this._cachedTextureMatrix[13] = this.vOffset;
  30465. break;
  30466. case Texture.PROJECTION_MODE:
  30467. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30468. this._projectionModeMatrix.m[0] = 0.5;
  30469. this._projectionModeMatrix.m[5] = -0.5;
  30470. this._projectionModeMatrix.m[10] = 0.0;
  30471. this._projectionModeMatrix.m[12] = 0.5;
  30472. this._projectionModeMatrix.m[13] = 0.5;
  30473. this._projectionModeMatrix.m[14] = 1.0;
  30474. this._projectionModeMatrix.m[15] = 1.0;
  30475. var projectionMatrix = scene.getProjectionMatrix();
  30476. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30477. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30478. break;
  30479. default:
  30480. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30481. break;
  30482. }
  30483. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30484. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30485. });
  30486. return this._cachedTextureMatrix;
  30487. };
  30488. Texture.prototype.clone = function () {
  30489. var _this = this;
  30490. return BABYLON.SerializationHelper.Clone(function () {
  30491. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30492. }, this);
  30493. };
  30494. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30495. get: function () {
  30496. if (!this._onLoadObservable) {
  30497. this._onLoadObservable = new BABYLON.Observable();
  30498. }
  30499. return this._onLoadObservable;
  30500. },
  30501. enumerable: true,
  30502. configurable: true
  30503. });
  30504. Texture.prototype.serialize = function () {
  30505. var serializationObject = _super.prototype.serialize.call(this);
  30506. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30507. serializationObject.base64String = this._buffer;
  30508. serializationObject.name = serializationObject.name.replace("data:", "");
  30509. }
  30510. serializationObject.invertY = this._invertY;
  30511. serializationObject.samplingMode = this.samplingMode;
  30512. return serializationObject;
  30513. };
  30514. Texture.prototype.getClassName = function () {
  30515. return "Texture";
  30516. };
  30517. Texture.prototype.dispose = function () {
  30518. _super.prototype.dispose.call(this);
  30519. if (this._onLoadObservable) {
  30520. this._onLoadObservable.clear();
  30521. this._onLoadObservable = null;
  30522. }
  30523. this._delayedOnLoad = null;
  30524. this._delayedOnError = null;
  30525. };
  30526. // Statics
  30527. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30528. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30529. if (onLoad === void 0) { onLoad = null; }
  30530. if (onError === void 0) { onError = null; }
  30531. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30532. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30533. };
  30534. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30535. if (parsedTexture.customType) {
  30536. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30537. // Update Sampling Mode
  30538. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30539. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30540. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30541. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30542. }
  30543. }
  30544. return parsedCustomTexture;
  30545. }
  30546. if (parsedTexture.isCube) {
  30547. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30548. }
  30549. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30550. return null;
  30551. }
  30552. var texture = BABYLON.SerializationHelper.Parse(function () {
  30553. var generateMipMaps = true;
  30554. if (parsedTexture.noMipmap) {
  30555. generateMipMaps = false;
  30556. }
  30557. if (parsedTexture.mirrorPlane) {
  30558. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30559. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30560. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30561. return mirrorTexture;
  30562. }
  30563. else if (parsedTexture.isRenderTarget) {
  30564. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30565. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30566. return renderTargetTexture;
  30567. }
  30568. else {
  30569. var texture;
  30570. if (parsedTexture.base64String) {
  30571. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30572. }
  30573. else {
  30574. var url = rootUrl + parsedTexture.name;
  30575. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30576. url = parsedTexture.url;
  30577. }
  30578. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30579. }
  30580. return texture;
  30581. }
  30582. }, parsedTexture, scene);
  30583. // Update Sampling Mode
  30584. if (parsedTexture.samplingMode) {
  30585. var sampling = parsedTexture.samplingMode;
  30586. if (texture._samplingMode !== sampling) {
  30587. texture.updateSamplingMode(sampling);
  30588. }
  30589. }
  30590. // Animations
  30591. if (parsedTexture.animations) {
  30592. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30593. var parsedAnimation = parsedTexture.animations[animationIndex];
  30594. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30595. }
  30596. }
  30597. return texture;
  30598. };
  30599. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30600. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30601. if (noMipmap === void 0) { noMipmap = false; }
  30602. if (invertY === void 0) { invertY = true; }
  30603. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30604. if (onLoad === void 0) { onLoad = null; }
  30605. if (onError === void 0) { onError = null; }
  30606. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30607. if (name.substr(0, 5) !== "data:") {
  30608. name = "data:" + name;
  30609. }
  30610. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30611. };
  30612. // Constants
  30613. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  30614. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  30615. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  30616. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  30617. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  30618. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  30619. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  30620. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  30621. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  30622. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  30623. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  30624. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  30625. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  30626. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  30627. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  30628. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  30629. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  30630. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  30631. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  30632. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  30633. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  30634. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  30635. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  30636. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  30637. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  30638. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  30639. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  30640. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  30641. /**
  30642. * 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
  30643. */
  30644. Texture.UseSerializedUrlIfAny = false;
  30645. __decorate([
  30646. BABYLON.serialize()
  30647. ], Texture.prototype, "url", void 0);
  30648. __decorate([
  30649. BABYLON.serialize()
  30650. ], Texture.prototype, "uOffset", void 0);
  30651. __decorate([
  30652. BABYLON.serialize()
  30653. ], Texture.prototype, "vOffset", void 0);
  30654. __decorate([
  30655. BABYLON.serialize()
  30656. ], Texture.prototype, "uScale", void 0);
  30657. __decorate([
  30658. BABYLON.serialize()
  30659. ], Texture.prototype, "vScale", void 0);
  30660. __decorate([
  30661. BABYLON.serialize()
  30662. ], Texture.prototype, "uAng", void 0);
  30663. __decorate([
  30664. BABYLON.serialize()
  30665. ], Texture.prototype, "vAng", void 0);
  30666. __decorate([
  30667. BABYLON.serialize()
  30668. ], Texture.prototype, "wAng", void 0);
  30669. __decorate([
  30670. BABYLON.serialize()
  30671. ], Texture.prototype, "uRotationCenter", void 0);
  30672. __decorate([
  30673. BABYLON.serialize()
  30674. ], Texture.prototype, "vRotationCenter", void 0);
  30675. __decorate([
  30676. BABYLON.serialize()
  30677. ], Texture.prototype, "wRotationCenter", void 0);
  30678. __decorate([
  30679. BABYLON.serialize()
  30680. ], Texture.prototype, "isBlocking", null);
  30681. return Texture;
  30682. }(BABYLON.BaseTexture));
  30683. BABYLON.Texture = Texture;
  30684. })(BABYLON || (BABYLON = {}));
  30685. //# sourceMappingURL=babylon.texture.js.map
  30686. var BABYLON;
  30687. (function (BABYLON) {
  30688. /**
  30689. * @hidden
  30690. **/
  30691. var _InstancesBatch = /** @class */ (function () {
  30692. function _InstancesBatch() {
  30693. this.mustReturn = false;
  30694. this.visibleInstances = new Array();
  30695. this.renderSelf = new Array();
  30696. }
  30697. return _InstancesBatch;
  30698. }());
  30699. BABYLON._InstancesBatch = _InstancesBatch;
  30700. /**
  30701. * Class used to represent renderable models
  30702. */
  30703. var Mesh = /** @class */ (function (_super) {
  30704. __extends(Mesh, _super);
  30705. /**
  30706. * @constructor
  30707. * @param name The value used by scene.getMeshByName() to do a lookup.
  30708. * @param scene The scene to add this mesh to.
  30709. * @param parent The parent of this mesh, if it has one
  30710. * @param source An optional Mesh from which geometry is shared, cloned.
  30711. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30712. * When false, achieved by calling a clone(), also passing False.
  30713. * This will make creation of children, recursive.
  30714. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30715. */
  30716. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30717. if (scene === void 0) { scene = null; }
  30718. if (parent === void 0) { parent = null; }
  30719. if (source === void 0) { source = null; }
  30720. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30721. var _this = _super.call(this, name, scene) || this;
  30722. // Members
  30723. /**
  30724. * Gets the delay loading state of the mesh (when delay loading is turned on)
  30725. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  30726. */
  30727. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30728. /**
  30729. * Gets the list of instances created from this mesh
  30730. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  30731. */
  30732. _this.instances = new Array();
  30733. _this._LODLevels = new Array();
  30734. /** @hidden */
  30735. _this._visibleInstances = {};
  30736. _this._renderIdForInstances = new Array();
  30737. _this._batchCache = new _InstancesBatch();
  30738. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30739. // Use by builder only to know what orientation were the mesh build in.
  30740. /** @hidden */
  30741. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  30742. /**
  30743. * Use this property to change the original side orientation defined at construction time
  30744. */
  30745. _this.overrideMaterialSideOrientation = null;
  30746. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30747. // Will be used to save a source mesh reference, If any
  30748. _this._source = null;
  30749. scene = _this.getScene();
  30750. if (source) {
  30751. // Geometry
  30752. if (source._geometry) {
  30753. source._geometry.applyToMesh(_this);
  30754. }
  30755. // Deep copy
  30756. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30757. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  30758. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  30759. ], ["_poseMatrix"]);
  30760. // Source mesh
  30761. _this._source = source;
  30762. // Construction Params
  30763. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  30764. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  30765. var myAnyThis = _this;
  30766. var myAnySource = source;
  30767. myAnyThis._closePath = myAnySource._closePath;
  30768. myAnyThis._idx = myAnySource._idx;
  30769. myAnyThis.dashSize = myAnySource.dashSize;
  30770. myAnyThis.gapSize = myAnySource.gapSize;
  30771. myAnyThis.path3D = myAnySource.path3D;
  30772. myAnyThis.pathArray = myAnySource.pathArray;
  30773. myAnyThis.arc = myAnySource.arc;
  30774. myAnyThis.radius = myAnySource.radius;
  30775. // Animation ranges
  30776. if (_this._source._ranges) {
  30777. var ranges = _this._source._ranges;
  30778. for (var name in ranges) {
  30779. if (!ranges.hasOwnProperty(name)) {
  30780. continue;
  30781. }
  30782. if (!ranges[name]) {
  30783. continue;
  30784. }
  30785. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  30786. }
  30787. }
  30788. // Metadata
  30789. if (source.metadata && source.metadata.clone) {
  30790. _this.metadata = source.metadata.clone();
  30791. }
  30792. else {
  30793. _this.metadata = source.metadata;
  30794. }
  30795. // Tags
  30796. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30797. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30798. }
  30799. // Parent
  30800. _this.parent = source.parent;
  30801. // Pivot
  30802. _this.setPivotMatrix(source.getPivotMatrix());
  30803. _this.id = name + "." + source.id;
  30804. // Material
  30805. _this.material = source.material;
  30806. var index;
  30807. if (!doNotCloneChildren) {
  30808. // Children
  30809. var directDescendants = source.getDescendants(true);
  30810. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30811. var child = directDescendants[index_1];
  30812. if (child.clone) {
  30813. child.clone(name + "." + child.name, _this);
  30814. }
  30815. }
  30816. }
  30817. // Physics clone
  30818. var physicsEngine = _this.getScene().getPhysicsEngine();
  30819. if (clonePhysicsImpostor && physicsEngine) {
  30820. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30821. if (impostor) {
  30822. _this.physicsImpostor = impostor.clone(_this);
  30823. }
  30824. }
  30825. // Particles
  30826. for (index = 0; index < scene.particleSystems.length; index++) {
  30827. var system = scene.particleSystems[index];
  30828. if (system.emitter === source) {
  30829. system.clone(system.name, _this);
  30830. }
  30831. }
  30832. _this.refreshBoundingInfo();
  30833. _this.computeWorldMatrix(true);
  30834. }
  30835. // Parent
  30836. if (parent !== null) {
  30837. _this.parent = parent;
  30838. }
  30839. return _this;
  30840. }
  30841. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  30842. /**
  30843. * An event triggered before rendering the mesh
  30844. */
  30845. get: function () {
  30846. if (!this._onBeforeRenderObservable) {
  30847. this._onBeforeRenderObservable = new BABYLON.Observable();
  30848. }
  30849. return this._onBeforeRenderObservable;
  30850. },
  30851. enumerable: true,
  30852. configurable: true
  30853. });
  30854. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  30855. /**
  30856. * An event triggered after rendering the mesh
  30857. */
  30858. get: function () {
  30859. if (!this._onAfterRenderObservable) {
  30860. this._onAfterRenderObservable = new BABYLON.Observable();
  30861. }
  30862. return this._onAfterRenderObservable;
  30863. },
  30864. enumerable: true,
  30865. configurable: true
  30866. });
  30867. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  30868. /**
  30869. * An event triggered before drawing the mesh
  30870. */
  30871. get: function () {
  30872. if (!this._onBeforeDrawObservable) {
  30873. this._onBeforeDrawObservable = new BABYLON.Observable();
  30874. }
  30875. return this._onBeforeDrawObservable;
  30876. },
  30877. enumerable: true,
  30878. configurable: true
  30879. });
  30880. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30881. /**
  30882. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  30883. */
  30884. set: function (callback) {
  30885. if (this._onBeforeDrawObserver) {
  30886. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30887. }
  30888. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30889. },
  30890. enumerable: true,
  30891. configurable: true
  30892. });
  30893. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30894. /**
  30895. * Gets or sets the morph target manager
  30896. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  30897. */
  30898. get: function () {
  30899. return this._morphTargetManager;
  30900. },
  30901. set: function (value) {
  30902. if (this._morphTargetManager === value) {
  30903. return;
  30904. }
  30905. this._morphTargetManager = value;
  30906. this._syncGeometryWithMorphTargetManager();
  30907. },
  30908. enumerable: true,
  30909. configurable: true
  30910. });
  30911. Object.defineProperty(Mesh.prototype, "source", {
  30912. /**
  30913. * Gets the source mesh (the one used to clone this one from)
  30914. */
  30915. get: function () {
  30916. return this._source;
  30917. },
  30918. enumerable: true,
  30919. configurable: true
  30920. });
  30921. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30922. /**
  30923. * Gets or sets a boolean indicating that this mesh does not use index buffer
  30924. */
  30925. get: function () {
  30926. return this._unIndexed;
  30927. },
  30928. set: function (value) {
  30929. if (this._unIndexed !== value) {
  30930. this._unIndexed = value;
  30931. this._markSubMeshesAsAttributesDirty();
  30932. }
  30933. },
  30934. enumerable: true,
  30935. configurable: true
  30936. });
  30937. // Methods
  30938. /**
  30939. * Gets the class name
  30940. * @returns the string "Mesh".
  30941. */
  30942. Mesh.prototype.getClassName = function () {
  30943. return "Mesh";
  30944. };
  30945. /**
  30946. * Returns a description of this mesh
  30947. * @param fullDetails define if full details about this mesh must be used
  30948. * @returns a descriptive string representing this mesh
  30949. */
  30950. Mesh.prototype.toString = function (fullDetails) {
  30951. var ret = _super.prototype.toString.call(this, fullDetails);
  30952. ret += ", n vertices: " + this.getTotalVertices();
  30953. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30954. if (this.animations) {
  30955. for (var i = 0; i < this.animations.length; i++) {
  30956. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30957. }
  30958. }
  30959. if (fullDetails) {
  30960. if (this._geometry) {
  30961. var ib = this.getIndices();
  30962. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30963. if (vb && ib) {
  30964. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30965. }
  30966. }
  30967. else {
  30968. ret += ", flat shading: UNKNOWN";
  30969. }
  30970. }
  30971. return ret;
  30972. };
  30973. /** @hidden */
  30974. Mesh.prototype._unBindEffect = function () {
  30975. _super.prototype._unBindEffect.call(this);
  30976. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30977. var instance = _a[_i];
  30978. instance._unBindEffect();
  30979. }
  30980. };
  30981. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30982. /**
  30983. * Gets a boolean indicating if this mesh has LOD
  30984. */
  30985. get: function () {
  30986. return this._LODLevels.length > 0;
  30987. },
  30988. enumerable: true,
  30989. configurable: true
  30990. });
  30991. /**
  30992. * Gets the list of MeshLODLevel associated with the current mesh
  30993. * @returns an array of MeshLODLevel
  30994. */
  30995. Mesh.prototype.getLODLevels = function () {
  30996. return this._LODLevels;
  30997. };
  30998. Mesh.prototype._sortLODLevels = function () {
  30999. this._LODLevels.sort(function (a, b) {
  31000. if (a.distance < b.distance) {
  31001. return 1;
  31002. }
  31003. if (a.distance > b.distance) {
  31004. return -1;
  31005. }
  31006. return 0;
  31007. });
  31008. };
  31009. /**
  31010. * Add a mesh as LOD level triggered at the given distance.
  31011. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31012. * @param distance The distance from the center of the object to show this level
  31013. * @param mesh The mesh to be added as LOD level (can be null)
  31014. * @return This mesh (for chaining)
  31015. */
  31016. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31017. if (mesh && mesh._masterMesh) {
  31018. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31019. return this;
  31020. }
  31021. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31022. this._LODLevels.push(level);
  31023. if (mesh) {
  31024. mesh._masterMesh = this;
  31025. }
  31026. this._sortLODLevels();
  31027. return this;
  31028. };
  31029. /**
  31030. * Returns the LOD level mesh at the passed distance or null if not found.
  31031. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31032. * @param distance The distance from the center of the object to show this level
  31033. * @returns a Mesh or `null`
  31034. */
  31035. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31036. for (var index = 0; index < this._LODLevels.length; index++) {
  31037. var level = this._LODLevels[index];
  31038. if (level.distance === distance) {
  31039. return level.mesh;
  31040. }
  31041. }
  31042. return null;
  31043. };
  31044. /**
  31045. * Remove a mesh from the LOD array
  31046. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31047. * @param mesh defines the mesh to be removed
  31048. * @return This mesh (for chaining)
  31049. */
  31050. Mesh.prototype.removeLODLevel = function (mesh) {
  31051. for (var index = 0; index < this._LODLevels.length; index++) {
  31052. if (this._LODLevels[index].mesh === mesh) {
  31053. this._LODLevels.splice(index, 1);
  31054. if (mesh) {
  31055. mesh._masterMesh = null;
  31056. }
  31057. }
  31058. }
  31059. this._sortLODLevels();
  31060. return this;
  31061. };
  31062. /**
  31063. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31064. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  31065. * @param camera defines the camera to use to compute distance
  31066. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  31067. * @return This mesh (for chaining)
  31068. */
  31069. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31070. if (!this._LODLevels || this._LODLevels.length === 0) {
  31071. return this;
  31072. }
  31073. var bSphere;
  31074. if (boundingSphere) {
  31075. bSphere = boundingSphere;
  31076. }
  31077. else {
  31078. var boundingInfo = this.getBoundingInfo();
  31079. bSphere = boundingInfo.boundingSphere;
  31080. }
  31081. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31082. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31083. if (this.onLODLevelSelection) {
  31084. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31085. }
  31086. return this;
  31087. }
  31088. for (var index = 0; index < this._LODLevels.length; index++) {
  31089. var level = this._LODLevels[index];
  31090. if (level.distance < distanceToCamera) {
  31091. if (level.mesh) {
  31092. level.mesh._preActivate();
  31093. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31094. }
  31095. if (this.onLODLevelSelection) {
  31096. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31097. }
  31098. return level.mesh;
  31099. }
  31100. }
  31101. if (this.onLODLevelSelection) {
  31102. this.onLODLevelSelection(distanceToCamera, this, this);
  31103. }
  31104. return this;
  31105. };
  31106. Object.defineProperty(Mesh.prototype, "geometry", {
  31107. /**
  31108. * Gets the mesh internal Geometry object
  31109. */
  31110. get: function () {
  31111. return this._geometry;
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. /**
  31117. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31118. * @returns the total number of vertices
  31119. */
  31120. Mesh.prototype.getTotalVertices = function () {
  31121. if (this._geometry === null || this._geometry === undefined) {
  31122. return 0;
  31123. }
  31124. return this._geometry.getTotalVertices();
  31125. };
  31126. /**
  31127. * Returns the content of an associated vertex buffer
  31128. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31129. * - BABYLON.VertexBuffer.PositionKind
  31130. * - BABYLON.VertexBuffer.UVKind
  31131. * - BABYLON.VertexBuffer.UV2Kind
  31132. * - BABYLON.VertexBuffer.UV3Kind
  31133. * - BABYLON.VertexBuffer.UV4Kind
  31134. * - BABYLON.VertexBuffer.UV5Kind
  31135. * - BABYLON.VertexBuffer.UV6Kind
  31136. * - BABYLON.VertexBuffer.ColorKind
  31137. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31138. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31139. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31140. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31141. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  31142. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  31143. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  31144. */
  31145. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31146. if (!this._geometry) {
  31147. return null;
  31148. }
  31149. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31150. };
  31151. /**
  31152. * Returns the mesh VertexBuffer object from the requested `kind`
  31153. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31154. * - BABYLON.VertexBuffer.PositionKind
  31155. * - BABYLON.VertexBuffer.UVKind
  31156. * - BABYLON.VertexBuffer.UV2Kind
  31157. * - BABYLON.VertexBuffer.UV3Kind
  31158. * - BABYLON.VertexBuffer.UV4Kind
  31159. * - BABYLON.VertexBuffer.UV5Kind
  31160. * - BABYLON.VertexBuffer.UV6Kind
  31161. * - BABYLON.VertexBuffer.ColorKind
  31162. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31163. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31164. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31165. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31166. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  31167. */
  31168. Mesh.prototype.getVertexBuffer = function (kind) {
  31169. if (!this._geometry) {
  31170. return null;
  31171. }
  31172. return this._geometry.getVertexBuffer(kind);
  31173. };
  31174. /**
  31175. * Tests if a specific vertex buffer is associated with this mesh
  31176. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31177. * - BABYLON.VertexBuffer.PositionKind
  31178. * - BABYLON.VertexBuffer.UVKind
  31179. * - BABYLON.VertexBuffer.UV2Kind
  31180. * - BABYLON.VertexBuffer.UV3Kind
  31181. * - BABYLON.VertexBuffer.UV4Kind
  31182. * - BABYLON.VertexBuffer.UV5Kind
  31183. * - BABYLON.VertexBuffer.UV6Kind
  31184. * - BABYLON.VertexBuffer.ColorKind
  31185. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31186. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31187. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31188. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31189. * @returns a boolean
  31190. */
  31191. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31192. if (!this._geometry) {
  31193. if (this._delayInfo) {
  31194. return this._delayInfo.indexOf(kind) !== -1;
  31195. }
  31196. return false;
  31197. }
  31198. return this._geometry.isVerticesDataPresent(kind);
  31199. };
  31200. /**
  31201. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31202. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  31203. * - BABYLON.VertexBuffer.PositionKind
  31204. * - BABYLON.VertexBuffer.UVKind
  31205. * - BABYLON.VertexBuffer.UV2Kind
  31206. * - BABYLON.VertexBuffer.UV3Kind
  31207. * - BABYLON.VertexBuffer.UV4Kind
  31208. * - BABYLON.VertexBuffer.UV5Kind
  31209. * - BABYLON.VertexBuffer.UV6Kind
  31210. * - BABYLON.VertexBuffer.ColorKind
  31211. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31212. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31213. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31214. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31215. * @returns a boolean
  31216. */
  31217. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31218. if (!this._geometry) {
  31219. if (this._delayInfo) {
  31220. return this._delayInfo.indexOf(kind) !== -1;
  31221. }
  31222. return false;
  31223. }
  31224. return this._geometry.isVertexBufferUpdatable(kind);
  31225. };
  31226. /**
  31227. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  31228. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  31229. * - BABYLON.VertexBuffer.PositionKind
  31230. * - BABYLON.VertexBuffer.UVKind
  31231. * - BABYLON.VertexBuffer.UV2Kind
  31232. * - BABYLON.VertexBuffer.UV3Kind
  31233. * - BABYLON.VertexBuffer.UV4Kind
  31234. * - BABYLON.VertexBuffer.UV5Kind
  31235. * - BABYLON.VertexBuffer.UV6Kind
  31236. * - BABYLON.VertexBuffer.ColorKind
  31237. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31238. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31239. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31240. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31241. * @returns an array of strings
  31242. */
  31243. Mesh.prototype.getVerticesDataKinds = function () {
  31244. if (!this._geometry) {
  31245. var result = new Array();
  31246. if (this._delayInfo) {
  31247. this._delayInfo.forEach(function (kind, index, array) {
  31248. result.push(kind);
  31249. });
  31250. }
  31251. return result;
  31252. }
  31253. return this._geometry.getVerticesDataKinds();
  31254. };
  31255. /**
  31256. * Returns a positive integer : the total number of indices in this mesh geometry.
  31257. * @returns the numner of indices or zero if the mesh has no geometry.
  31258. */
  31259. Mesh.prototype.getTotalIndices = function () {
  31260. if (!this._geometry) {
  31261. return 0;
  31262. }
  31263. return this._geometry.getTotalIndices();
  31264. };
  31265. /**
  31266. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31267. * @param copyWhenShared If 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.
  31268. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31269. * @returns the indices array or an empty array if the mesh has no geometry
  31270. */
  31271. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31272. if (!this._geometry) {
  31273. return [];
  31274. }
  31275. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31276. };
  31277. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31278. get: function () {
  31279. return this._masterMesh !== null && this._masterMesh !== undefined;
  31280. },
  31281. enumerable: true,
  31282. configurable: true
  31283. });
  31284. /**
  31285. * Determine if the current mesh is ready to be rendered
  31286. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31287. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31288. * @returns true if all associated assets are ready (material, textures, shaders)
  31289. */
  31290. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31291. if (completeCheck === void 0) { completeCheck = false; }
  31292. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31293. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31294. return false;
  31295. }
  31296. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31297. return false;
  31298. }
  31299. if (!this.subMeshes || this.subMeshes.length === 0) {
  31300. return true;
  31301. }
  31302. if (!completeCheck) {
  31303. return true;
  31304. }
  31305. var engine = this.getEngine();
  31306. var scene = this.getScene();
  31307. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31308. this.computeWorldMatrix();
  31309. var mat = this.material || scene.defaultMaterial;
  31310. if (mat) {
  31311. if (mat.storeEffectOnSubMeshes) {
  31312. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31313. var subMesh = _a[_i];
  31314. var effectiveMaterial = subMesh.getMaterial();
  31315. if (effectiveMaterial) {
  31316. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31317. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31318. return false;
  31319. }
  31320. }
  31321. else {
  31322. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31323. return false;
  31324. }
  31325. }
  31326. }
  31327. }
  31328. }
  31329. else {
  31330. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31331. return false;
  31332. }
  31333. }
  31334. }
  31335. // Shadows
  31336. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31337. var light = _c[_b];
  31338. var generator = light.getShadowGenerator();
  31339. if (generator) {
  31340. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31341. var subMesh = _e[_d];
  31342. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31343. return false;
  31344. }
  31345. }
  31346. }
  31347. }
  31348. // LOD
  31349. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31350. var lod = _g[_f];
  31351. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31352. return false;
  31353. }
  31354. }
  31355. return true;
  31356. };
  31357. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31358. /**
  31359. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  31360. */
  31361. get: function () {
  31362. return this._areNormalsFrozen;
  31363. },
  31364. enumerable: true,
  31365. configurable: true
  31366. });
  31367. /**
  31368. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  31369. * @returns the current mesh
  31370. */
  31371. Mesh.prototype.freezeNormals = function () {
  31372. this._areNormalsFrozen = true;
  31373. return this;
  31374. };
  31375. /**
  31376. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  31377. * @returns the current mesh
  31378. */
  31379. Mesh.prototype.unfreezeNormals = function () {
  31380. this._areNormalsFrozen = false;
  31381. return this;
  31382. };
  31383. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31384. /**
  31385. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31386. */
  31387. set: function (count) {
  31388. this._overridenInstanceCount = count;
  31389. },
  31390. enumerable: true,
  31391. configurable: true
  31392. });
  31393. // Methods
  31394. /** @hidden */
  31395. Mesh.prototype._preActivate = function () {
  31396. var sceneRenderId = this.getScene().getRenderId();
  31397. if (this._preActivateId === sceneRenderId) {
  31398. return this;
  31399. }
  31400. this._preActivateId = sceneRenderId;
  31401. this._visibleInstances = null;
  31402. return this;
  31403. };
  31404. /** @hidden */
  31405. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31406. if (this._visibleInstances) {
  31407. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31408. }
  31409. return this;
  31410. };
  31411. /** @hidden */
  31412. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31413. if (!this._visibleInstances) {
  31414. this._visibleInstances = {};
  31415. this._visibleInstances.defaultRenderId = renderId;
  31416. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31417. }
  31418. if (!this._visibleInstances[renderId]) {
  31419. this._visibleInstances[renderId] = new Array();
  31420. }
  31421. this._visibleInstances[renderId].push(instance);
  31422. return this;
  31423. };
  31424. /**
  31425. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31426. * This means the mesh underlying bounding box and sphere are recomputed.
  31427. * @returns the current mesh
  31428. */
  31429. Mesh.prototype.refreshBoundingInfo = function () {
  31430. return this._refreshBoundingInfo(false);
  31431. };
  31432. /** @hidden */
  31433. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31434. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31435. return this;
  31436. }
  31437. var data = this._getPositionData(applySkeleton);
  31438. if (data) {
  31439. var bias = this.geometry ? this.geometry.boundingBias : null;
  31440. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  31441. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31442. }
  31443. if (this.subMeshes) {
  31444. for (var index = 0; index < this.subMeshes.length; index++) {
  31445. this.subMeshes[index].refreshBoundingInfo();
  31446. }
  31447. }
  31448. this._updateBoundingInfo();
  31449. return this;
  31450. };
  31451. Mesh.prototype._getPositionData = function (applySkeleton) {
  31452. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31453. if (data && applySkeleton && this.skeleton) {
  31454. data = BABYLON.Tools.Slice(data);
  31455. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31456. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31457. if (matricesWeightsData && matricesIndicesData) {
  31458. var needExtras = this.numBoneInfluencers > 4;
  31459. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31460. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31461. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31462. var tempVector = BABYLON.Tmp.Vector3[0];
  31463. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31464. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31465. var matWeightIdx = 0;
  31466. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31467. finalMatrix.reset();
  31468. var inf;
  31469. var weight;
  31470. for (inf = 0; inf < 4; inf++) {
  31471. weight = matricesWeightsData[matWeightIdx + inf];
  31472. if (weight > 0) {
  31473. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31474. finalMatrix.addToSelf(tempMatrix);
  31475. }
  31476. }
  31477. if (needExtras) {
  31478. for (inf = 0; inf < 4; inf++) {
  31479. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31480. if (weight > 0) {
  31481. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31482. finalMatrix.addToSelf(tempMatrix);
  31483. }
  31484. }
  31485. }
  31486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31487. tempVector.toArray(data, index);
  31488. }
  31489. }
  31490. }
  31491. return data;
  31492. };
  31493. /** @hidden */
  31494. Mesh.prototype._createGlobalSubMesh = function (force) {
  31495. var totalVertices = this.getTotalVertices();
  31496. if (!totalVertices || !this.getIndices()) {
  31497. return null;
  31498. }
  31499. // Check if we need to recreate the submeshes
  31500. if (this.subMeshes && this.subMeshes.length > 0) {
  31501. var ib = this.getIndices();
  31502. if (!ib) {
  31503. return null;
  31504. }
  31505. var totalIndices = ib.length;
  31506. var needToRecreate = false;
  31507. if (force) {
  31508. needToRecreate = true;
  31509. }
  31510. else {
  31511. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31512. var submesh = _a[_i];
  31513. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31514. needToRecreate = true;
  31515. break;
  31516. }
  31517. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31518. needToRecreate = true;
  31519. break;
  31520. }
  31521. }
  31522. }
  31523. if (!needToRecreate) {
  31524. return this.subMeshes[0];
  31525. }
  31526. }
  31527. this.releaseSubMeshes();
  31528. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31529. };
  31530. /**
  31531. * This function will subdivide the mesh into multiple submeshes
  31532. * @param count defines the expected number of submeshes
  31533. */
  31534. Mesh.prototype.subdivide = function (count) {
  31535. if (count < 1) {
  31536. return;
  31537. }
  31538. var totalIndices = this.getTotalIndices();
  31539. var subdivisionSize = (totalIndices / count) | 0;
  31540. var offset = 0;
  31541. // Ensure that subdivisionSize is a multiple of 3
  31542. while (subdivisionSize % 3 !== 0) {
  31543. subdivisionSize++;
  31544. }
  31545. this.releaseSubMeshes();
  31546. for (var index = 0; index < count; index++) {
  31547. if (offset >= totalIndices) {
  31548. break;
  31549. }
  31550. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31551. offset += subdivisionSize;
  31552. }
  31553. this.synchronizeInstances();
  31554. };
  31555. /**
  31556. * Copy a FloatArray into a specific associated vertex buffer
  31557. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31558. * - BABYLON.VertexBuffer.PositionKind
  31559. * - BABYLON.VertexBuffer.UVKind
  31560. * - BABYLON.VertexBuffer.UV2Kind
  31561. * - BABYLON.VertexBuffer.UV3Kind
  31562. * - BABYLON.VertexBuffer.UV4Kind
  31563. * - BABYLON.VertexBuffer.UV5Kind
  31564. * - BABYLON.VertexBuffer.UV6Kind
  31565. * - BABYLON.VertexBuffer.ColorKind
  31566. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31567. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31568. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31569. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31570. * @param data defines the data source
  31571. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31572. * @param stride defines the data stride size (can be null)
  31573. * @returns the current mesh
  31574. */
  31575. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31576. if (updatable === void 0) { updatable = false; }
  31577. if (!this._geometry) {
  31578. var vertexData = new BABYLON.VertexData();
  31579. vertexData.set(data, kind);
  31580. var scene = this.getScene();
  31581. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31582. }
  31583. else {
  31584. this._geometry.setVerticesData(kind, data, updatable, stride);
  31585. }
  31586. return this;
  31587. };
  31588. /**
  31589. * Flags an associated vertex buffer as updatable
  31590. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  31591. * - BABYLON.VertexBuffer.PositionKind
  31592. * - BABYLON.VertexBuffer.UVKind
  31593. * - BABYLON.VertexBuffer.UV2Kind
  31594. * - BABYLON.VertexBuffer.UV3Kind
  31595. * - BABYLON.VertexBuffer.UV4Kind
  31596. * - BABYLON.VertexBuffer.UV5Kind
  31597. * - BABYLON.VertexBuffer.UV6Kind
  31598. * - BABYLON.VertexBuffer.ColorKind
  31599. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31600. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31601. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31602. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31603. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  31604. */
  31605. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31606. if (updatable === void 0) { updatable = true; }
  31607. var vb = this.getVertexBuffer(kind);
  31608. if (!vb || vb.isUpdatable() === updatable) {
  31609. return;
  31610. }
  31611. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31612. };
  31613. /**
  31614. * Sets the mesh global Vertex Buffer
  31615. * @param buffer defines the buffer to use
  31616. * @returns the current mesh
  31617. */
  31618. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31619. if (!this._geometry) {
  31620. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31621. }
  31622. this._geometry.setVerticesBuffer(buffer);
  31623. return this;
  31624. };
  31625. /**
  31626. * Update a specific associated vertex buffer
  31627. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  31628. * - BABYLON.VertexBuffer.PositionKind
  31629. * - BABYLON.VertexBuffer.UVKind
  31630. * - BABYLON.VertexBuffer.UV2Kind
  31631. * - BABYLON.VertexBuffer.UV3Kind
  31632. * - BABYLON.VertexBuffer.UV4Kind
  31633. * - BABYLON.VertexBuffer.UV5Kind
  31634. * - BABYLON.VertexBuffer.UV6Kind
  31635. * - BABYLON.VertexBuffer.ColorKind
  31636. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31637. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31638. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31639. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31640. * @param data defines the data source
  31641. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  31642. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  31643. * @returns the current mesh
  31644. */
  31645. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31646. if (!this._geometry) {
  31647. return this;
  31648. }
  31649. if (!makeItUnique) {
  31650. this._geometry.updateVerticesData(kind, data, updateExtends);
  31651. }
  31652. else {
  31653. this.makeGeometryUnique();
  31654. this.updateVerticesData(kind, data, updateExtends, false);
  31655. }
  31656. return this;
  31657. };
  31658. /**
  31659. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31660. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31661. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  31662. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  31663. * @returns the current mesh
  31664. */
  31665. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31666. if (computeNormals === void 0) { computeNormals = true; }
  31667. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31668. if (!positions) {
  31669. return this;
  31670. }
  31671. positionFunction(positions);
  31672. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31673. if (computeNormals) {
  31674. var indices = this.getIndices();
  31675. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31676. if (!normals) {
  31677. return this;
  31678. }
  31679. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31680. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31681. }
  31682. return this;
  31683. };
  31684. /**
  31685. * Creates a un-shared specific occurence of the geometry for the mesh.
  31686. * @returns the current mesh
  31687. */
  31688. Mesh.prototype.makeGeometryUnique = function () {
  31689. if (!this._geometry) {
  31690. return this;
  31691. }
  31692. var oldGeometry = this._geometry;
  31693. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31694. oldGeometry.releaseForMesh(this, true);
  31695. geometry.applyToMesh(this);
  31696. return this;
  31697. };
  31698. /**
  31699. * Set the index buffer of this mesh
  31700. * @param indices defines the source data
  31701. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  31702. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  31703. * @returns the current mesh
  31704. */
  31705. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31706. if (totalVertices === void 0) { totalVertices = null; }
  31707. if (updatable === void 0) { updatable = false; }
  31708. if (!this._geometry) {
  31709. var vertexData = new BABYLON.VertexData();
  31710. vertexData.indices = indices;
  31711. var scene = this.getScene();
  31712. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31713. }
  31714. else {
  31715. this._geometry.setIndices(indices, totalVertices, updatable);
  31716. }
  31717. return this;
  31718. };
  31719. /**
  31720. * Update the current index buffer
  31721. * @param indices defines the source data
  31722. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  31723. * @returns the current mesh
  31724. */
  31725. Mesh.prototype.updateIndices = function (indices, offset) {
  31726. if (!this._geometry) {
  31727. return this;
  31728. }
  31729. this._geometry.updateIndices(indices, offset);
  31730. return this;
  31731. };
  31732. /**
  31733. * Invert the geometry to move from a right handed system to a left handed one.
  31734. * @returns the current mesh
  31735. */
  31736. Mesh.prototype.toLeftHanded = function () {
  31737. if (!this._geometry) {
  31738. return this;
  31739. }
  31740. this._geometry.toLeftHanded();
  31741. return this;
  31742. };
  31743. /** @hidden */
  31744. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31745. if (!this._geometry) {
  31746. return this;
  31747. }
  31748. var engine = this.getScene().getEngine();
  31749. // Wireframe
  31750. var indexToBind;
  31751. if (this._unIndexed) {
  31752. indexToBind = null;
  31753. }
  31754. else {
  31755. switch (fillMode) {
  31756. case BABYLON.Material.PointFillMode:
  31757. indexToBind = null;
  31758. break;
  31759. case BABYLON.Material.WireFrameFillMode:
  31760. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31761. break;
  31762. default:
  31763. case BABYLON.Material.TriangleFillMode:
  31764. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31765. break;
  31766. }
  31767. }
  31768. // VBOs
  31769. this._geometry._bind(effect, indexToBind);
  31770. return this;
  31771. };
  31772. /** @hidden */
  31773. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31774. if (alternate === void 0) { alternate = false; }
  31775. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31776. return this;
  31777. }
  31778. if (this._onBeforeDrawObservable) {
  31779. this._onBeforeDrawObservable.notifyObservers(this);
  31780. }
  31781. var scene = this.getScene();
  31782. var engine = scene.getEngine();
  31783. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31784. // or triangles as points
  31785. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31786. }
  31787. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31788. // Triangles as wireframe
  31789. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31790. }
  31791. else {
  31792. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31793. }
  31794. if (scene._isAlternateRenderingEnabled && !alternate) {
  31795. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31796. if (!effect || !scene.activeCamera) {
  31797. return this;
  31798. }
  31799. scene._switchToAlternateCameraConfiguration(true);
  31800. this._effectiveMaterial.bindView(effect);
  31801. this._effectiveMaterial.bindViewProjection(effect);
  31802. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31803. this._draw(subMesh, fillMode, instancesCount, true);
  31804. engine.setViewport(scene.activeCamera.viewport);
  31805. scene._switchToAlternateCameraConfiguration(false);
  31806. this._effectiveMaterial.bindView(effect);
  31807. this._effectiveMaterial.bindViewProjection(effect);
  31808. }
  31809. return this;
  31810. };
  31811. /**
  31812. * Registers for this mesh a javascript function called just before the rendering process
  31813. * @param func defines the function to call before rendering this mesh
  31814. * @returns the current mesh
  31815. */
  31816. Mesh.prototype.registerBeforeRender = function (func) {
  31817. this.onBeforeRenderObservable.add(func);
  31818. return this;
  31819. };
  31820. /**
  31821. * Disposes a previously registered javascript function called before the rendering
  31822. * @param func defines the function to remove
  31823. * @returns the current mesh
  31824. */
  31825. Mesh.prototype.unregisterBeforeRender = function (func) {
  31826. this.onBeforeRenderObservable.removeCallback(func);
  31827. return this;
  31828. };
  31829. /**
  31830. * Registers for this mesh a javascript function called just after the rendering is complete
  31831. * @param func defines the function to call after rendering this mesh
  31832. * @returns the current mesh
  31833. */
  31834. Mesh.prototype.registerAfterRender = function (func) {
  31835. this.onAfterRenderObservable.add(func);
  31836. return this;
  31837. };
  31838. /**
  31839. * Disposes a previously registered javascript function called after the rendering.
  31840. * @param func defines the function to remove
  31841. * @returns the current mesh
  31842. */
  31843. Mesh.prototype.unregisterAfterRender = function (func) {
  31844. this.onAfterRenderObservable.removeCallback(func);
  31845. return this;
  31846. };
  31847. /** @hidden */
  31848. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31849. var scene = this.getScene();
  31850. this._batchCache.mustReturn = false;
  31851. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31852. this._batchCache.visibleInstances[subMeshId] = null;
  31853. if (this._visibleInstances) {
  31854. var currentRenderId = scene.getRenderId();
  31855. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31856. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31857. var selfRenderId = this._renderId;
  31858. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31859. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31860. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31861. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31862. }
  31863. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31864. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31865. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31866. this._batchCache.mustReturn = true;
  31867. return this._batchCache;
  31868. }
  31869. if (currentRenderId !== selfRenderId) {
  31870. this._batchCache.renderSelf[subMeshId] = false;
  31871. }
  31872. }
  31873. this._renderIdForInstances[subMeshId] = currentRenderId;
  31874. }
  31875. return this._batchCache;
  31876. };
  31877. /** @hidden */
  31878. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31879. var visibleInstances = batch.visibleInstances[subMesh._id];
  31880. if (!visibleInstances) {
  31881. return this;
  31882. }
  31883. var matricesCount = visibleInstances.length + 1;
  31884. var bufferSize = matricesCount * 16 * 4;
  31885. var currentInstancesBufferSize = this._instancesBufferSize;
  31886. var instancesBuffer = this._instancesBuffer;
  31887. while (this._instancesBufferSize < bufferSize) {
  31888. this._instancesBufferSize *= 2;
  31889. }
  31890. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31891. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31892. }
  31893. var offset = 0;
  31894. var instancesCount = 0;
  31895. var world = this.getWorldMatrix();
  31896. if (batch.renderSelf[subMesh._id]) {
  31897. world.copyToArray(this._instancesData, offset);
  31898. offset += 16;
  31899. instancesCount++;
  31900. }
  31901. if (visibleInstances) {
  31902. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31903. var instance = visibleInstances[instanceIndex];
  31904. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31905. offset += 16;
  31906. instancesCount++;
  31907. }
  31908. }
  31909. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31910. if (instancesBuffer) {
  31911. instancesBuffer.dispose();
  31912. }
  31913. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31914. this._instancesBuffer = instancesBuffer;
  31915. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31916. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31917. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31918. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31919. }
  31920. else {
  31921. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31922. }
  31923. this._bind(subMesh, effect, fillMode);
  31924. this._draw(subMesh, fillMode, instancesCount);
  31925. engine.unbindInstanceAttributes();
  31926. return this;
  31927. };
  31928. /** @hidden */
  31929. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31930. var scene = this.getScene();
  31931. var engine = scene.getEngine();
  31932. if (hardwareInstancedRendering) {
  31933. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31934. }
  31935. else {
  31936. if (batch.renderSelf[subMesh._id]) {
  31937. // Draw
  31938. if (onBeforeDraw) {
  31939. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31940. }
  31941. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31942. }
  31943. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31944. if (visibleInstancesForSubMesh) {
  31945. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31946. var instance = visibleInstancesForSubMesh[instanceIndex];
  31947. // World
  31948. var world = instance.getWorldMatrix();
  31949. if (onBeforeDraw) {
  31950. onBeforeDraw(true, world, effectiveMaterial);
  31951. }
  31952. // Draw
  31953. this._draw(subMesh, fillMode);
  31954. }
  31955. }
  31956. }
  31957. return this;
  31958. };
  31959. /**
  31960. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  31961. * @param subMesh defines the subMesh to render
  31962. * @param enableAlphaMode defines if alpha mode can be changed
  31963. * @returns the current mesh
  31964. */
  31965. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31966. this._checkOcclusionQuery();
  31967. if (this._isOccluded) {
  31968. return this;
  31969. }
  31970. var scene = this.getScene();
  31971. // Managing instances
  31972. var batch = this._getInstancesRenderList(subMesh._id);
  31973. if (batch.mustReturn) {
  31974. return this;
  31975. }
  31976. // Checking geometry state
  31977. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31978. return this;
  31979. }
  31980. if (this._onBeforeRenderObservable) {
  31981. this._onBeforeRenderObservable.notifyObservers(this);
  31982. }
  31983. var engine = scene.getEngine();
  31984. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31985. // Material
  31986. var material = subMesh.getMaterial();
  31987. if (!material) {
  31988. return this;
  31989. }
  31990. this._effectiveMaterial = material;
  31991. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31992. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31993. return this;
  31994. }
  31995. }
  31996. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31997. return this;
  31998. }
  31999. // Alpha mode
  32000. if (enableAlphaMode) {
  32001. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32002. }
  32003. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  32004. var step = _a[_i];
  32005. step.action(this, subMesh, batch);
  32006. }
  32007. var effect;
  32008. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32009. effect = subMesh.effect;
  32010. }
  32011. else {
  32012. effect = this._effectiveMaterial.getEffect();
  32013. }
  32014. if (!effect) {
  32015. return this;
  32016. }
  32017. var sideOrientation = this.overrideMaterialSideOrientation;
  32018. if (sideOrientation == null) {
  32019. sideOrientation = this._effectiveMaterial.sideOrientation;
  32020. if (this._getWorldMatrixDeterminant() < 0) {
  32021. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32022. }
  32023. }
  32024. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32025. if (this._effectiveMaterial.forceDepthWrite) {
  32026. engine.setDepthWrite(true);
  32027. }
  32028. // Bind
  32029. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32030. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32031. this._bind(subMesh, effect, fillMode);
  32032. }
  32033. var world = this.getWorldMatrix();
  32034. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32035. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32036. }
  32037. else {
  32038. this._effectiveMaterial.bind(world, this);
  32039. }
  32040. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32041. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32042. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32043. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32044. }
  32045. // Draw
  32046. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32047. // Unbind
  32048. this._effectiveMaterial.unbind();
  32049. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  32050. var step = _c[_b];
  32051. step.action(this, subMesh, batch);
  32052. }
  32053. if (this._onAfterRenderObservable) {
  32054. this._onAfterRenderObservable.notifyObservers(this);
  32055. }
  32056. return this;
  32057. };
  32058. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32059. if (isInstance && effectiveMaterial) {
  32060. effectiveMaterial.bindOnlyWorldMatrix(world);
  32061. }
  32062. };
  32063. /**
  32064. * Normalize matrix weights so that all vertices have a total weight set to 1
  32065. */
  32066. Mesh.prototype.cleanMatrixWeights = function () {
  32067. var epsilon = 1e-3;
  32068. var noInfluenceBoneIndex = 0.0;
  32069. if (this.skeleton) {
  32070. noInfluenceBoneIndex = this.skeleton.bones.length;
  32071. }
  32072. else {
  32073. return;
  32074. }
  32075. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32076. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32077. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32078. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32079. var influencers = this.numBoneInfluencers;
  32080. var size = matricesWeights.length;
  32081. for (var i = 0; i < size; i += 4) {
  32082. var weight = 0.0;
  32083. var firstZeroWeight = -1;
  32084. for (var j = 0; j < 4; j++) {
  32085. var w = matricesWeights[i + j];
  32086. weight += w;
  32087. if (w < epsilon && firstZeroWeight < 0) {
  32088. firstZeroWeight = j;
  32089. }
  32090. }
  32091. if (matricesWeightsExtra) {
  32092. for (var j = 0; j < 4; j++) {
  32093. var w = matricesWeightsExtra[i + j];
  32094. weight += w;
  32095. if (w < epsilon && firstZeroWeight < 0) {
  32096. firstZeroWeight = j + 4;
  32097. }
  32098. }
  32099. }
  32100. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32101. firstZeroWeight = influencers - 1;
  32102. }
  32103. if (weight > epsilon) {
  32104. var mweight = 1.0 / weight;
  32105. for (var j = 0; j < 4; j++) {
  32106. matricesWeights[i + j] *= mweight;
  32107. }
  32108. if (matricesWeightsExtra) {
  32109. for (var j = 0; j < 4; j++) {
  32110. matricesWeightsExtra[i + j] *= mweight;
  32111. }
  32112. }
  32113. }
  32114. else {
  32115. if (firstZeroWeight >= 4) {
  32116. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32117. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32118. }
  32119. else {
  32120. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32121. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32122. }
  32123. }
  32124. }
  32125. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32126. if (matricesIndicesExtra) {
  32127. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32128. }
  32129. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32130. if (matricesWeightsExtra) {
  32131. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32132. }
  32133. };
  32134. /** @hidden */
  32135. Mesh.prototype._checkDelayState = function () {
  32136. var scene = this.getScene();
  32137. if (this._geometry) {
  32138. this._geometry.load(scene);
  32139. }
  32140. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32141. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32142. this._queueLoad(scene);
  32143. }
  32144. return this;
  32145. };
  32146. Mesh.prototype._queueLoad = function (scene) {
  32147. var _this = this;
  32148. scene._addPendingData(this);
  32149. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32150. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32151. if (data instanceof ArrayBuffer) {
  32152. _this._delayLoadingFunction(data, _this);
  32153. }
  32154. else {
  32155. _this._delayLoadingFunction(JSON.parse(data), _this);
  32156. }
  32157. _this.instances.forEach(function (instance) {
  32158. instance._syncSubMeshes();
  32159. });
  32160. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32161. scene._removePendingData(_this);
  32162. }, function () { }, scene.database, getBinaryData);
  32163. return this;
  32164. };
  32165. /**
  32166. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32167. * A mesh is in the frustum if its bounding box intersects the frustum
  32168. * @param frustumPlanes defines the frustum to test
  32169. * @returns true if the mesh is in the frustum planes
  32170. */
  32171. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32172. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32173. return false;
  32174. }
  32175. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32176. return false;
  32177. }
  32178. this._checkDelayState();
  32179. return true;
  32180. };
  32181. /**
  32182. * Sets the mesh material by the material or multiMaterial `id` property
  32183. * @param id is a string identifying the material or the multiMaterial
  32184. * @returns the current mesh
  32185. */
  32186. Mesh.prototype.setMaterialByID = function (id) {
  32187. var materials = this.getScene().materials;
  32188. var index;
  32189. for (index = materials.length - 1; index > -1; index--) {
  32190. if (materials[index].id === id) {
  32191. this.material = materials[index];
  32192. return this;
  32193. }
  32194. }
  32195. // Multi
  32196. var multiMaterials = this.getScene().multiMaterials;
  32197. for (index = multiMaterials.length - 1; index > -1; index--) {
  32198. if (multiMaterials[index].id === id) {
  32199. this.material = multiMaterials[index];
  32200. return this;
  32201. }
  32202. }
  32203. return this;
  32204. };
  32205. /**
  32206. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32207. * @returns an array of IAnimatable
  32208. */
  32209. Mesh.prototype.getAnimatables = function () {
  32210. var results = new Array();
  32211. if (this.material) {
  32212. results.push(this.material);
  32213. }
  32214. if (this.skeleton) {
  32215. results.push(this.skeleton);
  32216. }
  32217. return results;
  32218. };
  32219. /**
  32220. * Modifies the mesh geometry according to the passed transformation matrix.
  32221. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32222. * The mesh normals are modified using the same transformation.
  32223. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32224. * @param transform defines the transform matrix to use
  32225. * @see http://doc.babylonjs.com/resources/baking_transformations
  32226. * @returns the current mesh
  32227. */
  32228. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32229. // Position
  32230. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32231. return this;
  32232. }
  32233. var submeshes = this.subMeshes.splice(0);
  32234. this._resetPointsArrayCache();
  32235. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32236. var temp = new Array();
  32237. var index;
  32238. for (index = 0; index < data.length; index += 3) {
  32239. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32240. }
  32241. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32242. // Normals
  32243. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32244. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32245. temp = [];
  32246. for (index = 0; index < data.length; index += 3) {
  32247. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32248. }
  32249. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32250. }
  32251. // flip faces?
  32252. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32253. this.flipFaces();
  32254. }
  32255. // Restore submeshes
  32256. this.releaseSubMeshes();
  32257. this.subMeshes = submeshes;
  32258. return this;
  32259. };
  32260. /**
  32261. * Modifies the mesh geometry according to its own current World Matrix.
  32262. * The mesh World Matrix is then reset.
  32263. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32264. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32265. * @see http://doc.babylonjs.com/resources/baking_transformations
  32266. * @returns the current mesh
  32267. */
  32268. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32269. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32270. this.scaling.copyFromFloats(1, 1, 1);
  32271. this.position.copyFromFloats(0, 0, 0);
  32272. this.rotation.copyFromFloats(0, 0, 0);
  32273. //only if quaternion is already set
  32274. if (this.rotationQuaternion) {
  32275. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32276. }
  32277. this._worldMatrix = BABYLON.Matrix.Identity();
  32278. return this;
  32279. };
  32280. Object.defineProperty(Mesh.prototype, "_positions", {
  32281. // Cache
  32282. /** @hidden */
  32283. get: function () {
  32284. if (this._geometry) {
  32285. return this._geometry._positions;
  32286. }
  32287. return null;
  32288. },
  32289. enumerable: true,
  32290. configurable: true
  32291. });
  32292. /** @hidden */
  32293. Mesh.prototype._resetPointsArrayCache = function () {
  32294. if (this._geometry) {
  32295. this._geometry._resetPointsArrayCache();
  32296. }
  32297. return this;
  32298. };
  32299. /** @hidden */
  32300. Mesh.prototype._generatePointsArray = function () {
  32301. if (this._geometry) {
  32302. return this._geometry._generatePointsArray();
  32303. }
  32304. return false;
  32305. };
  32306. /**
  32307. * Returns a new Mesh object generated from the current mesh properties.
  32308. * This method must not get confused with createInstance()
  32309. * @param name is a string, the name given to the new mesh
  32310. * @param newParent can be any Node object (default `null`)
  32311. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  32312. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  32313. * @returns a new mesh
  32314. */
  32315. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32316. if (name === void 0) { name = ""; }
  32317. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32318. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32319. };
  32320. /**
  32321. * Releases resources associated with this mesh.
  32322. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32323. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32324. */
  32325. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32326. var _this = this;
  32327. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32328. this.morphTargetManager = null;
  32329. if (this._geometry) {
  32330. this._geometry.releaseForMesh(this, true);
  32331. }
  32332. if (this._onBeforeDrawObservable) {
  32333. this._onBeforeDrawObservable.clear();
  32334. }
  32335. if (this._onBeforeRenderObservable) {
  32336. this._onBeforeRenderObservable.clear();
  32337. }
  32338. if (this._onAfterRenderObservable) {
  32339. this._onAfterRenderObservable.clear();
  32340. }
  32341. // Sources
  32342. var meshes = this.getScene().meshes;
  32343. meshes.forEach(function (abstractMesh) {
  32344. var mesh = abstractMesh;
  32345. if (mesh._source && mesh._source === _this) {
  32346. mesh._source = null;
  32347. }
  32348. });
  32349. this._source = null;
  32350. // Instances
  32351. if (this._instancesBuffer) {
  32352. this._instancesBuffer.dispose();
  32353. this._instancesBuffer = null;
  32354. }
  32355. while (this.instances.length) {
  32356. this.instances[0].dispose();
  32357. }
  32358. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32359. };
  32360. /**
  32361. * Modifies the mesh geometry according to a displacement map.
  32362. * 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.
  32363. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32364. * @param url is a string, the URL from the image file is to be downloaded.
  32365. * @param minHeight is the lower limit of the displacement.
  32366. * @param maxHeight is the upper limit of the displacement.
  32367. * @param 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.
  32368. * @param uvOffset is an optional vector2 used to offset UV.
  32369. * @param uvScale is an optional vector2 used to scale UV.
  32370. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32371. * @returns the Mesh.
  32372. */
  32373. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  32374. var _this = this;
  32375. if (forceUpdate === void 0) { forceUpdate = false; }
  32376. var scene = this.getScene();
  32377. var onload = function (img) {
  32378. // Getting height map data
  32379. var canvas = document.createElement("canvas");
  32380. var context = canvas.getContext("2d");
  32381. var heightMapWidth = img.width;
  32382. var heightMapHeight = img.height;
  32383. canvas.width = heightMapWidth;
  32384. canvas.height = heightMapHeight;
  32385. context.drawImage(img, 0, 0);
  32386. // Create VertexData from map data
  32387. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32388. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32389. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  32390. //execute success callback, if set
  32391. if (onSuccess) {
  32392. onSuccess(_this);
  32393. }
  32394. };
  32395. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32396. return this;
  32397. };
  32398. /**
  32399. * Modifies the mesh geometry according to a displacementMap buffer.
  32400. * 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.
  32401. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32402. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  32403. * @param heightMapWidth is the width of the buffer image.
  32404. * @param heightMapHeight is the height of the buffer image.
  32405. * @param minHeight is the lower limit of the displacement.
  32406. * @param maxHeight is the upper limit of the displacement.
  32407. * @param 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.
  32408. * @param uvOffset is an optional vector2 used to offset UV.
  32409. * @param uvScale is an optional vector2 used to scale UV.
  32410. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
  32411. * @returns the Mesh.
  32412. */
  32413. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  32414. if (forceUpdate === void 0) { forceUpdate = false; }
  32415. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32416. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32417. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32418. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32419. return this;
  32420. }
  32421. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  32422. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32423. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32424. var position = BABYLON.Vector3.Zero();
  32425. var normal = BABYLON.Vector3.Zero();
  32426. var uv = BABYLON.Vector2.Zero();
  32427. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32428. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32429. for (var index = 0; index < positions.length; index += 3) {
  32430. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32431. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32432. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32433. // Compute height
  32434. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32435. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32436. var pos = (u + v * heightMapWidth) * 4;
  32437. var r = buffer[pos] / 255.0;
  32438. var g = buffer[pos + 1] / 255.0;
  32439. var b = buffer[pos + 2] / 255.0;
  32440. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32441. normal.normalize();
  32442. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32443. position = position.add(normal);
  32444. position.toArray(positions, index);
  32445. }
  32446. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32447. if (forceUpdate) {
  32448. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32449. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32450. }
  32451. else {
  32452. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32453. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32454. }
  32455. return this;
  32456. };
  32457. /**
  32458. * Modify the mesh to get a flat shading rendering.
  32459. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32460. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32461. * @returns current mesh
  32462. */
  32463. Mesh.prototype.convertToFlatShadedMesh = function () {
  32464. var kinds = this.getVerticesDataKinds();
  32465. var vbs = {};
  32466. var data = {};
  32467. var newdata = {};
  32468. var updatableNormals = false;
  32469. var kindIndex;
  32470. var kind;
  32471. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32472. kind = kinds[kindIndex];
  32473. var vertexBuffer = this.getVertexBuffer(kind);
  32474. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32475. updatableNormals = vertexBuffer.isUpdatable();
  32476. kinds.splice(kindIndex, 1);
  32477. kindIndex--;
  32478. continue;
  32479. }
  32480. vbs[kind] = vertexBuffer;
  32481. data[kind] = vbs[kind].getData();
  32482. newdata[kind] = [];
  32483. }
  32484. // Save previous submeshes
  32485. var previousSubmeshes = this.subMeshes.slice(0);
  32486. var indices = this.getIndices();
  32487. var totalIndices = this.getTotalIndices();
  32488. // Generating unique vertices per face
  32489. var index;
  32490. for (index = 0; index < totalIndices; index++) {
  32491. var vertexIndex = indices[index];
  32492. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32493. kind = kinds[kindIndex];
  32494. var stride = vbs[kind].getStrideSize();
  32495. for (var offset = 0; offset < stride; offset++) {
  32496. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32497. }
  32498. }
  32499. }
  32500. // Updating faces & normal
  32501. var normals = [];
  32502. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32503. for (index = 0; index < totalIndices; index += 3) {
  32504. indices[index] = index;
  32505. indices[index + 1] = index + 1;
  32506. indices[index + 2] = index + 2;
  32507. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32508. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32509. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32510. var p1p2 = p1.subtract(p2);
  32511. var p3p2 = p3.subtract(p2);
  32512. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32513. // Store same normals for every vertex
  32514. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32515. normals.push(normal.x);
  32516. normals.push(normal.y);
  32517. normals.push(normal.z);
  32518. }
  32519. }
  32520. this.setIndices(indices);
  32521. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32522. // Updating vertex buffers
  32523. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32524. kind = kinds[kindIndex];
  32525. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32526. }
  32527. // Updating submeshes
  32528. this.releaseSubMeshes();
  32529. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32530. var previousOne = previousSubmeshes[submeshIndex];
  32531. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32532. }
  32533. this.synchronizeInstances();
  32534. return this;
  32535. };
  32536. /**
  32537. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32538. * In other words, more vertices, no more indices and a single bigger VBO.
  32539. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32540. * @returns current mesh
  32541. */
  32542. Mesh.prototype.convertToUnIndexedMesh = function () {
  32543. var kinds = this.getVerticesDataKinds();
  32544. var vbs = {};
  32545. var data = {};
  32546. var newdata = {};
  32547. var kindIndex;
  32548. var kind;
  32549. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32550. kind = kinds[kindIndex];
  32551. var vertexBuffer = this.getVertexBuffer(kind);
  32552. vbs[kind] = vertexBuffer;
  32553. data[kind] = vbs[kind].getData();
  32554. newdata[kind] = [];
  32555. }
  32556. // Save previous submeshes
  32557. var previousSubmeshes = this.subMeshes.slice(0);
  32558. var indices = this.getIndices();
  32559. var totalIndices = this.getTotalIndices();
  32560. // Generating unique vertices per face
  32561. var index;
  32562. for (index = 0; index < totalIndices; index++) {
  32563. var vertexIndex = indices[index];
  32564. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32565. kind = kinds[kindIndex];
  32566. var stride = vbs[kind].getStrideSize();
  32567. for (var offset = 0; offset < stride; offset++) {
  32568. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32569. }
  32570. }
  32571. }
  32572. // Updating indices
  32573. for (index = 0; index < totalIndices; index += 3) {
  32574. indices[index] = index;
  32575. indices[index + 1] = index + 1;
  32576. indices[index + 2] = index + 2;
  32577. }
  32578. this.setIndices(indices);
  32579. // Updating vertex buffers
  32580. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32581. kind = kinds[kindIndex];
  32582. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32583. }
  32584. // Updating submeshes
  32585. this.releaseSubMeshes();
  32586. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32587. var previousOne = previousSubmeshes[submeshIndex];
  32588. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32589. }
  32590. this._unIndexed = true;
  32591. this.synchronizeInstances();
  32592. return this;
  32593. };
  32594. /**
  32595. * Inverses facet orientations.
  32596. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32597. * @param flipNormals will also inverts the normals
  32598. * @returns current mesh
  32599. */
  32600. Mesh.prototype.flipFaces = function (flipNormals) {
  32601. if (flipNormals === void 0) { flipNormals = false; }
  32602. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32603. var i;
  32604. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32605. for (i = 0; i < vertex_data.normals.length; i++) {
  32606. vertex_data.normals[i] *= -1;
  32607. }
  32608. }
  32609. if (vertex_data.indices) {
  32610. var temp;
  32611. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32612. // reassign indices
  32613. temp = vertex_data.indices[i + 1];
  32614. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32615. vertex_data.indices[i + 2] = temp;
  32616. }
  32617. }
  32618. vertex_data.applyToMesh(this);
  32619. return this;
  32620. };
  32621. // Instances
  32622. /**
  32623. * Creates a new InstancedMesh object from the mesh model.
  32624. * Warning : this method is not supported for Line mesh and LineSystem
  32625. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32626. * @param name defines the name of the new instance
  32627. * @returns a new InstancedMesh
  32628. */
  32629. Mesh.prototype.createInstance = function (name) {
  32630. return new BABYLON.InstancedMesh(name, this);
  32631. };
  32632. /**
  32633. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32634. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32635. * @returns the current mesh
  32636. */
  32637. Mesh.prototype.synchronizeInstances = function () {
  32638. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32639. var instance = this.instances[instanceIndex];
  32640. instance._syncSubMeshes();
  32641. }
  32642. return this;
  32643. };
  32644. /**
  32645. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32646. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32647. * This should be used together with the simplification to avoid disappearing triangles.
  32648. * @param successCallback an optional success callback to be called after the optimization finished.
  32649. * @returns the current mesh
  32650. */
  32651. Mesh.prototype.optimizeIndices = function (successCallback) {
  32652. var _this = this;
  32653. var indices = this.getIndices();
  32654. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32655. if (!positions || !indices) {
  32656. return this;
  32657. }
  32658. var vectorPositions = new Array();
  32659. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32660. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32661. }
  32662. var dupes = new Array();
  32663. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32664. var realPos = vectorPositions.length - 1 - iteration;
  32665. var testedPosition = vectorPositions[realPos];
  32666. for (var j = 0; j < realPos; ++j) {
  32667. var againstPosition = vectorPositions[j];
  32668. if (testedPosition.equals(againstPosition)) {
  32669. dupes[realPos] = j;
  32670. break;
  32671. }
  32672. }
  32673. }, function () {
  32674. for (var i = 0; i < indices.length; ++i) {
  32675. indices[i] = dupes[indices[i]] || indices[i];
  32676. }
  32677. //indices are now reordered
  32678. var originalSubMeshes = _this.subMeshes.slice(0);
  32679. _this.setIndices(indices);
  32680. _this.subMeshes = originalSubMeshes;
  32681. if (successCallback) {
  32682. successCallback(_this);
  32683. }
  32684. });
  32685. return this;
  32686. };
  32687. /**
  32688. * Serialize current mesh
  32689. * @param serializationObject defines the object which will receive the serialization data
  32690. */
  32691. Mesh.prototype.serialize = function (serializationObject) {
  32692. serializationObject.name = this.name;
  32693. serializationObject.id = this.id;
  32694. serializationObject.type = this.getClassName();
  32695. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32696. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32697. }
  32698. serializationObject.position = this.position.asArray();
  32699. if (this.rotationQuaternion) {
  32700. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32701. }
  32702. else if (this.rotation) {
  32703. serializationObject.rotation = this.rotation.asArray();
  32704. }
  32705. serializationObject.scaling = this.scaling.asArray();
  32706. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32707. serializationObject.isEnabled = this.isEnabled(false);
  32708. serializationObject.isVisible = this.isVisible;
  32709. serializationObject.infiniteDistance = this.infiniteDistance;
  32710. serializationObject.pickable = this.isPickable;
  32711. serializationObject.receiveShadows = this.receiveShadows;
  32712. serializationObject.billboardMode = this.billboardMode;
  32713. serializationObject.visibility = this.visibility;
  32714. serializationObject.checkCollisions = this.checkCollisions;
  32715. serializationObject.isBlocker = this.isBlocker;
  32716. // Parent
  32717. if (this.parent) {
  32718. serializationObject.parentId = this.parent.id;
  32719. }
  32720. // Geometry
  32721. serializationObject.isUnIndexed = this.isUnIndexed;
  32722. var geometry = this._geometry;
  32723. if (geometry) {
  32724. var geometryId = geometry.id;
  32725. serializationObject.geometryId = geometryId;
  32726. // SubMeshes
  32727. serializationObject.subMeshes = [];
  32728. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32729. var subMesh = this.subMeshes[subIndex];
  32730. serializationObject.subMeshes.push({
  32731. materialIndex: subMesh.materialIndex,
  32732. verticesStart: subMesh.verticesStart,
  32733. verticesCount: subMesh.verticesCount,
  32734. indexStart: subMesh.indexStart,
  32735. indexCount: subMesh.indexCount
  32736. });
  32737. }
  32738. }
  32739. // Material
  32740. if (this.material) {
  32741. serializationObject.materialId = this.material.id;
  32742. }
  32743. else {
  32744. this.material = null;
  32745. }
  32746. // Morph targets
  32747. if (this.morphTargetManager) {
  32748. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32749. }
  32750. // Skeleton
  32751. if (this.skeleton) {
  32752. serializationObject.skeletonId = this.skeleton.id;
  32753. }
  32754. // Physics
  32755. //TODO implement correct serialization for physics impostors.
  32756. var impostor = this.getPhysicsImpostor();
  32757. if (impostor) {
  32758. serializationObject.physicsMass = impostor.getParam("mass");
  32759. serializationObject.physicsFriction = impostor.getParam("friction");
  32760. serializationObject.physicsRestitution = impostor.getParam("mass");
  32761. serializationObject.physicsImpostor = impostor.type;
  32762. }
  32763. // Metadata
  32764. if (this.metadata) {
  32765. serializationObject.metadata = this.metadata;
  32766. }
  32767. // Instances
  32768. serializationObject.instances = [];
  32769. for (var index = 0; index < this.instances.length; index++) {
  32770. var instance = this.instances[index];
  32771. if (instance.doNotSerialize) {
  32772. continue;
  32773. }
  32774. var serializationInstance = {
  32775. name: instance.name,
  32776. id: instance.id,
  32777. position: instance.position.asArray(),
  32778. scaling: instance.scaling.asArray()
  32779. };
  32780. if (instance.parent) {
  32781. serializationInstance.parentId = instance.parent.id;
  32782. }
  32783. if (instance.rotationQuaternion) {
  32784. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32785. }
  32786. else if (instance.rotation) {
  32787. serializationInstance.rotation = instance.rotation.asArray();
  32788. }
  32789. serializationObject.instances.push(serializationInstance);
  32790. // Animations
  32791. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32792. serializationInstance.ranges = instance.serializeAnimationRanges();
  32793. }
  32794. //
  32795. // Animations
  32796. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32797. serializationObject.ranges = this.serializeAnimationRanges();
  32798. // Layer mask
  32799. serializationObject.layerMask = this.layerMask;
  32800. // Alpha
  32801. serializationObject.alphaIndex = this.alphaIndex;
  32802. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32803. // Overlay
  32804. serializationObject.overlayAlpha = this.overlayAlpha;
  32805. serializationObject.overlayColor = this.overlayColor.asArray();
  32806. serializationObject.renderOverlay = this.renderOverlay;
  32807. // Fog
  32808. serializationObject.applyFog = this.applyFog;
  32809. // Action Manager
  32810. if (this.actionManager) {
  32811. serializationObject.actions = this.actionManager.serialize(this.name);
  32812. }
  32813. };
  32814. /** @hidden */
  32815. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32816. if (!this.geometry) {
  32817. return;
  32818. }
  32819. this._markSubMeshesAsAttributesDirty();
  32820. var morphTargetManager = this._morphTargetManager;
  32821. if (morphTargetManager && morphTargetManager.vertexCount) {
  32822. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32823. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32824. this.morphTargetManager = null;
  32825. return;
  32826. }
  32827. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32828. var morphTarget = morphTargetManager.getActiveTarget(index);
  32829. var positions = morphTarget.getPositions();
  32830. if (!positions) {
  32831. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32832. return;
  32833. }
  32834. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32835. var normals = morphTarget.getNormals();
  32836. if (normals) {
  32837. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32838. }
  32839. var tangents = morphTarget.getTangents();
  32840. if (tangents) {
  32841. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32842. }
  32843. }
  32844. }
  32845. else {
  32846. var index = 0;
  32847. // Positions
  32848. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32849. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32850. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32851. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32852. }
  32853. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32854. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32855. }
  32856. index++;
  32857. }
  32858. }
  32859. };
  32860. // Statics
  32861. /**
  32862. * Returns a new Mesh object parsed from the source provided.
  32863. * @param parsedMesh is the source
  32864. * @param scene defines the hosting scene
  32865. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  32866. * @returns a new Mesh
  32867. */
  32868. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32869. var mesh;
  32870. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32871. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32872. }
  32873. else {
  32874. mesh = new Mesh(parsedMesh.name, scene);
  32875. }
  32876. mesh.id = parsedMesh.id;
  32877. if (BABYLON.Tags) {
  32878. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32879. }
  32880. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32881. if (parsedMesh.metadata !== undefined) {
  32882. mesh.metadata = parsedMesh.metadata;
  32883. }
  32884. if (parsedMesh.rotationQuaternion) {
  32885. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32886. }
  32887. else if (parsedMesh.rotation) {
  32888. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32889. }
  32890. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32891. if (parsedMesh.localMatrix) {
  32892. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32893. }
  32894. else if (parsedMesh.pivotMatrix) {
  32895. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32896. }
  32897. mesh.setEnabled(parsedMesh.isEnabled);
  32898. mesh.isVisible = parsedMesh.isVisible;
  32899. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32900. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32901. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32902. if (parsedMesh.applyFog !== undefined) {
  32903. mesh.applyFog = parsedMesh.applyFog;
  32904. }
  32905. if (parsedMesh.pickable !== undefined) {
  32906. mesh.isPickable = parsedMesh.pickable;
  32907. }
  32908. if (parsedMesh.alphaIndex !== undefined) {
  32909. mesh.alphaIndex = parsedMesh.alphaIndex;
  32910. }
  32911. mesh.receiveShadows = parsedMesh.receiveShadows;
  32912. mesh.billboardMode = parsedMesh.billboardMode;
  32913. if (parsedMesh.visibility !== undefined) {
  32914. mesh.visibility = parsedMesh.visibility;
  32915. }
  32916. mesh.checkCollisions = parsedMesh.checkCollisions;
  32917. if (parsedMesh.isBlocker !== undefined) {
  32918. mesh.isBlocker = parsedMesh.isBlocker;
  32919. }
  32920. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32921. // freezeWorldMatrix
  32922. if (parsedMesh.freezeWorldMatrix) {
  32923. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32924. }
  32925. // Parent
  32926. if (parsedMesh.parentId) {
  32927. mesh._waitingParentId = parsedMesh.parentId;
  32928. }
  32929. // Actions
  32930. if (parsedMesh.actions !== undefined) {
  32931. mesh._waitingActions = parsedMesh.actions;
  32932. }
  32933. // Overlay
  32934. if (parsedMesh.overlayAlpha !== undefined) {
  32935. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32936. }
  32937. if (parsedMesh.overlayColor !== undefined) {
  32938. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32939. }
  32940. if (parsedMesh.renderOverlay !== undefined) {
  32941. mesh.renderOverlay = parsedMesh.renderOverlay;
  32942. }
  32943. // Geometry
  32944. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32945. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32946. if (parsedMesh.delayLoadingFile) {
  32947. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32948. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32949. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32950. if (parsedMesh._binaryInfo) {
  32951. mesh._binaryInfo = parsedMesh._binaryInfo;
  32952. }
  32953. mesh._delayInfo = [];
  32954. if (parsedMesh.hasUVs) {
  32955. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32956. }
  32957. if (parsedMesh.hasUVs2) {
  32958. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32959. }
  32960. if (parsedMesh.hasUVs3) {
  32961. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32962. }
  32963. if (parsedMesh.hasUVs4) {
  32964. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32965. }
  32966. if (parsedMesh.hasUVs5) {
  32967. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32968. }
  32969. if (parsedMesh.hasUVs6) {
  32970. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32971. }
  32972. if (parsedMesh.hasColors) {
  32973. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32974. }
  32975. if (parsedMesh.hasMatricesIndices) {
  32976. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32977. }
  32978. if (parsedMesh.hasMatricesWeights) {
  32979. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32980. }
  32981. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32982. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32983. mesh._checkDelayState();
  32984. }
  32985. }
  32986. else {
  32987. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32988. }
  32989. // Material
  32990. if (parsedMesh.materialId) {
  32991. mesh.setMaterialByID(parsedMesh.materialId);
  32992. }
  32993. else {
  32994. mesh.material = null;
  32995. }
  32996. // Morph targets
  32997. if (parsedMesh.morphTargetManagerId > -1) {
  32998. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32999. }
  33000. // Skeleton
  33001. if (parsedMesh.skeletonId > -1) {
  33002. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33003. if (parsedMesh.numBoneInfluencers) {
  33004. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33005. }
  33006. }
  33007. // Animations
  33008. if (parsedMesh.animations) {
  33009. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33010. var parsedAnimation = parsedMesh.animations[animationIndex];
  33011. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33012. }
  33013. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33014. }
  33015. if (parsedMesh.autoAnimate) {
  33016. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33017. }
  33018. // Layer Mask
  33019. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33020. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33021. }
  33022. else {
  33023. mesh.layerMask = 0x0FFFFFFF;
  33024. }
  33025. // Physics
  33026. if (parsedMesh.physicsImpostor) {
  33027. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33028. mass: parsedMesh.physicsMass,
  33029. friction: parsedMesh.physicsFriction,
  33030. restitution: parsedMesh.physicsRestitution
  33031. }, scene);
  33032. }
  33033. // Instances
  33034. if (parsedMesh.instances) {
  33035. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33036. var parsedInstance = parsedMesh.instances[index];
  33037. var instance = mesh.createInstance(parsedInstance.name);
  33038. if (parsedInstance.id) {
  33039. instance.id = parsedInstance.id;
  33040. }
  33041. if (BABYLON.Tags) {
  33042. if (parsedInstance.tags) {
  33043. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33044. }
  33045. else {
  33046. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  33047. }
  33048. }
  33049. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33050. if (parsedInstance.parentId) {
  33051. instance._waitingParentId = parsedInstance.parentId;
  33052. }
  33053. if (parsedInstance.rotationQuaternion) {
  33054. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33055. }
  33056. else if (parsedInstance.rotation) {
  33057. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33058. }
  33059. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33060. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  33061. instance.checkCollisions = parsedInstance.checkCollisions;
  33062. }
  33063. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  33064. instance.isPickable = parsedInstance.pickable;
  33065. }
  33066. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  33067. instance.showBoundingBox = parsedInstance.showBoundingBox;
  33068. }
  33069. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33070. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  33071. }
  33072. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  33073. instance.alphaIndex = parsedInstance.alphaIndex;
  33074. }
  33075. // Physics
  33076. if (parsedInstance.physicsImpostor) {
  33077. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  33078. mass: parsedInstance.physicsMass,
  33079. friction: parsedInstance.physicsFriction,
  33080. restitution: parsedInstance.physicsRestitution
  33081. }, scene);
  33082. }
  33083. // Animation
  33084. if (parsedInstance.animations) {
  33085. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  33086. parsedAnimation = parsedInstance.animations[animationIndex];
  33087. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33088. }
  33089. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  33090. if (parsedInstance.autoAnimate) {
  33091. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  33092. }
  33093. }
  33094. }
  33095. }
  33096. return mesh;
  33097. };
  33098. /**
  33099. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  33100. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33101. * @param name defines the name of the mesh to create
  33102. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33103. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  33104. * @param closePath creates a seam between the first and the last points of each path of the path array
  33105. * @param offset is taken in account only if the `pathArray` is containing a single path
  33106. * @param scene defines the hosting scene
  33107. * @param updatable defines if the mesh must be flagged as updatable
  33108. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33109. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  33110. * @returns a new Mesh
  33111. */
  33112. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33113. if (closeArray === void 0) { closeArray = false; }
  33114. if (updatable === void 0) { updatable = false; }
  33115. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33116. pathArray: pathArray,
  33117. closeArray: closeArray,
  33118. closePath: closePath,
  33119. offset: offset,
  33120. updatable: updatable,
  33121. sideOrientation: sideOrientation,
  33122. instance: instance
  33123. }, scene);
  33124. };
  33125. /**
  33126. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  33127. * @param name defines the name of the mesh to create
  33128. * @param radius sets the radius size (float) of the polygon (default 0.5)
  33129. * @param 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
  33130. * @param scene defines the hosting scene
  33131. * @param updatable defines if the mesh must be flagged as updatable
  33132. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33133. * @returns a new Mesh
  33134. */
  33135. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33136. if (scene === void 0) { scene = null; }
  33137. var options = {
  33138. radius: radius,
  33139. tessellation: tessellation,
  33140. sideOrientation: sideOrientation,
  33141. updatable: updatable
  33142. };
  33143. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33144. };
  33145. /**
  33146. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  33147. * @param name defines the name of the mesh to create
  33148. * @param size sets the size (float) of each box side (default 1)
  33149. * @param scene defines the hosting scene
  33150. * @param updatable defines if the mesh must be flagged as updatable
  33151. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33152. * @returns a new Mesh
  33153. */
  33154. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33155. if (scene === void 0) { scene = null; }
  33156. var options = {
  33157. size: size,
  33158. sideOrientation: sideOrientation,
  33159. updatable: updatable
  33160. };
  33161. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33162. };
  33163. /**
  33164. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  33165. * @param name defines the name of the mesh to create
  33166. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  33167. * @param diameter sets the diameter size (float) of the sphere (default 1)
  33168. * @param scene defines the hosting scene
  33169. * @param updatable defines if the mesh must be flagged as updatable
  33170. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33171. * @returns a new Mesh
  33172. */
  33173. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33174. var options = {
  33175. segments: segments,
  33176. diameterX: diameter,
  33177. diameterY: diameter,
  33178. diameterZ: diameter,
  33179. sideOrientation: sideOrientation,
  33180. updatable: updatable
  33181. };
  33182. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33183. };
  33184. /**
  33185. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  33186. * @param name defines the name of the mesh to create
  33187. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  33188. * @param diameterTop set the top cap diameter (floats, default 1)
  33189. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  33190. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  33191. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  33192. * @param scene defines the hosting scene
  33193. * @param updatable defines if the mesh must be flagged as updatable
  33194. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33195. * @returns a new Mesh
  33196. */
  33197. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33198. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33199. if (scene !== undefined) {
  33200. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33201. updatable = scene;
  33202. }
  33203. scene = subdivisions;
  33204. subdivisions = 1;
  33205. }
  33206. var options = {
  33207. height: height,
  33208. diameterTop: diameterTop,
  33209. diameterBottom: diameterBottom,
  33210. tessellation: tessellation,
  33211. subdivisions: subdivisions,
  33212. sideOrientation: sideOrientation,
  33213. updatable: updatable
  33214. };
  33215. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33216. };
  33217. // Torus (Code from SharpDX.org)
  33218. /**
  33219. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  33220. * @param name defines the name of the mesh to create
  33221. * @param diameter sets the diameter size (float) of the torus (default 1)
  33222. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  33223. * @param tessellation sets the number of torus sides (postive integer, default 16)
  33224. * @param scene defines the hosting scene
  33225. * @param updatable defines if the mesh must be flagged as updatable
  33226. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33227. * @returns a new Mesh
  33228. */
  33229. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33230. var options = {
  33231. diameter: diameter,
  33232. thickness: thickness,
  33233. tessellation: tessellation,
  33234. sideOrientation: sideOrientation,
  33235. updatable: updatable
  33236. };
  33237. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33238. };
  33239. /**
  33240. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  33241. * @param name defines the name of the mesh to create
  33242. * @param radius sets the global radius size (float) of the torus knot (default 2)
  33243. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  33244. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  33245. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  33246. * @param p the number of windings on X axis (positive integers, default 2)
  33247. * @param q the number of windings on Y axis (positive integers, default 3)
  33248. * @param scene defines the hosting scene
  33249. * @param updatable defines if the mesh must be flagged as updatable
  33250. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33251. * @returns a new Mesh
  33252. */
  33253. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33254. var options = {
  33255. radius: radius,
  33256. tube: tube,
  33257. radialSegments: radialSegments,
  33258. tubularSegments: tubularSegments,
  33259. p: p,
  33260. q: q,
  33261. sideOrientation: sideOrientation,
  33262. updatable: updatable
  33263. };
  33264. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33265. };
  33266. /**
  33267. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  33268. * @param name defines the name of the mesh to create
  33269. * @param points is an array successive Vector3
  33270. * @param scene defines the hosting scene
  33271. * @param updatable defines if the mesh must be flagged as updatable
  33272. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  33273. * @returns a new Mesh
  33274. */
  33275. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33276. if (scene === void 0) { scene = null; }
  33277. if (updatable === void 0) { updatable = false; }
  33278. if (instance === void 0) { instance = null; }
  33279. var options = {
  33280. points: points,
  33281. updatable: updatable,
  33282. instance: instance
  33283. };
  33284. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33285. };
  33286. /**
  33287. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  33288. * @param name defines the name of the mesh to create
  33289. * @param points is an array successive Vector3
  33290. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  33291. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  33292. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  33293. * @param scene defines the hosting scene
  33294. * @param updatable defines if the mesh must be flagged as updatable
  33295. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  33296. * @returns a new Mesh
  33297. */
  33298. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33299. if (scene === void 0) { scene = null; }
  33300. var options = {
  33301. points: points,
  33302. dashSize: dashSize,
  33303. gapSize: gapSize,
  33304. dashNb: dashNb,
  33305. updatable: updatable,
  33306. instance: instance
  33307. };
  33308. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33309. };
  33310. /**
  33311. * Creates a polygon mesh.
  33312. * Please consider using the same method from the MeshBuilder class instead.
  33313. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33314. * 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.
  33315. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33317. * Remember you can only change the shape positions, not their number when updating a polygon.
  33318. */
  33319. /**
  33320. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  33321. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  33322. * @param name defines the name of the mesh to create
  33323. * @param 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
  33324. * @param scene defines the hosting scene
  33325. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33326. * @param updatable defines if the mesh must be flagged as updatable
  33327. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33328. * @returns a new Mesh
  33329. */
  33330. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33331. var options = {
  33332. shape: shape,
  33333. holes: holes,
  33334. updatable: updatable,
  33335. sideOrientation: sideOrientation
  33336. };
  33337. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33338. };
  33339. /**
  33340. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  33341. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  33342. * @param name defines the name of the mesh to create
  33343. * @param 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
  33344. * @param depth defines the height of extrusion
  33345. * @param scene defines the hosting scene
  33346. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  33347. * @param updatable defines if the mesh must be flagged as updatable
  33348. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33349. * @returns a new Mesh
  33350. */
  33351. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33352. var options = {
  33353. shape: shape,
  33354. holes: holes,
  33355. depth: depth,
  33356. updatable: updatable,
  33357. sideOrientation: sideOrientation
  33358. };
  33359. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33360. };
  33361. /**
  33362. * Creates an extruded shape mesh.
  33363. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  33364. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33365. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33366. * @param name defines the name of the mesh to create
  33367. * @param 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 extruded along the Z axis
  33368. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33369. * @param scale is the value to scale the shape
  33370. * @param rotation 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
  33371. * @param 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
  33372. * @param scene defines the hosting scene
  33373. * @param updatable defines if the mesh must be flagged as updatable
  33374. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33375. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  33376. * @returns a new Mesh
  33377. */
  33378. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33379. if (scene === void 0) { scene = null; }
  33380. var options = {
  33381. shape: shape,
  33382. path: path,
  33383. scale: scale,
  33384. rotation: rotation,
  33385. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33386. sideOrientation: sideOrientation,
  33387. instance: instance,
  33388. updatable: updatable
  33389. };
  33390. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33391. };
  33392. /**
  33393. * Creates an custom extruded shape mesh.
  33394. * The custom extrusion is a parametric shape.
  33395. * It has no predefined shape. Its final shape will depend on the input parameters.
  33396. * Please consider using the same method from the MeshBuilder class instead
  33397. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33398. * @param name defines the name of the mesh to create
  33399. * @param 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 extruded along the Z axis
  33400. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  33401. * @param scaleFunction is a custom Javascript function called on each path point
  33402. * @param rotationFunction is a custom Javascript function called on each path point
  33403. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  33404. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  33405. * @param 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
  33406. * @param scene defines the hosting scene
  33407. * @param updatable defines if the mesh must be flagged as updatable
  33408. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33409. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  33410. * @returns a new Mesh
  33411. */
  33412. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33413. var options = {
  33414. shape: shape,
  33415. path: path,
  33416. scaleFunction: scaleFunction,
  33417. rotationFunction: rotationFunction,
  33418. ribbonCloseArray: ribbonCloseArray,
  33419. ribbonClosePath: ribbonClosePath,
  33420. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33421. sideOrientation: sideOrientation,
  33422. instance: instance,
  33423. updatable: updatable
  33424. };
  33425. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33426. };
  33427. /**
  33428. * Creates lathe mesh.
  33429. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33430. * Please consider using the same method from the MeshBuilder class instead
  33431. * @param name defines the name of the mesh to create
  33432. * @param 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  33433. * @param radius is the radius value of the lathe
  33434. * @param tessellation is the side number of the lathe.
  33435. * @param scene defines the hosting scene
  33436. * @param updatable defines if the mesh must be flagged as updatable
  33437. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33438. * @returns a new Mesh
  33439. */
  33440. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33441. var options = {
  33442. shape: shape,
  33443. radius: radius,
  33444. tessellation: tessellation,
  33445. sideOrientation: sideOrientation,
  33446. updatable: updatable
  33447. };
  33448. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33449. };
  33450. /**
  33451. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  33452. * @param name defines the name of the mesh to create
  33453. * @param size sets the size (float) of both sides of the plane at once (default 1)
  33454. * @param scene defines the hosting scene
  33455. * @param updatable defines if the mesh must be flagged as updatable
  33456. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33457. * @returns a new Mesh
  33458. */
  33459. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33460. var options = {
  33461. size: size,
  33462. width: size,
  33463. height: size,
  33464. sideOrientation: sideOrientation,
  33465. updatable: updatable
  33466. };
  33467. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33468. };
  33469. /**
  33470. * Creates a ground mesh.
  33471. * Please consider using the same method from the MeshBuilder class instead
  33472. * @param name defines the name of the mesh to create
  33473. * @param width set the width of the ground
  33474. * @param height set the height of the ground
  33475. * @param subdivisions sets the number of subdivisions per side
  33476. * @param scene defines the hosting scene
  33477. * @param updatable defines if the mesh must be flagged as updatable
  33478. * @returns a new Mesh
  33479. */
  33480. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33481. var options = {
  33482. width: width,
  33483. height: height,
  33484. subdivisions: subdivisions,
  33485. updatable: updatable
  33486. };
  33487. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33488. };
  33489. /**
  33490. * Creates a tiled ground mesh.
  33491. * Please consider using the same method from the MeshBuilder class instead
  33492. * @param name defines the name of the mesh to create
  33493. * @param xmin set the ground minimum X coordinate
  33494. * @param zmin set the ground minimum Y coordinate
  33495. * @param xmax set the ground maximum X coordinate
  33496. * @param zmax set the ground maximum Z coordinate
  33497. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  33498. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  33499. * @param scene defines the hosting scene
  33500. * @param updatable defines if the mesh must be flagged as updatable
  33501. * @returns a new Mesh
  33502. */
  33503. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33504. var options = {
  33505. xmin: xmin,
  33506. zmin: zmin,
  33507. xmax: xmax,
  33508. zmax: zmax,
  33509. subdivisions: subdivisions,
  33510. precision: precision,
  33511. updatable: updatable
  33512. };
  33513. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33514. };
  33515. /**
  33516. * Creates a ground mesh from a height map.
  33517. * Please consider using the same method from the MeshBuilder class instead
  33518. * @see http://doc.babylonjs.com/babylon101/height_map
  33519. * @param name defines the name of the mesh to create
  33520. * @param url sets the URL of the height map image resource
  33521. * @param width set the ground width size
  33522. * @param height set the ground height size
  33523. * @param subdivisions sets the number of subdivision per side
  33524. * @param minHeight is the minimum altitude on the ground
  33525. * @param maxHeight is the maximum altitude on the ground
  33526. * @param scene defines the hosting scene
  33527. * @param updatable defines if the mesh must be flagged as updatable
  33528. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  33529. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  33530. * @returns a new Mesh
  33531. */
  33532. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  33533. var options = {
  33534. width: width,
  33535. height: height,
  33536. subdivisions: subdivisions,
  33537. minHeight: minHeight,
  33538. maxHeight: maxHeight,
  33539. updatable: updatable,
  33540. onReady: onReady,
  33541. alphaFilter: alphaFilter
  33542. };
  33543. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33544. };
  33545. /**
  33546. * Creates a tube mesh.
  33547. * The tube is a parametric shape.
  33548. * It has no predefined shape. Its final shape will depend on the input parameters.
  33549. * Please consider using the same method from the MeshBuilder class instead
  33550. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  33551. * @param name defines the name of the mesh to create
  33552. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  33553. * @param radius sets the tube radius size
  33554. * @param tessellation is the number of sides on the tubular surface
  33555. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  33556. * @param 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
  33557. * @param scene defines the hosting scene
  33558. * @param updatable defines if the mesh must be flagged as updatable
  33559. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  33560. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  33561. * @returns a new Mesh
  33562. */
  33563. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33564. var options = {
  33565. path: path,
  33566. radius: radius,
  33567. tessellation: tessellation,
  33568. radiusFunction: radiusFunction,
  33569. arc: 1,
  33570. cap: cap,
  33571. updatable: updatable,
  33572. sideOrientation: sideOrientation,
  33573. instance: instance
  33574. };
  33575. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33576. };
  33577. /**
  33578. * Creates a polyhedron mesh.
  33579. * Please consider using the same method from the MeshBuilder class instead.
  33580. * * 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 to choose the wanted type
  33581. * * The parameter `size` (positive float, default 1) sets the polygon size
  33582. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  33583. * * 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`
  33584. * * 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
  33585. * * 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)`)
  33586. * * 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
  33587. * * 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
  33588. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33589. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33590. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33591. * @param name defines the name of the mesh to create
  33592. * @param options defines the options used to create the mesh
  33593. * @param scene defines the hosting scene
  33594. * @returns a new Mesh
  33595. */
  33596. Mesh.CreatePolyhedron = function (name, options, scene) {
  33597. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33598. };
  33599. /**
  33600. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  33601. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  33602. * * 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`)
  33603. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  33604. * * 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
  33605. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33606. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33607. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  33608. * @param name defines the name of the mesh
  33609. * @param options defines the options used to create the mesh
  33610. * @param scene defines the hosting scene
  33611. * @returns a new Mesh
  33612. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  33613. */
  33614. Mesh.CreateIcoSphere = function (name, options, scene) {
  33615. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33616. };
  33617. /**
  33618. * Creates a decal mesh.
  33619. * Please consider using the same method from the MeshBuilder class instead.
  33620. * A decal is a mesh usually applied as a model onto the surface of another mesh
  33621. * @param name defines the name of the mesh
  33622. * @param sourceMesh defines the mesh receiving the decal
  33623. * @param position sets the position of the decal in world coordinates
  33624. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  33625. * @param size sets the decal scaling
  33626. * @param angle sets the angle to rotate the decal
  33627. * @returns a new Mesh
  33628. */
  33629. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33630. var options = {
  33631. position: position,
  33632. normal: normal,
  33633. size: size,
  33634. angle: angle
  33635. };
  33636. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33637. };
  33638. // Skeletons
  33639. /**
  33640. * Prepare internal position array for software CPU skinning
  33641. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  33642. */
  33643. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33644. if (!this._sourcePositions) {
  33645. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33646. if (!source) {
  33647. return this._sourcePositions;
  33648. }
  33649. this._sourcePositions = new Float32Array(source);
  33650. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33651. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33652. }
  33653. }
  33654. return this._sourcePositions;
  33655. };
  33656. /**
  33657. * Prepare internal normal array for software CPU skinning
  33658. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33659. */
  33660. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33661. if (!this._sourceNormals) {
  33662. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33663. if (!source) {
  33664. return this._sourceNormals;
  33665. }
  33666. this._sourceNormals = new Float32Array(source);
  33667. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33668. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33669. }
  33670. }
  33671. return this._sourceNormals;
  33672. };
  33673. /**
  33674. * Updates the vertex buffer by applying transformation from the bones
  33675. * @param skeleton defines the skeleton to apply to current mesh
  33676. * @returns the current mesh
  33677. */
  33678. Mesh.prototype.applySkeleton = function (skeleton) {
  33679. if (!this.geometry) {
  33680. return this;
  33681. }
  33682. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  33683. return this;
  33684. }
  33685. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  33686. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33687. return this;
  33688. }
  33689. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33690. return this;
  33691. }
  33692. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33693. return this;
  33694. }
  33695. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33696. return this;
  33697. }
  33698. if (!this._sourcePositions) {
  33699. var submeshes = this.subMeshes.slice();
  33700. this.setPositionsForCPUSkinning();
  33701. this.subMeshes = submeshes;
  33702. }
  33703. if (!this._sourceNormals) {
  33704. this.setNormalsForCPUSkinning();
  33705. }
  33706. // positionsData checks for not being Float32Array will only pass at most once
  33707. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33708. if (!positionsData) {
  33709. return this;
  33710. }
  33711. if (!(positionsData instanceof Float32Array)) {
  33712. positionsData = new Float32Array(positionsData);
  33713. }
  33714. // normalsData checks for not being Float32Array will only pass at most once
  33715. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33716. if (!normalsData) {
  33717. return this;
  33718. }
  33719. if (!(normalsData instanceof Float32Array)) {
  33720. normalsData = new Float32Array(normalsData);
  33721. }
  33722. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33723. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33724. if (!matricesWeightsData || !matricesIndicesData) {
  33725. return this;
  33726. }
  33727. var needExtras = this.numBoneInfluencers > 4;
  33728. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33729. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33730. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33731. var tempVector3 = BABYLON.Vector3.Zero();
  33732. var finalMatrix = new BABYLON.Matrix();
  33733. var tempMatrix = new BABYLON.Matrix();
  33734. var matWeightIdx = 0;
  33735. var inf;
  33736. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33737. var weight;
  33738. for (inf = 0; inf < 4; inf++) {
  33739. weight = matricesWeightsData[matWeightIdx + inf];
  33740. if (weight > 0) {
  33741. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33742. finalMatrix.addToSelf(tempMatrix);
  33743. }
  33744. }
  33745. if (needExtras) {
  33746. for (inf = 0; inf < 4; inf++) {
  33747. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33748. if (weight > 0) {
  33749. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33750. finalMatrix.addToSelf(tempMatrix);
  33751. }
  33752. }
  33753. }
  33754. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33755. tempVector3.toArray(positionsData, index);
  33756. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33757. tempVector3.toArray(normalsData, index);
  33758. finalMatrix.reset();
  33759. }
  33760. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33761. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33762. return this;
  33763. };
  33764. // Tools
  33765. /**
  33766. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  33767. * @param meshes defines the list of meshes to scan
  33768. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  33769. */
  33770. Mesh.MinMax = function (meshes) {
  33771. var minVector = null;
  33772. var maxVector = null;
  33773. meshes.forEach(function (mesh, index, array) {
  33774. var boundingInfo = mesh.getBoundingInfo();
  33775. var boundingBox = boundingInfo.boundingBox;
  33776. if (!minVector || !maxVector) {
  33777. minVector = boundingBox.minimumWorld;
  33778. maxVector = boundingBox.maximumWorld;
  33779. }
  33780. else {
  33781. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33782. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33783. }
  33784. });
  33785. if (!minVector || !maxVector) {
  33786. return {
  33787. min: BABYLON.Vector3.Zero(),
  33788. max: BABYLON.Vector3.Zero()
  33789. };
  33790. }
  33791. return {
  33792. min: minVector,
  33793. max: maxVector
  33794. };
  33795. };
  33796. /**
  33797. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  33798. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  33799. * @returns a vector3
  33800. */
  33801. Mesh.Center = function (meshesOrMinMaxVector) {
  33802. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33803. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33804. };
  33805. /**
  33806. * Merge the array of meshes into a single mesh for performance reasons.
  33807. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  33808. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  33809. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  33810. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33811. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  33812. * @returns a new mesh
  33813. */
  33814. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33815. if (disposeSource === void 0) { disposeSource = true; }
  33816. var index;
  33817. if (!allow32BitsIndices) {
  33818. var totalVertices = 0;
  33819. // Counting vertices
  33820. for (index = 0; index < meshes.length; index++) {
  33821. if (meshes[index]) {
  33822. totalVertices += meshes[index].getTotalVertices();
  33823. if (totalVertices > 65536) {
  33824. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33825. return null;
  33826. }
  33827. }
  33828. }
  33829. }
  33830. // Merge
  33831. var vertexData = null;
  33832. var otherVertexData;
  33833. var indiceArray = new Array();
  33834. var source = null;
  33835. for (index = 0; index < meshes.length; index++) {
  33836. if (meshes[index]) {
  33837. var wm = meshes[index].computeWorldMatrix(true);
  33838. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  33839. otherVertexData.transform(wm);
  33840. if (vertexData) {
  33841. vertexData.merge(otherVertexData, allow32BitsIndices);
  33842. }
  33843. else {
  33844. vertexData = otherVertexData;
  33845. source = meshes[index];
  33846. }
  33847. if (subdivideWithSubMeshes) {
  33848. indiceArray.push(meshes[index].getTotalIndices());
  33849. }
  33850. }
  33851. }
  33852. source = source;
  33853. if (!meshSubclass) {
  33854. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33855. }
  33856. vertexData.applyToMesh(meshSubclass);
  33857. // Setting properties
  33858. meshSubclass.material = source.material;
  33859. meshSubclass.checkCollisions = source.checkCollisions;
  33860. // Cleaning
  33861. if (disposeSource) {
  33862. for (index = 0; index < meshes.length; index++) {
  33863. if (meshes[index]) {
  33864. meshes[index].dispose();
  33865. }
  33866. }
  33867. }
  33868. // Subdivide
  33869. if (subdivideWithSubMeshes) {
  33870. //-- removal of global submesh
  33871. meshSubclass.releaseSubMeshes();
  33872. index = 0;
  33873. var offset = 0;
  33874. //-- apply subdivision according to index table
  33875. while (index < indiceArray.length) {
  33876. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33877. offset += indiceArray[index];
  33878. index++;
  33879. }
  33880. }
  33881. return meshSubclass;
  33882. };
  33883. // Consts
  33884. /**
  33885. * Mesh side orientation : usually the external or front surface
  33886. */
  33887. Mesh.FRONTSIDE = 0;
  33888. /**
  33889. * Mesh side orientation : usually the internal or back surface
  33890. */
  33891. Mesh.BACKSIDE = 1;
  33892. /**
  33893. * Mesh side orientation : both internal and external or front and back surfaces
  33894. */
  33895. Mesh.DOUBLESIDE = 2;
  33896. /**
  33897. * Mesh side orientation : by default, `FRONTSIDE`
  33898. */
  33899. Mesh.DEFAULTSIDE = 0;
  33900. /**
  33901. * Mesh cap setting : no cap
  33902. */
  33903. Mesh.NO_CAP = 0;
  33904. /**
  33905. * Mesh cap setting : one cap at the beginning of the mesh
  33906. */
  33907. Mesh.CAP_START = 1;
  33908. /**
  33909. * Mesh cap setting : one cap at the end of the mesh
  33910. */
  33911. Mesh.CAP_END = 2;
  33912. /**
  33913. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  33914. */
  33915. Mesh.CAP_ALL = 3;
  33916. return Mesh;
  33917. }(BABYLON.AbstractMesh));
  33918. BABYLON.Mesh = Mesh;
  33919. })(BABYLON || (BABYLON = {}));
  33920. //# sourceMappingURL=babylon.mesh.js.map
  33921. var BABYLON;
  33922. (function (BABYLON) {
  33923. var BaseSubMesh = /** @class */ (function () {
  33924. function BaseSubMesh() {
  33925. }
  33926. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33927. get: function () {
  33928. return this._materialEffect;
  33929. },
  33930. enumerable: true,
  33931. configurable: true
  33932. });
  33933. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33934. if (defines === void 0) { defines = null; }
  33935. if (this._materialEffect === effect) {
  33936. if (!effect) {
  33937. this._materialDefines = null;
  33938. }
  33939. return;
  33940. }
  33941. this._materialDefines = defines;
  33942. this._materialEffect = effect;
  33943. };
  33944. return BaseSubMesh;
  33945. }());
  33946. BABYLON.BaseSubMesh = BaseSubMesh;
  33947. var SubMesh = /** @class */ (function (_super) {
  33948. __extends(SubMesh, _super);
  33949. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33950. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33951. var _this = _super.call(this) || this;
  33952. _this.materialIndex = materialIndex;
  33953. _this.verticesStart = verticesStart;
  33954. _this.verticesCount = verticesCount;
  33955. _this.indexStart = indexStart;
  33956. _this.indexCount = indexCount;
  33957. /** @hidden */
  33958. _this._renderId = 0;
  33959. _this._mesh = mesh;
  33960. _this._renderingMesh = renderingMesh || mesh;
  33961. mesh.subMeshes.push(_this);
  33962. _this._trianglePlanes = [];
  33963. _this._id = mesh.subMeshes.length - 1;
  33964. if (createBoundingBox) {
  33965. _this.refreshBoundingInfo();
  33966. mesh.computeWorldMatrix(true);
  33967. }
  33968. return _this;
  33969. }
  33970. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33971. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33972. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33973. };
  33974. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33975. get: function () {
  33976. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  33977. },
  33978. enumerable: true,
  33979. configurable: true
  33980. });
  33981. /**
  33982. * Returns the submesh BoudingInfo object.
  33983. */
  33984. SubMesh.prototype.getBoundingInfo = function () {
  33985. if (this.IsGlobal) {
  33986. return this._mesh.getBoundingInfo();
  33987. }
  33988. return this._boundingInfo;
  33989. };
  33990. /**
  33991. * Sets the submesh BoundingInfo.
  33992. * Return the SubMesh.
  33993. */
  33994. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33995. this._boundingInfo = boundingInfo;
  33996. return this;
  33997. };
  33998. /**
  33999. * Returns the mesh of the current submesh.
  34000. */
  34001. SubMesh.prototype.getMesh = function () {
  34002. return this._mesh;
  34003. };
  34004. /**
  34005. * Returns the rendering mesh of the submesh.
  34006. */
  34007. SubMesh.prototype.getRenderingMesh = function () {
  34008. return this._renderingMesh;
  34009. };
  34010. /**
  34011. * Returns the submesh material.
  34012. */
  34013. SubMesh.prototype.getMaterial = function () {
  34014. var rootMaterial = this._renderingMesh.material;
  34015. if (rootMaterial === null || rootMaterial === undefined) {
  34016. return this._mesh.getScene().defaultMaterial;
  34017. }
  34018. else if (rootMaterial.getSubMaterial) {
  34019. var multiMaterial = rootMaterial;
  34020. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34021. if (this._currentMaterial !== effectiveMaterial) {
  34022. this._currentMaterial = effectiveMaterial;
  34023. this._materialDefines = null;
  34024. }
  34025. return effectiveMaterial;
  34026. }
  34027. return rootMaterial;
  34028. };
  34029. // Methods
  34030. /**
  34031. * Sets a new updated BoundingInfo object to the submesh.
  34032. * Returns the SubMesh.
  34033. */
  34034. SubMesh.prototype.refreshBoundingInfo = function () {
  34035. this._lastColliderWorldVertices = null;
  34036. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34037. return this;
  34038. }
  34039. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34040. if (!data) {
  34041. this._boundingInfo = this._mesh.getBoundingInfo();
  34042. return this;
  34043. }
  34044. var indices = this._renderingMesh.getIndices();
  34045. var extend;
  34046. //is this the only submesh?
  34047. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34048. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34049. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34050. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34051. }
  34052. else {
  34053. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34054. }
  34055. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34056. return this;
  34057. };
  34058. /** @hidden */
  34059. SubMesh.prototype._checkCollision = function (collider) {
  34060. var boundingInfo = this.getBoundingInfo();
  34061. return boundingInfo._checkCollision(collider);
  34062. };
  34063. /**
  34064. * Updates the submesh BoundingInfo.
  34065. * Returns the Submesh.
  34066. */
  34067. SubMesh.prototype.updateBoundingInfo = function (world) {
  34068. var boundingInfo = this.getBoundingInfo();
  34069. if (!boundingInfo) {
  34070. this.refreshBoundingInfo();
  34071. boundingInfo = this.getBoundingInfo();
  34072. }
  34073. boundingInfo.update(world);
  34074. return this;
  34075. };
  34076. /**
  34077. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34078. * Boolean returned.
  34079. */
  34080. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34081. var boundingInfo = this.getBoundingInfo();
  34082. if (!boundingInfo) {
  34083. return false;
  34084. }
  34085. return boundingInfo.isInFrustum(frustumPlanes);
  34086. };
  34087. /**
  34088. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34089. * Boolean returned.
  34090. */
  34091. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34092. var boundingInfo = this.getBoundingInfo();
  34093. if (!boundingInfo) {
  34094. return false;
  34095. }
  34096. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34097. };
  34098. /**
  34099. * Renders the submesh.
  34100. * Returns it.
  34101. */
  34102. SubMesh.prototype.render = function (enableAlphaMode) {
  34103. this._renderingMesh.render(this, enableAlphaMode);
  34104. return this;
  34105. };
  34106. /**
  34107. * Returns a new Index Buffer.
  34108. * Type returned : WebGLBuffer.
  34109. */
  34110. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34111. if (!this._linesIndexBuffer) {
  34112. var linesIndices = [];
  34113. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34114. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34115. }
  34116. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34117. this.linesIndexCount = linesIndices.length;
  34118. }
  34119. return this._linesIndexBuffer;
  34120. };
  34121. /**
  34122. * True is the passed Ray intersects the submesh bounding box.
  34123. * Boolean returned.
  34124. */
  34125. SubMesh.prototype.canIntersects = function (ray) {
  34126. var boundingInfo = this.getBoundingInfo();
  34127. if (!boundingInfo) {
  34128. return false;
  34129. }
  34130. return ray.intersectsBox(boundingInfo.boundingBox);
  34131. };
  34132. /**
  34133. * Returns an object IntersectionInfo.
  34134. */
  34135. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34136. var intersectInfo = null;
  34137. var material = this.getMaterial();
  34138. if (!material) {
  34139. return null;
  34140. }
  34141. switch (material.fillMode) {
  34142. case BABYLON.Material.PointListDrawMode:
  34143. case BABYLON.Material.LineListDrawMode:
  34144. case BABYLON.Material.LineLoopDrawMode:
  34145. case BABYLON.Material.LineStripDrawMode:
  34146. case BABYLON.Material.TriangleFanDrawMode:
  34147. case BABYLON.Material.TriangleStripDrawMode:
  34148. return null;
  34149. }
  34150. // LineMesh first as it's also a Mesh...
  34151. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34152. var lineMesh = this._mesh;
  34153. // Line test
  34154. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34155. var p0 = positions[indices[index]];
  34156. var p1 = positions[indices[index + 1]];
  34157. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34158. if (length < 0) {
  34159. continue;
  34160. }
  34161. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34162. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34163. if (fastCheck) {
  34164. break;
  34165. }
  34166. }
  34167. }
  34168. }
  34169. else {
  34170. // Triangles test
  34171. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34172. var p0 = positions[indices[index]];
  34173. var p1 = positions[indices[index + 1]];
  34174. var p2 = positions[indices[index + 2]];
  34175. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34176. if (currentIntersectInfo) {
  34177. if (currentIntersectInfo.distance < 0) {
  34178. continue;
  34179. }
  34180. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34181. intersectInfo = currentIntersectInfo;
  34182. intersectInfo.faceId = index / 3;
  34183. if (fastCheck) {
  34184. break;
  34185. }
  34186. }
  34187. }
  34188. }
  34189. }
  34190. return intersectInfo;
  34191. };
  34192. /** @hidden */
  34193. SubMesh.prototype._rebuild = function () {
  34194. if (this._linesIndexBuffer) {
  34195. this._linesIndexBuffer = null;
  34196. }
  34197. };
  34198. // Clone
  34199. /**
  34200. * Creates a new Submesh from the passed Mesh.
  34201. */
  34202. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34203. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34204. if (!this.IsGlobal) {
  34205. var boundingInfo = this.getBoundingInfo();
  34206. if (!boundingInfo) {
  34207. return result;
  34208. }
  34209. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34210. }
  34211. return result;
  34212. };
  34213. // Dispose
  34214. /**
  34215. * Disposes the Submesh.
  34216. * Returns nothing.
  34217. */
  34218. SubMesh.prototype.dispose = function () {
  34219. if (this._linesIndexBuffer) {
  34220. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34221. this._linesIndexBuffer = null;
  34222. }
  34223. // Remove from mesh
  34224. var index = this._mesh.subMeshes.indexOf(this);
  34225. this._mesh.subMeshes.splice(index, 1);
  34226. };
  34227. // Statics
  34228. /**
  34229. * Creates a new Submesh from the passed parameters :
  34230. * - materialIndex (integer) : the index of the main mesh material.
  34231. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34232. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34233. * - mesh (Mesh) : the main mesh to create the submesh from.
  34234. * - renderingMesh (optional Mesh) : rendering mesh.
  34235. */
  34236. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34237. var minVertexIndex = Number.MAX_VALUE;
  34238. var maxVertexIndex = -Number.MAX_VALUE;
  34239. renderingMesh = (renderingMesh || mesh);
  34240. var indices = renderingMesh.getIndices();
  34241. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34242. var vertexIndex = indices[index];
  34243. if (vertexIndex < minVertexIndex)
  34244. minVertexIndex = vertexIndex;
  34245. if (vertexIndex > maxVertexIndex)
  34246. maxVertexIndex = vertexIndex;
  34247. }
  34248. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34249. };
  34250. return SubMesh;
  34251. }(BaseSubMesh));
  34252. BABYLON.SubMesh = SubMesh;
  34253. })(BABYLON || (BABYLON = {}));
  34254. //# sourceMappingURL=babylon.subMesh.js.map
  34255. var __assign = (this && this.__assign) || function () {
  34256. __assign = Object.assign || function(t) {
  34257. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34258. s = arguments[i];
  34259. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34260. t[p] = s[p];
  34261. }
  34262. return t;
  34263. };
  34264. return __assign.apply(this, arguments);
  34265. };
  34266. var BABYLON;
  34267. (function (BABYLON) {
  34268. /**
  34269. * Manages the defines for the Material
  34270. */
  34271. var MaterialDefines = /** @class */ (function () {
  34272. function MaterialDefines() {
  34273. this._isDirty = true;
  34274. /** @hidden */
  34275. this._areLightsDirty = true;
  34276. /** @hidden */
  34277. this._areAttributesDirty = true;
  34278. /** @hidden */
  34279. this._areTexturesDirty = true;
  34280. /** @hidden */
  34281. this._areFresnelDirty = true;
  34282. /** @hidden */
  34283. this._areMiscDirty = true;
  34284. /** @hidden */
  34285. this._areImageProcessingDirty = true;
  34286. /** @hidden */
  34287. this._normals = false;
  34288. /** @hidden */
  34289. this._uvs = false;
  34290. /** @hidden */
  34291. this._needNormals = false;
  34292. /** @hidden */
  34293. this._needUVs = false;
  34294. }
  34295. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34296. /**
  34297. * Specifies if the material needs to be re-calculated
  34298. */
  34299. get: function () {
  34300. return this._isDirty;
  34301. },
  34302. enumerable: true,
  34303. configurable: true
  34304. });
  34305. /**
  34306. * Marks the material to indicate that it has been re-calculated
  34307. */
  34308. MaterialDefines.prototype.markAsProcessed = function () {
  34309. this._isDirty = false;
  34310. this._areAttributesDirty = false;
  34311. this._areTexturesDirty = false;
  34312. this._areFresnelDirty = false;
  34313. this._areLightsDirty = false;
  34314. this._areMiscDirty = false;
  34315. this._areImageProcessingDirty = false;
  34316. };
  34317. /**
  34318. * Marks the material to indicate that it needs to be re-calculated
  34319. */
  34320. MaterialDefines.prototype.markAsUnprocessed = function () {
  34321. this._isDirty = true;
  34322. };
  34323. /**
  34324. * Marks the material to indicate all of its defines need to be re-calculated
  34325. */
  34326. MaterialDefines.prototype.markAllAsDirty = function () {
  34327. this._areTexturesDirty = true;
  34328. this._areAttributesDirty = true;
  34329. this._areLightsDirty = true;
  34330. this._areFresnelDirty = true;
  34331. this._areMiscDirty = true;
  34332. this._areImageProcessingDirty = true;
  34333. this._isDirty = true;
  34334. };
  34335. /**
  34336. * Marks the material to indicate that image processing needs to be re-calculated
  34337. */
  34338. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34339. this._areImageProcessingDirty = true;
  34340. this._isDirty = true;
  34341. };
  34342. /**
  34343. * Marks the material to indicate the lights need to be re-calculated
  34344. */
  34345. MaterialDefines.prototype.markAsLightDirty = function () {
  34346. this._areLightsDirty = true;
  34347. this._isDirty = true;
  34348. };
  34349. /**
  34350. * Marks the attribute state as changed
  34351. */
  34352. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34353. this._areAttributesDirty = true;
  34354. this._isDirty = true;
  34355. };
  34356. /**
  34357. * Marks the texture state as changed
  34358. */
  34359. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34360. this._areTexturesDirty = true;
  34361. this._isDirty = true;
  34362. };
  34363. /**
  34364. * Marks the fresnel state as changed
  34365. */
  34366. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34367. this._areFresnelDirty = true;
  34368. this._isDirty = true;
  34369. };
  34370. /**
  34371. * Marks the misc state as changed
  34372. */
  34373. MaterialDefines.prototype.markAsMiscDirty = function () {
  34374. this._areMiscDirty = true;
  34375. this._isDirty = true;
  34376. };
  34377. /**
  34378. * Rebuilds the material defines
  34379. */
  34380. MaterialDefines.prototype.rebuild = function () {
  34381. if (this._keys) {
  34382. delete this._keys;
  34383. }
  34384. this._keys = [];
  34385. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34386. var key = _a[_i];
  34387. if (key[0] === "_") {
  34388. continue;
  34389. }
  34390. this._keys.push(key);
  34391. }
  34392. };
  34393. /**
  34394. * Specifies if two material defines are equal
  34395. * @param other - A material define instance to compare to
  34396. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34397. */
  34398. MaterialDefines.prototype.isEqual = function (other) {
  34399. if (this._keys.length !== other._keys.length) {
  34400. return false;
  34401. }
  34402. for (var index = 0; index < this._keys.length; index++) {
  34403. var prop = this._keys[index];
  34404. if (this[prop] !== other[prop]) {
  34405. return false;
  34406. }
  34407. }
  34408. return true;
  34409. };
  34410. /**
  34411. * Clones this instance's defines to another instance
  34412. * @param other - material defines to clone values to
  34413. */
  34414. MaterialDefines.prototype.cloneTo = function (other) {
  34415. if (this._keys.length !== other._keys.length) {
  34416. other._keys = this._keys.slice(0);
  34417. }
  34418. for (var index = 0; index < this._keys.length; index++) {
  34419. var prop = this._keys[index];
  34420. other[prop] = this[prop];
  34421. }
  34422. };
  34423. /**
  34424. * Resets the material define values
  34425. */
  34426. MaterialDefines.prototype.reset = function () {
  34427. for (var index = 0; index < this._keys.length; index++) {
  34428. var prop = this._keys[index];
  34429. var type = typeof this[prop];
  34430. switch (type) {
  34431. case "number":
  34432. this[prop] = 0;
  34433. break;
  34434. case "string":
  34435. this[prop] = "";
  34436. break;
  34437. default:
  34438. this[prop] = false;
  34439. break;
  34440. }
  34441. }
  34442. };
  34443. /**
  34444. * Converts the material define values to a string
  34445. * @returns - String of material define information
  34446. */
  34447. MaterialDefines.prototype.toString = function () {
  34448. var result = "";
  34449. for (var index = 0; index < this._keys.length; index++) {
  34450. var prop = this._keys[index];
  34451. var value = this[prop];
  34452. var type = typeof value;
  34453. switch (type) {
  34454. case "number":
  34455. case "string":
  34456. result += "#define " + prop + " " + value + "\n";
  34457. break;
  34458. default:
  34459. if (value) {
  34460. result += "#define " + prop + "\n";
  34461. }
  34462. break;
  34463. }
  34464. }
  34465. return result;
  34466. };
  34467. return MaterialDefines;
  34468. }());
  34469. BABYLON.MaterialDefines = MaterialDefines;
  34470. /**
  34471. * Base class for the main features of a material in Babylon.js
  34472. */
  34473. var Material = /** @class */ (function () {
  34474. /**
  34475. * Creates a material instance
  34476. * @param name defines the name of the material
  34477. * @param scene defines the scene to reference
  34478. * @param doNotAdd specifies if the material should be added to the scene
  34479. */
  34480. function Material(name, scene, doNotAdd) {
  34481. /**
  34482. * Specifies if the ready state should be checked on each call
  34483. */
  34484. this.checkReadyOnEveryCall = false;
  34485. /**
  34486. * Specifies if the ready state should be checked once
  34487. */
  34488. this.checkReadyOnlyOnce = false;
  34489. /**
  34490. * The state of the material
  34491. */
  34492. this.state = "";
  34493. /**
  34494. * The alpha value of the material
  34495. */
  34496. this._alpha = 1.0;
  34497. /**
  34498. * Specifies if back face culling is enabled
  34499. */
  34500. this._backFaceCulling = true;
  34501. /**
  34502. * Gets a boolean indicating that current material needs to register RTT
  34503. */
  34504. this.hasRenderTargetTextures = false;
  34505. /**
  34506. * Specifies if the material should be serialized
  34507. */
  34508. this.doNotSerialize = false;
  34509. /**
  34510. * Specifies if the effect should be stored on sub meshes
  34511. */
  34512. this.storeEffectOnSubMeshes = false;
  34513. /**
  34514. * An event triggered when the material is disposed
  34515. */
  34516. this.onDisposeObservable = new BABYLON.Observable();
  34517. /**
  34518. * Stores the value of the alpha mode
  34519. */
  34520. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34521. /**
  34522. * Stores the state of the need depth pre-pass value
  34523. */
  34524. this._needDepthPrePass = false;
  34525. /**
  34526. * Specifies if depth writing should be disabled
  34527. */
  34528. this.disableDepthWrite = false;
  34529. /**
  34530. * Specifies if depth writing should be forced
  34531. */
  34532. this.forceDepthWrite = false;
  34533. /**
  34534. * Specifies if there should be a separate pass for culling
  34535. */
  34536. this.separateCullingPass = false;
  34537. /**
  34538. * Stores the state specifing if fog should be enabled
  34539. */
  34540. this._fogEnabled = true;
  34541. /**
  34542. * Stores the size of points
  34543. */
  34544. this.pointSize = 1.0;
  34545. /**
  34546. * Stores the z offset value
  34547. */
  34548. this.zOffset = 0;
  34549. /**
  34550. * @hidden
  34551. * Specifies if the material was previously ready
  34552. */
  34553. this._wasPreviouslyReady = false;
  34554. /**
  34555. * Stores the fill mode state
  34556. */
  34557. this._fillMode = Material.TriangleFillMode;
  34558. this.name = name;
  34559. this.id = name || BABYLON.Tools.RandomId();
  34560. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34561. this.uniqueId = this._scene.getUniqueId();
  34562. if (this._scene.useRightHandedSystem) {
  34563. this.sideOrientation = Material.ClockWiseSideOrientation;
  34564. }
  34565. else {
  34566. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34567. }
  34568. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34569. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34570. if (!doNotAdd) {
  34571. this._scene.materials.push(this);
  34572. }
  34573. }
  34574. Object.defineProperty(Material, "TriangleFillMode", {
  34575. /**
  34576. * Returns the triangle fill mode
  34577. */
  34578. get: function () {
  34579. return Material._TriangleFillMode;
  34580. },
  34581. enumerable: true,
  34582. configurable: true
  34583. });
  34584. Object.defineProperty(Material, "WireFrameFillMode", {
  34585. /**
  34586. * Returns the wireframe mode
  34587. */
  34588. get: function () {
  34589. return Material._WireFrameFillMode;
  34590. },
  34591. enumerable: true,
  34592. configurable: true
  34593. });
  34594. Object.defineProperty(Material, "PointFillMode", {
  34595. /**
  34596. * Returns the point fill mode
  34597. */
  34598. get: function () {
  34599. return Material._PointFillMode;
  34600. },
  34601. enumerable: true,
  34602. configurable: true
  34603. });
  34604. Object.defineProperty(Material, "PointListDrawMode", {
  34605. /**
  34606. * Returns the point list draw mode
  34607. */
  34608. get: function () {
  34609. return Material._PointListDrawMode;
  34610. },
  34611. enumerable: true,
  34612. configurable: true
  34613. });
  34614. Object.defineProperty(Material, "LineListDrawMode", {
  34615. /**
  34616. * Returns the line list draw mode
  34617. */
  34618. get: function () {
  34619. return Material._LineListDrawMode;
  34620. },
  34621. enumerable: true,
  34622. configurable: true
  34623. });
  34624. Object.defineProperty(Material, "LineLoopDrawMode", {
  34625. /**
  34626. * Returns the line loop draw mode
  34627. */
  34628. get: function () {
  34629. return Material._LineLoopDrawMode;
  34630. },
  34631. enumerable: true,
  34632. configurable: true
  34633. });
  34634. Object.defineProperty(Material, "LineStripDrawMode", {
  34635. /**
  34636. * Returns the line strip draw mode
  34637. */
  34638. get: function () {
  34639. return Material._LineStripDrawMode;
  34640. },
  34641. enumerable: true,
  34642. configurable: true
  34643. });
  34644. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34645. /**
  34646. * Returns the triangle strip draw mode
  34647. */
  34648. get: function () {
  34649. return Material._TriangleStripDrawMode;
  34650. },
  34651. enumerable: true,
  34652. configurable: true
  34653. });
  34654. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34655. /**
  34656. * Returns the triangle fan draw mode
  34657. */
  34658. get: function () {
  34659. return Material._TriangleFanDrawMode;
  34660. },
  34661. enumerable: true,
  34662. configurable: true
  34663. });
  34664. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34665. /**
  34666. * Returns the clock-wise side orientation
  34667. */
  34668. get: function () {
  34669. return Material._ClockWiseSideOrientation;
  34670. },
  34671. enumerable: true,
  34672. configurable: true
  34673. });
  34674. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34675. /**
  34676. * Returns the counter clock-wise side orientation
  34677. */
  34678. get: function () {
  34679. return Material._CounterClockWiseSideOrientation;
  34680. },
  34681. enumerable: true,
  34682. configurable: true
  34683. });
  34684. Object.defineProperty(Material, "TextureDirtyFlag", {
  34685. /**
  34686. * Returns the dirty texture flag value
  34687. */
  34688. get: function () {
  34689. return Material._TextureDirtyFlag;
  34690. },
  34691. enumerable: true,
  34692. configurable: true
  34693. });
  34694. Object.defineProperty(Material, "LightDirtyFlag", {
  34695. /**
  34696. * Returns the dirty light flag value
  34697. */
  34698. get: function () {
  34699. return Material._LightDirtyFlag;
  34700. },
  34701. enumerable: true,
  34702. configurable: true
  34703. });
  34704. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34705. /**
  34706. * Returns the dirty fresnel flag value
  34707. */
  34708. get: function () {
  34709. return Material._FresnelDirtyFlag;
  34710. },
  34711. enumerable: true,
  34712. configurable: true
  34713. });
  34714. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34715. /**
  34716. * Returns the dirty attributes flag value
  34717. */
  34718. get: function () {
  34719. return Material._AttributesDirtyFlag;
  34720. },
  34721. enumerable: true,
  34722. configurable: true
  34723. });
  34724. Object.defineProperty(Material, "MiscDirtyFlag", {
  34725. /**
  34726. * Returns the dirty misc flag value
  34727. */
  34728. get: function () {
  34729. return Material._MiscDirtyFlag;
  34730. },
  34731. enumerable: true,
  34732. configurable: true
  34733. });
  34734. Object.defineProperty(Material.prototype, "alpha", {
  34735. /**
  34736. * Gets the alpha value of the material
  34737. */
  34738. get: function () {
  34739. return this._alpha;
  34740. },
  34741. /**
  34742. * Sets the alpha value of the material
  34743. */
  34744. set: function (value) {
  34745. if (this._alpha === value) {
  34746. return;
  34747. }
  34748. this._alpha = value;
  34749. this.markAsDirty(Material.MiscDirtyFlag);
  34750. },
  34751. enumerable: true,
  34752. configurable: true
  34753. });
  34754. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34755. /**
  34756. * Gets the back-face culling state
  34757. */
  34758. get: function () {
  34759. return this._backFaceCulling;
  34760. },
  34761. /**
  34762. * Sets the back-face culling state
  34763. */
  34764. set: function (value) {
  34765. if (this._backFaceCulling === value) {
  34766. return;
  34767. }
  34768. this._backFaceCulling = value;
  34769. this.markAsDirty(Material.TextureDirtyFlag);
  34770. },
  34771. enumerable: true,
  34772. configurable: true
  34773. });
  34774. Object.defineProperty(Material.prototype, "onDispose", {
  34775. /**
  34776. * Called during a dispose event
  34777. */
  34778. set: function (callback) {
  34779. if (this._onDisposeObserver) {
  34780. this.onDisposeObservable.remove(this._onDisposeObserver);
  34781. }
  34782. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material.prototype, "onBindObservable", {
  34788. /**
  34789. * An event triggered when the material is bound
  34790. */
  34791. get: function () {
  34792. if (!this._onBindObservable) {
  34793. this._onBindObservable = new BABYLON.Observable();
  34794. }
  34795. return this._onBindObservable;
  34796. },
  34797. enumerable: true,
  34798. configurable: true
  34799. });
  34800. Object.defineProperty(Material.prototype, "onBind", {
  34801. /**
  34802. * Called during a bind event
  34803. */
  34804. set: function (callback) {
  34805. if (this._onBindObserver) {
  34806. this.onBindObservable.remove(this._onBindObserver);
  34807. }
  34808. this._onBindObserver = this.onBindObservable.add(callback);
  34809. },
  34810. enumerable: true,
  34811. configurable: true
  34812. });
  34813. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  34814. /**
  34815. * An event triggered when the material is unbound
  34816. */
  34817. get: function () {
  34818. if (!this._onUnBindObservable) {
  34819. this._onUnBindObservable = new BABYLON.Observable();
  34820. }
  34821. return this._onUnBindObservable;
  34822. },
  34823. enumerable: true,
  34824. configurable: true
  34825. });
  34826. Object.defineProperty(Material.prototype, "alphaMode", {
  34827. /**
  34828. * Gets the value of the alpha mode
  34829. */
  34830. get: function () {
  34831. return this._alphaMode;
  34832. },
  34833. /**
  34834. * Sets the value of the alpha mode.
  34835. *
  34836. * | Value | Type | Description |
  34837. * | --- | --- | --- |
  34838. * | 0 | ALPHA_DISABLE | |
  34839. * | 1 | ALPHA_ADD | |
  34840. * | 2 | ALPHA_COMBINE | |
  34841. * | 3 | ALPHA_SUBTRACT | |
  34842. * | 4 | ALPHA_MULTIPLY | |
  34843. * | 5 | ALPHA_MAXIMIZED | |
  34844. * | 6 | ALPHA_ONEONE | |
  34845. * | 7 | ALPHA_PREMULTIPLIED | |
  34846. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34847. * | 9 | ALPHA_INTERPOLATE | |
  34848. * | 10 | ALPHA_SCREENMODE | |
  34849. *
  34850. */
  34851. set: function (value) {
  34852. if (this._alphaMode === value) {
  34853. return;
  34854. }
  34855. this._alphaMode = value;
  34856. this.markAsDirty(Material.TextureDirtyFlag);
  34857. },
  34858. enumerable: true,
  34859. configurable: true
  34860. });
  34861. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34862. /**
  34863. * Gets the depth pre-pass value
  34864. */
  34865. get: function () {
  34866. return this._needDepthPrePass;
  34867. },
  34868. /**
  34869. * Sets the need depth pre-pass value
  34870. */
  34871. set: function (value) {
  34872. if (this._needDepthPrePass === value) {
  34873. return;
  34874. }
  34875. this._needDepthPrePass = value;
  34876. if (this._needDepthPrePass) {
  34877. this.checkReadyOnEveryCall = true;
  34878. }
  34879. },
  34880. enumerable: true,
  34881. configurable: true
  34882. });
  34883. Object.defineProperty(Material.prototype, "fogEnabled", {
  34884. /**
  34885. * Gets the value of the fog enabled state
  34886. */
  34887. get: function () {
  34888. return this._fogEnabled;
  34889. },
  34890. /**
  34891. * Sets the state for enabling fog
  34892. */
  34893. set: function (value) {
  34894. if (this._fogEnabled === value) {
  34895. return;
  34896. }
  34897. this._fogEnabled = value;
  34898. this.markAsDirty(Material.MiscDirtyFlag);
  34899. },
  34900. enumerable: true,
  34901. configurable: true
  34902. });
  34903. Object.defineProperty(Material.prototype, "wireframe", {
  34904. /**
  34905. * Gets a value specifying if wireframe mode is enabled
  34906. */
  34907. get: function () {
  34908. switch (this._fillMode) {
  34909. case Material.WireFrameFillMode:
  34910. case Material.LineListDrawMode:
  34911. case Material.LineLoopDrawMode:
  34912. case Material.LineStripDrawMode:
  34913. return true;
  34914. }
  34915. return this._scene.forceWireframe;
  34916. },
  34917. /**
  34918. * Sets the state of wireframe mode
  34919. */
  34920. set: function (value) {
  34921. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34922. },
  34923. enumerable: true,
  34924. configurable: true
  34925. });
  34926. Object.defineProperty(Material.prototype, "pointsCloud", {
  34927. /**
  34928. * Gets the value specifying if point clouds are enabled
  34929. */
  34930. get: function () {
  34931. switch (this._fillMode) {
  34932. case Material.PointFillMode:
  34933. case Material.PointListDrawMode:
  34934. return true;
  34935. }
  34936. return this._scene.forcePointsCloud;
  34937. },
  34938. /**
  34939. * Sets the state of point cloud mode
  34940. */
  34941. set: function (value) {
  34942. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34943. },
  34944. enumerable: true,
  34945. configurable: true
  34946. });
  34947. Object.defineProperty(Material.prototype, "fillMode", {
  34948. /**
  34949. * Gets the material fill mode
  34950. */
  34951. get: function () {
  34952. return this._fillMode;
  34953. },
  34954. /**
  34955. * Sets the material fill mode
  34956. */
  34957. set: function (value) {
  34958. if (this._fillMode === value) {
  34959. return;
  34960. }
  34961. this._fillMode = value;
  34962. this.markAsDirty(Material.MiscDirtyFlag);
  34963. },
  34964. enumerable: true,
  34965. configurable: true
  34966. });
  34967. /**
  34968. * Returns a string representation of the current material
  34969. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34970. * @returns a string with material information
  34971. */
  34972. Material.prototype.toString = function (fullDetails) {
  34973. var ret = "Name: " + this.name;
  34974. if (fullDetails) {
  34975. }
  34976. return ret;
  34977. };
  34978. /**
  34979. * Gets the class name of the material
  34980. * @returns a string with the class name of the material
  34981. */
  34982. Material.prototype.getClassName = function () {
  34983. return "Material";
  34984. };
  34985. Object.defineProperty(Material.prototype, "isFrozen", {
  34986. /**
  34987. * Specifies if updates for the material been locked
  34988. */
  34989. get: function () {
  34990. return this.checkReadyOnlyOnce;
  34991. },
  34992. enumerable: true,
  34993. configurable: true
  34994. });
  34995. /**
  34996. * Locks updates for the material
  34997. */
  34998. Material.prototype.freeze = function () {
  34999. this.checkReadyOnlyOnce = true;
  35000. };
  35001. /**
  35002. * Unlocks updates for the material
  35003. */
  35004. Material.prototype.unfreeze = function () {
  35005. this.checkReadyOnlyOnce = false;
  35006. };
  35007. /**
  35008. * Specifies if the material is ready to be used
  35009. * @param mesh defines the mesh to check
  35010. * @param useInstances specifies if instances should be used
  35011. * @returns a boolean indicating if the material is ready to be used
  35012. */
  35013. Material.prototype.isReady = function (mesh, useInstances) {
  35014. return true;
  35015. };
  35016. /**
  35017. * Specifies that the submesh is ready to be used
  35018. * @param mesh defines the mesh to check
  35019. * @param subMesh defines which submesh to check
  35020. * @param useInstances specifies that instances should be used
  35021. * @returns a boolean indicating that the submesh is ready or not
  35022. */
  35023. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35024. return false;
  35025. };
  35026. /**
  35027. * Returns the material effect
  35028. * @returns the effect associated with the material
  35029. */
  35030. Material.prototype.getEffect = function () {
  35031. return this._effect;
  35032. };
  35033. /**
  35034. * Returns the current scene
  35035. * @returns a Scene
  35036. */
  35037. Material.prototype.getScene = function () {
  35038. return this._scene;
  35039. };
  35040. /**
  35041. * Specifies if the material will require alpha blending
  35042. * @returns a boolean specifying if alpha blending is needed
  35043. */
  35044. Material.prototype.needAlphaBlending = function () {
  35045. return (this.alpha < 1.0);
  35046. };
  35047. /**
  35048. * Specifies if the mesh will require alpha blending
  35049. * @param mesh defines the mesh to check
  35050. * @returns a boolean specifying if alpha blending is needed for the mesh
  35051. */
  35052. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35053. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35054. };
  35055. /**
  35056. * Specifies if this material should be rendered in alpha test mode
  35057. * @returns a boolean specifying if an alpha test is needed.
  35058. */
  35059. Material.prototype.needAlphaTesting = function () {
  35060. return false;
  35061. };
  35062. /**
  35063. * Gets the texture used for the alpha test
  35064. * @returns the texture to use for alpha testing
  35065. */
  35066. Material.prototype.getAlphaTestTexture = function () {
  35067. return null;
  35068. };
  35069. /**
  35070. * Marks the material to indicate that it needs to be re-calculated
  35071. */
  35072. Material.prototype.markDirty = function () {
  35073. this._wasPreviouslyReady = false;
  35074. };
  35075. /** @hidden */
  35076. Material.prototype._preBind = function (effect, overrideOrientation) {
  35077. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35078. var engine = this._scene.getEngine();
  35079. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35080. var reverse = orientation === Material.ClockWiseSideOrientation;
  35081. engine.enableEffect(effect ? effect : this._effect);
  35082. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35083. return reverse;
  35084. };
  35085. /**
  35086. * Binds the material to the mesh
  35087. * @param world defines the world transformation matrix
  35088. * @param mesh defines the mesh to bind the material to
  35089. */
  35090. Material.prototype.bind = function (world, mesh) {
  35091. };
  35092. /**
  35093. * Binds the submesh to the material
  35094. * @param world defines the world transformation matrix
  35095. * @param mesh defines the mesh containing the submesh
  35096. * @param subMesh defines the submesh to bind the material to
  35097. */
  35098. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35099. };
  35100. /**
  35101. * Binds the world matrix to the material
  35102. * @param world defines the world transformation matrix
  35103. */
  35104. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35105. };
  35106. /**
  35107. * Binds the scene's uniform buffer to the effect.
  35108. * @param effect defines the effect to bind to the scene uniform buffer
  35109. * @param sceneUbo defines the uniform buffer storing scene data
  35110. */
  35111. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35112. sceneUbo.bindToEffect(effect, "Scene");
  35113. };
  35114. /**
  35115. * Binds the view matrix to the effect
  35116. * @param effect defines the effect to bind the view matrix to
  35117. */
  35118. Material.prototype.bindView = function (effect) {
  35119. if (!this._useUBO) {
  35120. effect.setMatrix("view", this.getScene().getViewMatrix());
  35121. }
  35122. else {
  35123. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35124. }
  35125. };
  35126. /**
  35127. * Binds the view projection matrix to the effect
  35128. * @param effect defines the effect to bind the view projection matrix to
  35129. */
  35130. Material.prototype.bindViewProjection = function (effect) {
  35131. if (!this._useUBO) {
  35132. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35133. }
  35134. else {
  35135. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35136. }
  35137. };
  35138. /**
  35139. * Specifies if material alpha testing should be turned on for the mesh
  35140. * @param mesh defines the mesh to check
  35141. */
  35142. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35143. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35144. };
  35145. /**
  35146. * Processes to execute after binding the material to a mesh
  35147. * @param mesh defines the rendered mesh
  35148. */
  35149. Material.prototype._afterBind = function (mesh) {
  35150. this._scene._cachedMaterial = this;
  35151. if (mesh) {
  35152. this._scene._cachedVisibility = mesh.visibility;
  35153. }
  35154. else {
  35155. this._scene._cachedVisibility = 1;
  35156. }
  35157. if (this._onBindObservable && mesh) {
  35158. this._onBindObservable.notifyObservers(mesh);
  35159. }
  35160. if (this.disableDepthWrite) {
  35161. var engine = this._scene.getEngine();
  35162. this._cachedDepthWriteState = engine.getDepthWrite();
  35163. engine.setDepthWrite(false);
  35164. }
  35165. };
  35166. /**
  35167. * Unbinds the material from the mesh
  35168. */
  35169. Material.prototype.unbind = function () {
  35170. if (this._onUnBindObservable) {
  35171. this._onUnBindObservable.notifyObservers(this);
  35172. }
  35173. if (this.disableDepthWrite) {
  35174. var engine = this._scene.getEngine();
  35175. engine.setDepthWrite(this._cachedDepthWriteState);
  35176. }
  35177. };
  35178. /**
  35179. * Gets the active textures from the material
  35180. * @returns an array of textures
  35181. */
  35182. Material.prototype.getActiveTextures = function () {
  35183. return [];
  35184. };
  35185. /**
  35186. * Specifies if the material uses a texture
  35187. * @param texture defines the texture to check against the material
  35188. * @returns a boolean specifying if the material uses the texture
  35189. */
  35190. Material.prototype.hasTexture = function (texture) {
  35191. return false;
  35192. };
  35193. /**
  35194. * Makes a duplicate of the material, and gives it a new name
  35195. * @param name defines the new name for the duplicated material
  35196. * @returns the cloned material
  35197. */
  35198. Material.prototype.clone = function (name) {
  35199. return null;
  35200. };
  35201. /**
  35202. * Gets the meshes bound to the material
  35203. * @returns an array of meshes bound to the material
  35204. */
  35205. Material.prototype.getBindedMeshes = function () {
  35206. var result = new Array();
  35207. for (var index = 0; index < this._scene.meshes.length; index++) {
  35208. var mesh = this._scene.meshes[index];
  35209. if (mesh.material === this) {
  35210. result.push(mesh);
  35211. }
  35212. }
  35213. return result;
  35214. };
  35215. /**
  35216. * Force shader compilation
  35217. * @param mesh defines the mesh associated with this material
  35218. * @param onCompiled defines a function to execute once the material is compiled
  35219. * @param options defines the options to configure the compilation
  35220. */
  35221. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35222. var _this = this;
  35223. var localOptions = __assign({ clipPlane: false }, options);
  35224. var subMesh = new BABYLON.BaseSubMesh();
  35225. var scene = this.getScene();
  35226. var checkReady = function () {
  35227. if (!_this._scene || !_this._scene.getEngine()) {
  35228. return;
  35229. }
  35230. if (subMesh._materialDefines) {
  35231. subMesh._materialDefines._renderId = -1;
  35232. }
  35233. var clipPlaneState = scene.clipPlane;
  35234. if (localOptions.clipPlane) {
  35235. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35236. }
  35237. if (_this.storeEffectOnSubMeshes) {
  35238. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35239. if (onCompiled) {
  35240. onCompiled(_this);
  35241. }
  35242. }
  35243. else {
  35244. setTimeout(checkReady, 16);
  35245. }
  35246. }
  35247. else {
  35248. if (_this.isReady(mesh)) {
  35249. if (onCompiled) {
  35250. onCompiled(_this);
  35251. }
  35252. }
  35253. else {
  35254. setTimeout(checkReady, 16);
  35255. }
  35256. }
  35257. if (localOptions.clipPlane) {
  35258. scene.clipPlane = clipPlaneState;
  35259. }
  35260. };
  35261. checkReady();
  35262. };
  35263. /**
  35264. * Force shader compilation
  35265. * @param mesh defines the mesh that will use this material
  35266. * @param options defines additional options for compiling the shaders
  35267. * @returns a promise that resolves when the compilation completes
  35268. */
  35269. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35270. var _this = this;
  35271. return new Promise(function (resolve) {
  35272. _this.forceCompilation(mesh, function () {
  35273. resolve();
  35274. }, options);
  35275. });
  35276. };
  35277. /**
  35278. * Marks a define in the material to indicate that it needs to be re-computed
  35279. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35280. */
  35281. Material.prototype.markAsDirty = function (flag) {
  35282. if (flag & Material.TextureDirtyFlag) {
  35283. this._markAllSubMeshesAsTexturesDirty();
  35284. }
  35285. if (flag & Material.LightDirtyFlag) {
  35286. this._markAllSubMeshesAsLightsDirty();
  35287. }
  35288. if (flag & Material.FresnelDirtyFlag) {
  35289. this._markAllSubMeshesAsFresnelDirty();
  35290. }
  35291. if (flag & Material.AttributesDirtyFlag) {
  35292. this._markAllSubMeshesAsAttributesDirty();
  35293. }
  35294. if (flag & Material.MiscDirtyFlag) {
  35295. this._markAllSubMeshesAsMiscDirty();
  35296. }
  35297. this.getScene().resetCachedMaterial();
  35298. };
  35299. /**
  35300. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35301. * @param func defines a function which checks material defines against the submeshes
  35302. */
  35303. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35304. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35305. var mesh = _a[_i];
  35306. if (!mesh.subMeshes) {
  35307. continue;
  35308. }
  35309. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35310. var subMesh = _c[_b];
  35311. if (subMesh.getMaterial() !== this) {
  35312. continue;
  35313. }
  35314. if (!subMesh._materialDefines) {
  35315. continue;
  35316. }
  35317. func(subMesh._materialDefines);
  35318. }
  35319. }
  35320. };
  35321. /**
  35322. * Indicates that image processing needs to be re-calculated for all submeshes
  35323. */
  35324. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35325. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35326. };
  35327. /**
  35328. * Indicates that textures need to be re-calculated for all submeshes
  35329. */
  35330. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35331. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35332. };
  35333. /**
  35334. * Indicates that fresnel needs to be re-calculated for all submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35338. };
  35339. /**
  35340. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35341. */
  35342. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35343. this._markAllSubMeshesAsDirty(function (defines) {
  35344. defines.markAsFresnelDirty();
  35345. defines.markAsMiscDirty();
  35346. });
  35347. };
  35348. /**
  35349. * Indicates that lights need to be re-calculated for all submeshes
  35350. */
  35351. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35352. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35353. };
  35354. /**
  35355. * Indicates that attributes need to be re-calculated for all submeshes
  35356. */
  35357. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35358. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35359. };
  35360. /**
  35361. * Indicates that misc needs to be re-calculated for all submeshes
  35362. */
  35363. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35365. };
  35366. /**
  35367. * Indicates that textures and misc need to be re-calculated for all submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35370. this._markAllSubMeshesAsDirty(function (defines) {
  35371. defines.markAsTexturesDirty();
  35372. defines.markAsMiscDirty();
  35373. });
  35374. };
  35375. /**
  35376. * Disposes the material
  35377. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35378. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35379. */
  35380. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35381. // Animations
  35382. this.getScene().stopAnimation(this);
  35383. this.getScene().freeProcessedMaterials();
  35384. // Remove from scene
  35385. var index = this._scene.materials.indexOf(this);
  35386. if (index >= 0) {
  35387. this._scene.materials.splice(index, 1);
  35388. }
  35389. // Remove from meshes
  35390. for (index = 0; index < this._scene.meshes.length; index++) {
  35391. var mesh = this._scene.meshes[index];
  35392. if (mesh.material === this) {
  35393. mesh.material = null;
  35394. if (mesh.geometry) {
  35395. var geometry = (mesh.geometry);
  35396. if (this.storeEffectOnSubMeshes) {
  35397. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35398. var subMesh = _a[_i];
  35399. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35400. if (forceDisposeEffect && subMesh._materialEffect) {
  35401. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35402. }
  35403. }
  35404. }
  35405. else {
  35406. geometry._releaseVertexArrayObject(this._effect);
  35407. }
  35408. }
  35409. }
  35410. }
  35411. this._uniformBuffer.dispose();
  35412. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35413. if (forceDisposeEffect && this._effect) {
  35414. if (!this.storeEffectOnSubMeshes) {
  35415. this._scene.getEngine()._releaseEffect(this._effect);
  35416. }
  35417. this._effect = null;
  35418. }
  35419. // Callback
  35420. this.onDisposeObservable.notifyObservers(this);
  35421. this.onDisposeObservable.clear();
  35422. if (this._onBindObservable) {
  35423. this._onBindObservable.clear();
  35424. }
  35425. if (this._onUnBindObservable) {
  35426. this._onUnBindObservable.clear();
  35427. }
  35428. };
  35429. /**
  35430. * Serializes this material
  35431. * @returns the serialized material object
  35432. */
  35433. Material.prototype.serialize = function () {
  35434. return BABYLON.SerializationHelper.Serialize(this);
  35435. };
  35436. /**
  35437. * Creates a MultiMaterial from parsed MultiMaterial data.
  35438. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35439. * @param scene defines the hosting scene
  35440. * @returns a new MultiMaterial
  35441. */
  35442. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35443. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35444. multiMaterial.id = parsedMultiMaterial.id;
  35445. if (BABYLON.Tags) {
  35446. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35447. }
  35448. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35449. var subMatId = parsedMultiMaterial.materials[matIndex];
  35450. if (subMatId) {
  35451. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35452. }
  35453. else {
  35454. multiMaterial.subMaterials.push(null);
  35455. }
  35456. }
  35457. return multiMaterial;
  35458. };
  35459. /**
  35460. * Creates a material from parsed material data
  35461. * @param parsedMaterial defines parsed material data
  35462. * @param scene defines the hosting scene
  35463. * @param rootUrl defines the root URL to use to load textures
  35464. * @returns a new material
  35465. */
  35466. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35467. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35468. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35469. }
  35470. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35471. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35472. if (!BABYLON.LegacyPBRMaterial) {
  35473. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35474. return;
  35475. }
  35476. }
  35477. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35478. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35479. };
  35480. // Triangle views
  35481. Material._TriangleFillMode = 0;
  35482. Material._WireFrameFillMode = 1;
  35483. Material._PointFillMode = 2;
  35484. // Draw modes
  35485. Material._PointListDrawMode = 3;
  35486. Material._LineListDrawMode = 4;
  35487. Material._LineLoopDrawMode = 5;
  35488. Material._LineStripDrawMode = 6;
  35489. Material._TriangleStripDrawMode = 7;
  35490. Material._TriangleFanDrawMode = 8;
  35491. /**
  35492. * Stores the clock-wise side orientation
  35493. */
  35494. Material._ClockWiseSideOrientation = 0;
  35495. /**
  35496. * Stores the counter clock-wise side orientation
  35497. */
  35498. Material._CounterClockWiseSideOrientation = 1;
  35499. /**
  35500. * The dirty texture flag value
  35501. */
  35502. Material._TextureDirtyFlag = 1;
  35503. /**
  35504. * The dirty light flag value
  35505. */
  35506. Material._LightDirtyFlag = 2;
  35507. /**
  35508. * The dirty fresnel flag value
  35509. */
  35510. Material._FresnelDirtyFlag = 4;
  35511. /**
  35512. * The dirty attribute flag value
  35513. */
  35514. Material._AttributesDirtyFlag = 8;
  35515. /**
  35516. * The dirty misc flag value
  35517. */
  35518. Material._MiscDirtyFlag = 16;
  35519. __decorate([
  35520. BABYLON.serialize()
  35521. ], Material.prototype, "id", void 0);
  35522. __decorate([
  35523. BABYLON.serialize()
  35524. ], Material.prototype, "uniqueId", void 0);
  35525. __decorate([
  35526. BABYLON.serialize()
  35527. ], Material.prototype, "name", void 0);
  35528. __decorate([
  35529. BABYLON.serialize()
  35530. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35531. __decorate([
  35532. BABYLON.serialize()
  35533. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35534. __decorate([
  35535. BABYLON.serialize()
  35536. ], Material.prototype, "state", void 0);
  35537. __decorate([
  35538. BABYLON.serialize("alpha")
  35539. ], Material.prototype, "_alpha", void 0);
  35540. __decorate([
  35541. BABYLON.serialize("backFaceCulling")
  35542. ], Material.prototype, "_backFaceCulling", void 0);
  35543. __decorate([
  35544. BABYLON.serialize()
  35545. ], Material.prototype, "sideOrientation", void 0);
  35546. __decorate([
  35547. BABYLON.serialize("alphaMode")
  35548. ], Material.prototype, "_alphaMode", void 0);
  35549. __decorate([
  35550. BABYLON.serialize()
  35551. ], Material.prototype, "_needDepthPrePass", void 0);
  35552. __decorate([
  35553. BABYLON.serialize()
  35554. ], Material.prototype, "disableDepthWrite", void 0);
  35555. __decorate([
  35556. BABYLON.serialize()
  35557. ], Material.prototype, "forceDepthWrite", void 0);
  35558. __decorate([
  35559. BABYLON.serialize()
  35560. ], Material.prototype, "separateCullingPass", void 0);
  35561. __decorate([
  35562. BABYLON.serialize("fogEnabled")
  35563. ], Material.prototype, "_fogEnabled", void 0);
  35564. __decorate([
  35565. BABYLON.serialize()
  35566. ], Material.prototype, "pointSize", void 0);
  35567. __decorate([
  35568. BABYLON.serialize()
  35569. ], Material.prototype, "zOffset", void 0);
  35570. __decorate([
  35571. BABYLON.serialize()
  35572. ], Material.prototype, "wireframe", null);
  35573. __decorate([
  35574. BABYLON.serialize()
  35575. ], Material.prototype, "pointsCloud", null);
  35576. __decorate([
  35577. BABYLON.serialize()
  35578. ], Material.prototype, "fillMode", null);
  35579. return Material;
  35580. }());
  35581. BABYLON.Material = Material;
  35582. })(BABYLON || (BABYLON = {}));
  35583. //# sourceMappingURL=babylon.material.js.map
  35584. var BABYLON;
  35585. (function (BABYLON) {
  35586. var UniformBuffer = /** @class */ (function () {
  35587. /**
  35588. * Uniform buffer objects.
  35589. *
  35590. * Handles blocks of uniform on the GPU.
  35591. *
  35592. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35593. *
  35594. * For more information, please refer to :
  35595. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35596. */
  35597. function UniformBuffer(engine, data, dynamic) {
  35598. this._engine = engine;
  35599. this._noUBO = !engine.supportsUniformBuffers;
  35600. this._dynamic = dynamic;
  35601. this._data = data || [];
  35602. this._uniformLocations = {};
  35603. this._uniformSizes = {};
  35604. this._uniformLocationPointer = 0;
  35605. this._needSync = false;
  35606. if (this._noUBO) {
  35607. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35608. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35609. this.updateFloat = this._updateFloatForEffect;
  35610. this.updateFloat2 = this._updateFloat2ForEffect;
  35611. this.updateFloat3 = this._updateFloat3ForEffect;
  35612. this.updateFloat4 = this._updateFloat4ForEffect;
  35613. this.updateMatrix = this._updateMatrixForEffect;
  35614. this.updateVector3 = this._updateVector3ForEffect;
  35615. this.updateVector4 = this._updateVector4ForEffect;
  35616. this.updateColor3 = this._updateColor3ForEffect;
  35617. this.updateColor4 = this._updateColor4ForEffect;
  35618. }
  35619. else {
  35620. this._engine._uniformBuffers.push(this);
  35621. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35622. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35623. this.updateFloat = this._updateFloatForUniform;
  35624. this.updateFloat2 = this._updateFloat2ForUniform;
  35625. this.updateFloat3 = this._updateFloat3ForUniform;
  35626. this.updateFloat4 = this._updateFloat4ForUniform;
  35627. this.updateMatrix = this._updateMatrixForUniform;
  35628. this.updateVector3 = this._updateVector3ForUniform;
  35629. this.updateVector4 = this._updateVector4ForUniform;
  35630. this.updateColor3 = this._updateColor3ForUniform;
  35631. this.updateColor4 = this._updateColor4ForUniform;
  35632. }
  35633. }
  35634. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35635. // Properties
  35636. /**
  35637. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35638. * or just falling back on setUniformXXX calls.
  35639. */
  35640. get: function () {
  35641. return !this._noUBO;
  35642. },
  35643. enumerable: true,
  35644. configurable: true
  35645. });
  35646. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35647. /**
  35648. * Indicates if the WebGL underlying uniform buffer is in sync
  35649. * with the javascript cache data.
  35650. */
  35651. get: function () {
  35652. return !this._needSync;
  35653. },
  35654. enumerable: true,
  35655. configurable: true
  35656. });
  35657. /**
  35658. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35659. * Also, a dynamic UniformBuffer will disable cache verification and always
  35660. * update the underlying WebGL uniform buffer to the GPU.
  35661. */
  35662. UniformBuffer.prototype.isDynamic = function () {
  35663. return this._dynamic !== undefined;
  35664. };
  35665. /**
  35666. * The data cache on JS side.
  35667. */
  35668. UniformBuffer.prototype.getData = function () {
  35669. return this._bufferData;
  35670. };
  35671. /**
  35672. * The underlying WebGL Uniform buffer.
  35673. */
  35674. UniformBuffer.prototype.getBuffer = function () {
  35675. return this._buffer;
  35676. };
  35677. /**
  35678. * std140 layout specifies how to align data within an UBO structure.
  35679. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35680. * for specs.
  35681. */
  35682. UniformBuffer.prototype._fillAlignment = function (size) {
  35683. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35684. // and 4x4 matrices
  35685. // TODO : change if other types are used
  35686. var alignment;
  35687. if (size <= 2) {
  35688. alignment = size;
  35689. }
  35690. else {
  35691. alignment = 4;
  35692. }
  35693. if ((this._uniformLocationPointer % alignment) !== 0) {
  35694. var oldPointer = this._uniformLocationPointer;
  35695. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35696. var diff = this._uniformLocationPointer - oldPointer;
  35697. for (var i = 0; i < diff; i++) {
  35698. this._data.push(0);
  35699. }
  35700. }
  35701. };
  35702. /**
  35703. * Adds an uniform in the buffer.
  35704. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35705. * for the layout to be correct !
  35706. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35707. * @param {number|number[]} size Data size, or data directly.
  35708. */
  35709. UniformBuffer.prototype.addUniform = function (name, size) {
  35710. if (this._noUBO) {
  35711. return;
  35712. }
  35713. if (this._uniformLocations[name] !== undefined) {
  35714. // Already existing uniform
  35715. return;
  35716. }
  35717. // This function must be called in the order of the shader layout !
  35718. // size can be the size of the uniform, or data directly
  35719. var data;
  35720. if (size instanceof Array) {
  35721. data = size;
  35722. size = data.length;
  35723. }
  35724. else {
  35725. size = size;
  35726. data = [];
  35727. // Fill with zeros
  35728. for (var i = 0; i < size; i++) {
  35729. data.push(0);
  35730. }
  35731. }
  35732. this._fillAlignment(size);
  35733. this._uniformSizes[name] = size;
  35734. this._uniformLocations[name] = this._uniformLocationPointer;
  35735. this._uniformLocationPointer += size;
  35736. for (var i = 0; i < size; i++) {
  35737. this._data.push(data[i]);
  35738. }
  35739. this._needSync = true;
  35740. };
  35741. /**
  35742. * Wrapper for addUniform.
  35743. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35744. * @param {Matrix} mat A 4x4 matrix.
  35745. */
  35746. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35747. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35748. };
  35749. /**
  35750. * Wrapper for addUniform.
  35751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35752. * @param {number} x
  35753. * @param {number} y
  35754. */
  35755. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35756. var temp = [x, y];
  35757. this.addUniform(name, temp);
  35758. };
  35759. /**
  35760. * Wrapper for addUniform.
  35761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35762. * @param {number} x
  35763. * @param {number} y
  35764. * @param {number} z
  35765. */
  35766. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35767. var temp = [x, y, z];
  35768. this.addUniform(name, temp);
  35769. };
  35770. /**
  35771. * Wrapper for addUniform.
  35772. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35773. * @param {Color3} color
  35774. */
  35775. UniformBuffer.prototype.addColor3 = function (name, color) {
  35776. var temp = new Array();
  35777. color.toArray(temp);
  35778. this.addUniform(name, temp);
  35779. };
  35780. /**
  35781. * Wrapper for addUniform.
  35782. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35783. * @param {Color3} color
  35784. * @param {number} alpha
  35785. */
  35786. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35787. var temp = new Array();
  35788. color.toArray(temp);
  35789. temp.push(alpha);
  35790. this.addUniform(name, temp);
  35791. };
  35792. /**
  35793. * Wrapper for addUniform.
  35794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35795. * @param {Vector3} vector
  35796. */
  35797. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35798. var temp = new Array();
  35799. vector.toArray(temp);
  35800. this.addUniform(name, temp);
  35801. };
  35802. /**
  35803. * Wrapper for addUniform.
  35804. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35805. */
  35806. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35807. this.addUniform(name, 12);
  35808. };
  35809. /**
  35810. * Wrapper for addUniform.
  35811. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35812. */
  35813. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35814. this.addUniform(name, 8);
  35815. };
  35816. /**
  35817. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35818. */
  35819. UniformBuffer.prototype.create = function () {
  35820. if (this._noUBO) {
  35821. return;
  35822. }
  35823. if (this._buffer) {
  35824. return; // nothing to do
  35825. }
  35826. // See spec, alignment must be filled as a vec4
  35827. this._fillAlignment(4);
  35828. this._bufferData = new Float32Array(this._data);
  35829. this._rebuild();
  35830. this._needSync = true;
  35831. };
  35832. /** @hidden */
  35833. UniformBuffer.prototype._rebuild = function () {
  35834. if (this._noUBO) {
  35835. return;
  35836. }
  35837. if (this._dynamic) {
  35838. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35839. }
  35840. else {
  35841. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35842. }
  35843. };
  35844. /**
  35845. * Updates the WebGL Uniform Buffer on the GPU.
  35846. * If the `dynamic` flag is set to true, no cache comparison is done.
  35847. * Otherwise, the buffer will be updated only if the cache differs.
  35848. */
  35849. UniformBuffer.prototype.update = function () {
  35850. if (!this._buffer) {
  35851. this.create();
  35852. return;
  35853. }
  35854. if (!this._dynamic && !this._needSync) {
  35855. return;
  35856. }
  35857. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35858. this._needSync = false;
  35859. };
  35860. /**
  35861. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35862. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35863. * @param {number[]|Float32Array} data Flattened data
  35864. * @param {number} size Size of the data.
  35865. */
  35866. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35867. var location = this._uniformLocations[uniformName];
  35868. if (location === undefined) {
  35869. if (this._buffer) {
  35870. // Cannot add an uniform if the buffer is already created
  35871. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35872. return;
  35873. }
  35874. this.addUniform(uniformName, size);
  35875. location = this._uniformLocations[uniformName];
  35876. }
  35877. if (!this._buffer) {
  35878. this.create();
  35879. }
  35880. if (!this._dynamic) {
  35881. // Cache for static uniform buffers
  35882. var changed = false;
  35883. for (var i = 0; i < size; i++) {
  35884. if (this._bufferData[location + i] !== data[i]) {
  35885. changed = true;
  35886. this._bufferData[location + i] = data[i];
  35887. }
  35888. }
  35889. this._needSync = this._needSync || changed;
  35890. }
  35891. else {
  35892. // No cache for dynamic
  35893. for (var i = 0; i < size; i++) {
  35894. this._bufferData[location + i] = data[i];
  35895. }
  35896. }
  35897. };
  35898. // Update methods
  35899. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35900. // To match std140, matrix must be realigned
  35901. for (var i = 0; i < 3; i++) {
  35902. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35903. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35904. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35905. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35906. }
  35907. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35908. };
  35909. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35910. this._currentEffect.setMatrix3x3(name, matrix);
  35911. };
  35912. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35913. this._currentEffect.setMatrix2x2(name, matrix);
  35914. };
  35915. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35916. // To match std140, matrix must be realigned
  35917. for (var i = 0; i < 2; i++) {
  35918. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35919. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35920. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35921. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35922. }
  35923. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35924. };
  35925. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35926. this._currentEffect.setFloat(name, x);
  35927. };
  35928. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35929. UniformBuffer._tempBuffer[0] = x;
  35930. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35931. };
  35932. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35933. if (suffix === void 0) { suffix = ""; }
  35934. this._currentEffect.setFloat2(name + suffix, x, y);
  35935. };
  35936. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35937. if (suffix === void 0) { suffix = ""; }
  35938. UniformBuffer._tempBuffer[0] = x;
  35939. UniformBuffer._tempBuffer[1] = y;
  35940. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35941. };
  35942. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35943. if (suffix === void 0) { suffix = ""; }
  35944. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35945. };
  35946. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35947. if (suffix === void 0) { suffix = ""; }
  35948. UniformBuffer._tempBuffer[0] = x;
  35949. UniformBuffer._tempBuffer[1] = y;
  35950. UniformBuffer._tempBuffer[2] = z;
  35951. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35952. };
  35953. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35954. if (suffix === void 0) { suffix = ""; }
  35955. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35956. };
  35957. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35958. if (suffix === void 0) { suffix = ""; }
  35959. UniformBuffer._tempBuffer[0] = x;
  35960. UniformBuffer._tempBuffer[1] = y;
  35961. UniformBuffer._tempBuffer[2] = z;
  35962. UniformBuffer._tempBuffer[3] = w;
  35963. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35964. };
  35965. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35966. this._currentEffect.setMatrix(name, mat);
  35967. };
  35968. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35969. this.updateUniform(name, mat.toArray(), 16);
  35970. };
  35971. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35972. this._currentEffect.setVector3(name, vector);
  35973. };
  35974. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35975. vector.toArray(UniformBuffer._tempBuffer);
  35976. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35977. };
  35978. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35979. this._currentEffect.setVector4(name, vector);
  35980. };
  35981. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35982. vector.toArray(UniformBuffer._tempBuffer);
  35983. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35984. };
  35985. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35986. if (suffix === void 0) { suffix = ""; }
  35987. this._currentEffect.setColor3(name + suffix, color);
  35988. };
  35989. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35990. if (suffix === void 0) { suffix = ""; }
  35991. color.toArray(UniformBuffer._tempBuffer);
  35992. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35993. };
  35994. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35995. if (suffix === void 0) { suffix = ""; }
  35996. this._currentEffect.setColor4(name + suffix, color, alpha);
  35997. };
  35998. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35999. if (suffix === void 0) { suffix = ""; }
  36000. color.toArray(UniformBuffer._tempBuffer);
  36001. UniformBuffer._tempBuffer[3] = alpha;
  36002. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36003. };
  36004. /**
  36005. * Sets a sampler uniform on the effect.
  36006. * @param {string} name Name of the sampler.
  36007. * @param {Texture} texture
  36008. */
  36009. UniformBuffer.prototype.setTexture = function (name, texture) {
  36010. this._currentEffect.setTexture(name, texture);
  36011. };
  36012. /**
  36013. * Directly updates the value of the uniform in the cache AND on the GPU.
  36014. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36015. * @param {number[]|Float32Array} data Flattened data
  36016. */
  36017. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36018. this.updateUniform(uniformName, data, data.length);
  36019. this.update();
  36020. };
  36021. /**
  36022. * Binds this uniform buffer to an effect.
  36023. * @param {Effect} effect
  36024. * @param {string} name Name of the uniform block in the shader.
  36025. */
  36026. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36027. this._currentEffect = effect;
  36028. if (this._noUBO || !this._buffer) {
  36029. return;
  36030. }
  36031. effect.bindUniformBuffer(this._buffer, name);
  36032. };
  36033. /**
  36034. * Disposes the uniform buffer.
  36035. */
  36036. UniformBuffer.prototype.dispose = function () {
  36037. if (this._noUBO) {
  36038. return;
  36039. }
  36040. var index = this._engine._uniformBuffers.indexOf(this);
  36041. if (index !== -1) {
  36042. this._engine._uniformBuffers.splice(index, 1);
  36043. }
  36044. if (!this._buffer) {
  36045. return;
  36046. }
  36047. if (this._engine._releaseBuffer(this._buffer)) {
  36048. this._buffer = null;
  36049. }
  36050. };
  36051. // Pool for avoiding memory leaks
  36052. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36053. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36054. return UniformBuffer;
  36055. }());
  36056. BABYLON.UniformBuffer = UniformBuffer;
  36057. })(BABYLON || (BABYLON = {}));
  36058. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36059. var BABYLON;
  36060. (function (BABYLON) {
  36061. /**
  36062. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36063. */
  36064. var VertexData = /** @class */ (function () {
  36065. function VertexData() {
  36066. }
  36067. /**
  36068. * Uses the passed data array to set the set the values for the specified kind of data
  36069. * @param data a linear array of floating numbers
  36070. * @param kind the type of data that is being set, eg positions, colors etc
  36071. */
  36072. VertexData.prototype.set = function (data, kind) {
  36073. switch (kind) {
  36074. case BABYLON.VertexBuffer.PositionKind:
  36075. this.positions = data;
  36076. break;
  36077. case BABYLON.VertexBuffer.NormalKind:
  36078. this.normals = data;
  36079. break;
  36080. case BABYLON.VertexBuffer.TangentKind:
  36081. this.tangents = data;
  36082. break;
  36083. case BABYLON.VertexBuffer.UVKind:
  36084. this.uvs = data;
  36085. break;
  36086. case BABYLON.VertexBuffer.UV2Kind:
  36087. this.uvs2 = data;
  36088. break;
  36089. case BABYLON.VertexBuffer.UV3Kind:
  36090. this.uvs3 = data;
  36091. break;
  36092. case BABYLON.VertexBuffer.UV4Kind:
  36093. this.uvs4 = data;
  36094. break;
  36095. case BABYLON.VertexBuffer.UV5Kind:
  36096. this.uvs5 = data;
  36097. break;
  36098. case BABYLON.VertexBuffer.UV6Kind:
  36099. this.uvs6 = data;
  36100. break;
  36101. case BABYLON.VertexBuffer.ColorKind:
  36102. this.colors = data;
  36103. break;
  36104. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36105. this.matricesIndices = data;
  36106. break;
  36107. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36108. this.matricesWeights = data;
  36109. break;
  36110. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36111. this.matricesIndicesExtra = data;
  36112. break;
  36113. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36114. this.matricesWeightsExtra = data;
  36115. break;
  36116. }
  36117. };
  36118. /**
  36119. * Associates the vertexData to the passed Mesh.
  36120. * Sets it as updatable or not (default `false`)
  36121. * @param mesh the mesh the vertexData is applied to
  36122. * @param updatable when used and having the value true allows new data to update the vertexData
  36123. * @returns the VertexData
  36124. */
  36125. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36126. this._applyTo(mesh, updatable);
  36127. return this;
  36128. };
  36129. /**
  36130. * Associates the vertexData to the passed Geometry.
  36131. * Sets it as updatable or not (default `false`)
  36132. * @param geometry the geometry the vertexData is applied to
  36133. * @param updatable when used and having the value true allows new data to update the vertexData
  36134. * @returns VertexData
  36135. */
  36136. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36137. this._applyTo(geometry, updatable);
  36138. return this;
  36139. };
  36140. /**
  36141. * Updates the associated mesh
  36142. * @param mesh the mesh to be updated
  36143. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36144. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36145. * @returns VertexData
  36146. */
  36147. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36148. this._update(mesh);
  36149. return this;
  36150. };
  36151. /**
  36152. * Updates the associated geometry
  36153. * @param geometry the geometry to be updated
  36154. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36155. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36156. * @returns VertexData.
  36157. */
  36158. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36159. this._update(geometry);
  36160. return this;
  36161. };
  36162. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36163. if (updatable === void 0) { updatable = false; }
  36164. if (this.positions) {
  36165. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36166. }
  36167. if (this.normals) {
  36168. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36169. }
  36170. if (this.tangents) {
  36171. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36172. }
  36173. if (this.uvs) {
  36174. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36175. }
  36176. if (this.uvs2) {
  36177. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36178. }
  36179. if (this.uvs3) {
  36180. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36181. }
  36182. if (this.uvs4) {
  36183. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36184. }
  36185. if (this.uvs5) {
  36186. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36187. }
  36188. if (this.uvs6) {
  36189. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36190. }
  36191. if (this.colors) {
  36192. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36193. }
  36194. if (this.matricesIndices) {
  36195. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36196. }
  36197. if (this.matricesWeights) {
  36198. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36199. }
  36200. if (this.matricesIndicesExtra) {
  36201. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36202. }
  36203. if (this.matricesWeightsExtra) {
  36204. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36205. }
  36206. if (this.indices) {
  36207. meshOrGeometry.setIndices(this.indices, null, updatable);
  36208. }
  36209. else {
  36210. meshOrGeometry.setIndices([], null);
  36211. }
  36212. return this;
  36213. };
  36214. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36215. if (this.positions) {
  36216. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36217. }
  36218. if (this.normals) {
  36219. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36220. }
  36221. if (this.tangents) {
  36222. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36223. }
  36224. if (this.uvs) {
  36225. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36226. }
  36227. if (this.uvs2) {
  36228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36229. }
  36230. if (this.uvs3) {
  36231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36232. }
  36233. if (this.uvs4) {
  36234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36235. }
  36236. if (this.uvs5) {
  36237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36238. }
  36239. if (this.uvs6) {
  36240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36241. }
  36242. if (this.colors) {
  36243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36244. }
  36245. if (this.matricesIndices) {
  36246. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36247. }
  36248. if (this.matricesWeights) {
  36249. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36250. }
  36251. if (this.matricesIndicesExtra) {
  36252. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36253. }
  36254. if (this.matricesWeightsExtra) {
  36255. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36256. }
  36257. if (this.indices) {
  36258. meshOrGeometry.setIndices(this.indices, null);
  36259. }
  36260. return this;
  36261. };
  36262. /**
  36263. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36264. * @param matrix the transforming matrix
  36265. * @returns the VertexData
  36266. */
  36267. VertexData.prototype.transform = function (matrix) {
  36268. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36269. var transformed = BABYLON.Vector3.Zero();
  36270. var index;
  36271. if (this.positions) {
  36272. var position = BABYLON.Vector3.Zero();
  36273. for (index = 0; index < this.positions.length; index += 3) {
  36274. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36275. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36276. this.positions[index] = transformed.x;
  36277. this.positions[index + 1] = transformed.y;
  36278. this.positions[index + 2] = transformed.z;
  36279. }
  36280. }
  36281. if (this.normals) {
  36282. var normal = BABYLON.Vector3.Zero();
  36283. for (index = 0; index < this.normals.length; index += 3) {
  36284. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36285. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36286. this.normals[index] = transformed.x;
  36287. this.normals[index + 1] = transformed.y;
  36288. this.normals[index + 2] = transformed.z;
  36289. }
  36290. }
  36291. if (this.tangents) {
  36292. var tangent = BABYLON.Vector4.Zero();
  36293. var tangentTransformed = BABYLON.Vector4.Zero();
  36294. for (index = 0; index < this.tangents.length; index += 4) {
  36295. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36296. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36297. this.tangents[index] = tangentTransformed.x;
  36298. this.tangents[index + 1] = tangentTransformed.y;
  36299. this.tangents[index + 2] = tangentTransformed.z;
  36300. this.tangents[index + 3] = tangentTransformed.w;
  36301. }
  36302. }
  36303. if (flip && this.indices) {
  36304. for (index = 0; index < this.indices.length; index += 3) {
  36305. var tmp = this.indices[index + 1];
  36306. this.indices[index + 1] = this.indices[index + 2];
  36307. this.indices[index + 2] = tmp;
  36308. }
  36309. }
  36310. return this;
  36311. };
  36312. /**
  36313. * Merges the passed VertexData into the current one
  36314. * @param other the VertexData to be merged into the current one
  36315. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36316. * @returns the modified VertexData
  36317. */
  36318. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36319. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36320. this._validate();
  36321. other._validate();
  36322. if (!this.normals !== !other.normals ||
  36323. !this.tangents !== !other.tangents ||
  36324. !this.uvs !== !other.uvs ||
  36325. !this.uvs2 !== !other.uvs2 ||
  36326. !this.uvs3 !== !other.uvs3 ||
  36327. !this.uvs4 !== !other.uvs4 ||
  36328. !this.uvs5 !== !other.uvs5 ||
  36329. !this.uvs6 !== !other.uvs6 ||
  36330. !this.colors !== !other.colors ||
  36331. !this.matricesIndices !== !other.matricesIndices ||
  36332. !this.matricesWeights !== !other.matricesWeights ||
  36333. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36334. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36335. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36336. }
  36337. if (other.indices) {
  36338. if (!this.indices) {
  36339. this.indices = [];
  36340. }
  36341. var offset = this.positions ? this.positions.length / 3 : 0;
  36342. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36343. if (isSrcTypedArray) {
  36344. var len = this.indices.length + other.indices.length;
  36345. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36346. temp.set(this.indices);
  36347. var decal = this.indices.length;
  36348. for (var index = 0; index < other.indices.length; index++) {
  36349. temp[decal + index] = other.indices[index] + offset;
  36350. }
  36351. this.indices = temp;
  36352. }
  36353. else {
  36354. for (var index = 0; index < other.indices.length; index++) {
  36355. this.indices.push(other.indices[index] + offset);
  36356. }
  36357. }
  36358. }
  36359. this.positions = this._mergeElement(this.positions, other.positions);
  36360. this.normals = this._mergeElement(this.normals, other.normals);
  36361. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36362. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36363. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36364. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36365. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36366. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36367. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36368. this.colors = this._mergeElement(this.colors, other.colors);
  36369. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36370. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36371. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36372. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36373. return this;
  36374. };
  36375. VertexData.prototype._mergeElement = function (source, other) {
  36376. if (!source) {
  36377. return other;
  36378. }
  36379. if (!other) {
  36380. return source;
  36381. }
  36382. var len = other.length + source.length;
  36383. var isSrcTypedArray = source instanceof Float32Array;
  36384. var isOthTypedArray = other instanceof Float32Array;
  36385. // use non-loop method when the source is Float32Array
  36386. if (isSrcTypedArray) {
  36387. var ret32 = new Float32Array(len);
  36388. ret32.set(source);
  36389. ret32.set(other, source.length);
  36390. return ret32;
  36391. // source is number[], when other is also use concat
  36392. }
  36393. else if (!isOthTypedArray) {
  36394. return source.concat(other);
  36395. // source is a number[], but other is a Float32Array, loop required
  36396. }
  36397. else {
  36398. var ret = source.slice(0); // copy source to a separate array
  36399. for (var i = 0, len = other.length; i < len; i++) {
  36400. ret.push(other[i]);
  36401. }
  36402. return ret;
  36403. }
  36404. };
  36405. VertexData.prototype._validate = function () {
  36406. if (!this.positions) {
  36407. throw new Error("Positions are required");
  36408. }
  36409. var getElementCount = function (kind, values) {
  36410. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36411. if ((values.length % stride) !== 0) {
  36412. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36413. }
  36414. return values.length / stride;
  36415. };
  36416. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36417. var validateElementCount = function (kind, values) {
  36418. var elementCount = getElementCount(kind, values);
  36419. if (elementCount !== positionsElementCount) {
  36420. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36421. }
  36422. };
  36423. if (this.normals)
  36424. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36425. if (this.tangents)
  36426. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36427. if (this.uvs)
  36428. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36429. if (this.uvs2)
  36430. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36431. if (this.uvs3)
  36432. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36433. if (this.uvs4)
  36434. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36435. if (this.uvs5)
  36436. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36437. if (this.uvs6)
  36438. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36439. if (this.colors)
  36440. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36441. if (this.matricesIndices)
  36442. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36443. if (this.matricesWeights)
  36444. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36445. if (this.matricesIndicesExtra)
  36446. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36447. if (this.matricesWeightsExtra)
  36448. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36449. };
  36450. /**
  36451. * Serializes the VertexData
  36452. * @returns a serialized object
  36453. */
  36454. VertexData.prototype.serialize = function () {
  36455. var serializationObject = this.serialize();
  36456. if (this.positions) {
  36457. serializationObject.positions = this.positions;
  36458. }
  36459. if (this.normals) {
  36460. serializationObject.normals = this.normals;
  36461. }
  36462. if (this.tangents) {
  36463. serializationObject.tangents = this.tangents;
  36464. }
  36465. if (this.uvs) {
  36466. serializationObject.uvs = this.uvs;
  36467. }
  36468. if (this.uvs2) {
  36469. serializationObject.uvs2 = this.uvs2;
  36470. }
  36471. if (this.uvs3) {
  36472. serializationObject.uvs3 = this.uvs3;
  36473. }
  36474. if (this.uvs4) {
  36475. serializationObject.uvs4 = this.uvs4;
  36476. }
  36477. if (this.uvs5) {
  36478. serializationObject.uvs5 = this.uvs5;
  36479. }
  36480. if (this.uvs6) {
  36481. serializationObject.uvs6 = this.uvs6;
  36482. }
  36483. if (this.colors) {
  36484. serializationObject.colors = this.colors;
  36485. }
  36486. if (this.matricesIndices) {
  36487. serializationObject.matricesIndices = this.matricesIndices;
  36488. serializationObject.matricesIndices._isExpanded = true;
  36489. }
  36490. if (this.matricesWeights) {
  36491. serializationObject.matricesWeights = this.matricesWeights;
  36492. }
  36493. if (this.matricesIndicesExtra) {
  36494. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36495. serializationObject.matricesIndicesExtra._isExpanded = true;
  36496. }
  36497. if (this.matricesWeightsExtra) {
  36498. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36499. }
  36500. serializationObject.indices = this.indices;
  36501. return serializationObject;
  36502. };
  36503. // Statics
  36504. /**
  36505. * Extracts the vertexData from a mesh
  36506. * @param mesh the mesh from which to extract the VertexData
  36507. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36508. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36509. * @returns the object VertexData associated to the passed mesh
  36510. */
  36511. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36512. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36513. };
  36514. /**
  36515. * Extracts the vertexData from the geometry
  36516. * @param geometry the geometry from which to extract the VertexData
  36517. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36518. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36519. * @returns the object VertexData associated to the passed mesh
  36520. */
  36521. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36522. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36523. };
  36524. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36525. var result = new VertexData();
  36526. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36527. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36528. }
  36529. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36530. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36531. }
  36532. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36533. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36534. }
  36535. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36536. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36537. }
  36538. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36539. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36540. }
  36541. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36542. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36543. }
  36544. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36545. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36546. }
  36547. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36548. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36549. }
  36550. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36551. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36552. }
  36553. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36554. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36555. }
  36556. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36557. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36558. }
  36559. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36560. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36561. }
  36562. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36563. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36564. }
  36565. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36566. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36567. }
  36568. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36569. return result;
  36570. };
  36571. /**
  36572. * Creates the VertexData for a Ribbon
  36573. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36574. * * pathArray array of paths, each of which an array of successive Vector3
  36575. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36576. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36577. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  36578. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36579. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36580. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36581. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36582. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36583. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36584. * @returns the VertexData of the ribbon
  36585. */
  36586. VertexData.CreateRibbon = function (options) {
  36587. var pathArray = options.pathArray;
  36588. var closeArray = options.closeArray || false;
  36589. var closePath = options.closePath || false;
  36590. var invertUV = options.invertUV || false;
  36591. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36592. var offset = options.offset || defaultOffset;
  36593. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36594. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36595. var customUV = options.uvs;
  36596. var customColors = options.colors;
  36597. var positions = [];
  36598. var indices = [];
  36599. var normals = [];
  36600. var uvs = [];
  36601. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36602. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36603. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36604. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36605. var minlg; // minimal length among all paths from pathArray
  36606. var lg = []; // array of path lengths : nb of vertex per path
  36607. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36608. var p; // path iterator
  36609. var i; // point iterator
  36610. var j; // point iterator
  36611. // if single path in pathArray
  36612. if (pathArray.length < 2) {
  36613. var ar1 = [];
  36614. var ar2 = [];
  36615. for (i = 0; i < pathArray[0].length - offset; i++) {
  36616. ar1.push(pathArray[0][i]);
  36617. ar2.push(pathArray[0][i + offset]);
  36618. }
  36619. pathArray = [ar1, ar2];
  36620. }
  36621. // positions and horizontal distances (u)
  36622. var idc = 0;
  36623. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36624. var path;
  36625. var l;
  36626. minlg = pathArray[0].length;
  36627. var vectlg;
  36628. var dist;
  36629. for (p = 0; p < pathArray.length; p++) {
  36630. uTotalDistance[p] = 0;
  36631. us[p] = [0];
  36632. path = pathArray[p];
  36633. l = path.length;
  36634. minlg = (minlg < l) ? minlg : l;
  36635. j = 0;
  36636. while (j < l) {
  36637. positions.push(path[j].x, path[j].y, path[j].z);
  36638. if (j > 0) {
  36639. vectlg = path[j].subtract(path[j - 1]).length();
  36640. dist = vectlg + uTotalDistance[p];
  36641. us[p].push(dist);
  36642. uTotalDistance[p] = dist;
  36643. }
  36644. j++;
  36645. }
  36646. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36647. j--;
  36648. positions.push(path[0].x, path[0].y, path[0].z);
  36649. vectlg = path[j].subtract(path[0]).length();
  36650. dist = vectlg + uTotalDistance[p];
  36651. us[p].push(dist);
  36652. uTotalDistance[p] = dist;
  36653. }
  36654. lg[p] = l + closePathCorr;
  36655. idx[p] = idc;
  36656. idc += (l + closePathCorr);
  36657. }
  36658. // vertical distances (v)
  36659. var path1;
  36660. var path2;
  36661. var vertex1 = null;
  36662. var vertex2 = null;
  36663. for (i = 0; i < minlg + closePathCorr; i++) {
  36664. vTotalDistance[i] = 0;
  36665. vs[i] = [0];
  36666. for (p = 0; p < pathArray.length - 1; p++) {
  36667. path1 = pathArray[p];
  36668. path2 = pathArray[p + 1];
  36669. if (i === minlg) { // closePath
  36670. vertex1 = path1[0];
  36671. vertex2 = path2[0];
  36672. }
  36673. else {
  36674. vertex1 = path1[i];
  36675. vertex2 = path2[i];
  36676. }
  36677. vectlg = vertex2.subtract(vertex1).length();
  36678. dist = vectlg + vTotalDistance[i];
  36679. vs[i].push(dist);
  36680. vTotalDistance[i] = dist;
  36681. }
  36682. if (closeArray && vertex2 && vertex1) {
  36683. path1 = pathArray[p];
  36684. path2 = pathArray[0];
  36685. if (i === minlg) { // closePath
  36686. vertex2 = path2[0];
  36687. }
  36688. vectlg = vertex2.subtract(vertex1).length();
  36689. dist = vectlg + vTotalDistance[i];
  36690. vTotalDistance[i] = dist;
  36691. }
  36692. }
  36693. // uvs
  36694. var u;
  36695. var v;
  36696. if (customUV) {
  36697. for (p = 0; p < customUV.length; p++) {
  36698. uvs.push(customUV[p].x, customUV[p].y);
  36699. }
  36700. }
  36701. else {
  36702. for (p = 0; p < pathArray.length; p++) {
  36703. for (i = 0; i < minlg + closePathCorr; i++) {
  36704. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36705. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36706. if (invertUV) {
  36707. uvs.push(v, u);
  36708. }
  36709. else {
  36710. uvs.push(u, v);
  36711. }
  36712. }
  36713. }
  36714. }
  36715. // indices
  36716. p = 0; // path index
  36717. var pi = 0; // positions array index
  36718. var l1 = lg[p] - 1; // path1 length
  36719. var l2 = lg[p + 1] - 1; // path2 length
  36720. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36721. var shft = idx[1] - idx[0]; // shift
  36722. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36723. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36724. // 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
  36725. indices.push(pi, pi + shft, pi + 1);
  36726. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36727. pi += 1;
  36728. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36729. p++;
  36730. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36731. shft = idx[0] - idx[p];
  36732. l1 = lg[p] - 1;
  36733. l2 = lg[0] - 1;
  36734. }
  36735. else {
  36736. shft = idx[p + 1] - idx[p];
  36737. l1 = lg[p] - 1;
  36738. l2 = lg[p + 1] - 1;
  36739. }
  36740. pi = idx[p];
  36741. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36742. }
  36743. }
  36744. // normals
  36745. VertexData.ComputeNormals(positions, indices, normals);
  36746. if (closePath) { // update both the first and last vertex normals to their average value
  36747. var indexFirst = 0;
  36748. var indexLast = 0;
  36749. for (p = 0; p < pathArray.length; p++) {
  36750. indexFirst = idx[p] * 3;
  36751. if (p + 1 < pathArray.length) {
  36752. indexLast = (idx[p + 1] - 1) * 3;
  36753. }
  36754. else {
  36755. indexLast = normals.length - 3;
  36756. }
  36757. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36758. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36759. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36760. normals[indexLast] = normals[indexFirst];
  36761. normals[indexLast + 1] = normals[indexFirst + 1];
  36762. normals[indexLast + 2] = normals[indexFirst + 2];
  36763. }
  36764. }
  36765. // sides
  36766. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36767. // Colors
  36768. var colors = null;
  36769. if (customColors) {
  36770. colors = new Float32Array(customColors.length * 4);
  36771. for (var c = 0; c < customColors.length; c++) {
  36772. colors[c * 4] = customColors[c].r;
  36773. colors[c * 4 + 1] = customColors[c].g;
  36774. colors[c * 4 + 2] = customColors[c].b;
  36775. colors[c * 4 + 3] = customColors[c].a;
  36776. }
  36777. }
  36778. // Result
  36779. var vertexData = new VertexData();
  36780. var positions32 = new Float32Array(positions);
  36781. var normals32 = new Float32Array(normals);
  36782. var uvs32 = new Float32Array(uvs);
  36783. vertexData.indices = indices;
  36784. vertexData.positions = positions32;
  36785. vertexData.normals = normals32;
  36786. vertexData.uvs = uvs32;
  36787. if (colors) {
  36788. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36789. }
  36790. if (closePath) {
  36791. vertexData._idx = idx;
  36792. }
  36793. return vertexData;
  36794. };
  36795. /**
  36796. * Creates the VertexData for a box
  36797. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36798. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36799. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36800. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36801. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36802. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36803. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36804. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36805. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36806. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36807. * @returns the VertexData of the box
  36808. */
  36809. VertexData.CreateBox = function (options) {
  36810. var normalsSource = [
  36811. new BABYLON.Vector3(0, 0, 1),
  36812. new BABYLON.Vector3(0, 0, -1),
  36813. new BABYLON.Vector3(1, 0, 0),
  36814. new BABYLON.Vector3(-1, 0, 0),
  36815. new BABYLON.Vector3(0, 1, 0),
  36816. new BABYLON.Vector3(0, -1, 0)
  36817. ];
  36818. var indices = [];
  36819. var positions = [];
  36820. var normals = [];
  36821. var uvs = [];
  36822. var width = options.width || options.size || 1;
  36823. var height = options.height || options.size || 1;
  36824. var depth = options.depth || options.size || 1;
  36825. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36826. var faceUV = options.faceUV || new Array(6);
  36827. var faceColors = options.faceColors;
  36828. var colors = [];
  36829. // default face colors and UV if undefined
  36830. for (var f = 0; f < 6; f++) {
  36831. if (faceUV[f] === undefined) {
  36832. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36833. }
  36834. if (faceColors && faceColors[f] === undefined) {
  36835. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36836. }
  36837. }
  36838. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36839. // Create each face in turn.
  36840. for (var index = 0; index < normalsSource.length; index++) {
  36841. var normal = normalsSource[index];
  36842. // Get two vectors perpendicular to the face normal and to each other.
  36843. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36844. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36845. // Six indices (two triangles) per face.
  36846. var verticesLength = positions.length / 3;
  36847. indices.push(verticesLength);
  36848. indices.push(verticesLength + 1);
  36849. indices.push(verticesLength + 2);
  36850. indices.push(verticesLength);
  36851. indices.push(verticesLength + 2);
  36852. indices.push(verticesLength + 3);
  36853. // Four vertices per face.
  36854. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36855. positions.push(vertex.x, vertex.y, vertex.z);
  36856. normals.push(normal.x, normal.y, normal.z);
  36857. uvs.push(faceUV[index].z, faceUV[index].w);
  36858. if (faceColors) {
  36859. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36860. }
  36861. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36862. positions.push(vertex.x, vertex.y, vertex.z);
  36863. normals.push(normal.x, normal.y, normal.z);
  36864. uvs.push(faceUV[index].x, faceUV[index].w);
  36865. if (faceColors) {
  36866. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36867. }
  36868. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36869. positions.push(vertex.x, vertex.y, vertex.z);
  36870. normals.push(normal.x, normal.y, normal.z);
  36871. uvs.push(faceUV[index].x, faceUV[index].y);
  36872. if (faceColors) {
  36873. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36874. }
  36875. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36876. positions.push(vertex.x, vertex.y, vertex.z);
  36877. normals.push(normal.x, normal.y, normal.z);
  36878. uvs.push(faceUV[index].z, faceUV[index].y);
  36879. if (faceColors) {
  36880. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36881. }
  36882. }
  36883. // sides
  36884. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36885. // Result
  36886. var vertexData = new VertexData();
  36887. vertexData.indices = indices;
  36888. vertexData.positions = positions;
  36889. vertexData.normals = normals;
  36890. vertexData.uvs = uvs;
  36891. if (faceColors) {
  36892. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36893. vertexData.colors = totalColors;
  36894. }
  36895. return vertexData;
  36896. };
  36897. /**
  36898. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36899. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36900. * * segments sets the number of horizontal strips optional, default 32
  36901. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36902. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36903. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36904. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36905. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  36906. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  36907. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36908. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36909. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36910. * @returns the VertexData of the ellipsoid
  36911. */
  36912. VertexData.CreateSphere = function (options) {
  36913. var segments = options.segments || 32;
  36914. var diameterX = options.diameterX || options.diameter || 1;
  36915. var diameterY = options.diameterY || options.diameter || 1;
  36916. var diameterZ = options.diameterZ || options.diameter || 1;
  36917. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36918. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36919. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36920. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36921. var totalZRotationSteps = 2 + segments;
  36922. var totalYRotationSteps = 2 * totalZRotationSteps;
  36923. var indices = [];
  36924. var positions = [];
  36925. var normals = [];
  36926. var uvs = [];
  36927. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36928. var normalizedZ = zRotationStep / totalZRotationSteps;
  36929. var angleZ = normalizedZ * Math.PI * slice;
  36930. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36931. var normalizedY = yRotationStep / totalYRotationSteps;
  36932. var angleY = normalizedY * Math.PI * 2 * arc;
  36933. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36934. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36935. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36936. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36937. var vertex = complete.multiply(radius);
  36938. var normal = complete.divide(radius).normalize();
  36939. positions.push(vertex.x, vertex.y, vertex.z);
  36940. normals.push(normal.x, normal.y, normal.z);
  36941. uvs.push(normalizedY, normalizedZ);
  36942. }
  36943. if (zRotationStep > 0) {
  36944. var verticesCount = positions.length / 3;
  36945. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36946. indices.push((firstIndex));
  36947. indices.push((firstIndex + 1));
  36948. indices.push(firstIndex + totalYRotationSteps + 1);
  36949. indices.push((firstIndex + totalYRotationSteps + 1));
  36950. indices.push((firstIndex + 1));
  36951. indices.push((firstIndex + totalYRotationSteps + 2));
  36952. }
  36953. }
  36954. }
  36955. // Sides
  36956. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36957. // Result
  36958. var vertexData = new VertexData();
  36959. vertexData.indices = indices;
  36960. vertexData.positions = positions;
  36961. vertexData.normals = normals;
  36962. vertexData.uvs = uvs;
  36963. return vertexData;
  36964. };
  36965. /**
  36966. * Creates the VertexData for a cylinder, cone or prism
  36967. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36968. * * height sets the height (y direction) of the cylinder, optional, default 2
  36969. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36970. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36971. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36972. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36973. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36974. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  36975. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36976. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36977. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36978. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36979. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36980. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  36981. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  36982. * @returns the VertexData of the cylinder, cone or prism
  36983. */
  36984. VertexData.CreateCylinder = function (options) {
  36985. var height = options.height || 2;
  36986. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36987. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36988. var tessellation = options.tessellation || 24;
  36989. var subdivisions = options.subdivisions || 1;
  36990. var hasRings = options.hasRings ? true : false;
  36991. var enclose = options.enclose ? true : false;
  36992. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36993. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36994. var faceUV = options.faceUV || new Array(3);
  36995. var faceColors = options.faceColors;
  36996. // default face colors and UV if undefined
  36997. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36998. var ringNb = (hasRings) ? subdivisions : 1;
  36999. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37000. var f;
  37001. for (f = 0; f < surfaceNb; f++) {
  37002. if (faceColors && faceColors[f] === undefined) {
  37003. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37004. }
  37005. }
  37006. for (f = 0; f < surfaceNb; f++) {
  37007. if (faceUV && faceUV[f] === undefined) {
  37008. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37009. }
  37010. }
  37011. var indices = new Array();
  37012. var positions = new Array();
  37013. var normals = new Array();
  37014. var uvs = new Array();
  37015. var colors = new Array();
  37016. var angle_step = Math.PI * 2 * arc / tessellation;
  37017. var angle;
  37018. var h;
  37019. var radius;
  37020. var tan = (diameterBottom - diameterTop) / 2 / height;
  37021. var ringVertex = BABYLON.Vector3.Zero();
  37022. var ringNormal = BABYLON.Vector3.Zero();
  37023. var ringFirstVertex = BABYLON.Vector3.Zero();
  37024. var ringFirstNormal = BABYLON.Vector3.Zero();
  37025. var quadNormal = BABYLON.Vector3.Zero();
  37026. var Y = BABYLON.Axis.Y;
  37027. // positions, normals, uvs
  37028. var i;
  37029. var j;
  37030. var r;
  37031. var ringIdx = 1;
  37032. var s = 1; // surface index
  37033. var cs = 0;
  37034. var v = 0;
  37035. for (i = 0; i <= subdivisions; i++) {
  37036. h = i / subdivisions;
  37037. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37038. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37039. for (r = 0; r < ringIdx; r++) {
  37040. if (hasRings) {
  37041. s += r;
  37042. }
  37043. if (enclose) {
  37044. s += 2 * r;
  37045. }
  37046. for (j = 0; j <= tessellation; j++) {
  37047. angle = j * angle_step;
  37048. // position
  37049. ringVertex.x = Math.cos(-angle) * radius;
  37050. ringVertex.y = -height / 2 + h * height;
  37051. ringVertex.z = Math.sin(-angle) * radius;
  37052. // normal
  37053. if (diameterTop === 0 && i === subdivisions) {
  37054. // if no top cap, reuse former normals
  37055. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37056. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37057. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37058. }
  37059. else {
  37060. ringNormal.x = ringVertex.x;
  37061. ringNormal.z = ringVertex.z;
  37062. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37063. ringNormal.normalize();
  37064. }
  37065. // keep first ring vertex values for enclose
  37066. if (j === 0) {
  37067. ringFirstVertex.copyFrom(ringVertex);
  37068. ringFirstNormal.copyFrom(ringNormal);
  37069. }
  37070. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37071. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37072. if (hasRings) {
  37073. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37074. }
  37075. else {
  37076. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37077. }
  37078. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37079. if (faceColors) {
  37080. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37081. }
  37082. }
  37083. // if enclose, add four vertices and their dedicated normals
  37084. if (arc !== 1 && enclose) {
  37085. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37086. positions.push(0, ringVertex.y, 0);
  37087. positions.push(0, ringVertex.y, 0);
  37088. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37089. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37090. quadNormal.normalize();
  37091. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37092. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37093. quadNormal.normalize();
  37094. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37095. if (hasRings) {
  37096. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37097. }
  37098. else {
  37099. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37100. }
  37101. uvs.push(faceUV[s + 1].x, v);
  37102. uvs.push(faceUV[s + 1].z, v);
  37103. if (hasRings) {
  37104. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37105. }
  37106. else {
  37107. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37108. }
  37109. uvs.push(faceUV[s + 2].x, v);
  37110. uvs.push(faceUV[s + 2].z, v);
  37111. if (faceColors) {
  37112. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37113. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37114. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37115. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37116. }
  37117. }
  37118. if (cs !== s) {
  37119. cs = s;
  37120. }
  37121. }
  37122. }
  37123. // indices
  37124. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37125. var s;
  37126. i = 0;
  37127. for (s = 0; s < subdivisions; s++) {
  37128. var i0 = 0;
  37129. var i1 = 0;
  37130. var i2 = 0;
  37131. var i3 = 0;
  37132. for (j = 0; j < tessellation; j++) {
  37133. i0 = i * (e + 1) + j;
  37134. i1 = (i + 1) * (e + 1) + j;
  37135. i2 = i * (e + 1) + (j + 1);
  37136. i3 = (i + 1) * (e + 1) + (j + 1);
  37137. indices.push(i0, i1, i2);
  37138. indices.push(i3, i2, i1);
  37139. }
  37140. if (arc !== 1 && enclose) { // if enclose, add two quads
  37141. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37142. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37143. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37144. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37145. }
  37146. i = (hasRings) ? (i + 2) : (i + 1);
  37147. }
  37148. // Caps
  37149. var createCylinderCap = function (isTop) {
  37150. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37151. if (radius === 0) {
  37152. return;
  37153. }
  37154. // Cap positions, normals & uvs
  37155. var angle;
  37156. var circleVector;
  37157. var i;
  37158. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37159. var c = null;
  37160. if (faceColors) {
  37161. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37162. }
  37163. // cap center
  37164. var vbase = positions.length / 3;
  37165. var offset = isTop ? height / 2 : -height / 2;
  37166. var center = new BABYLON.Vector3(0, offset, 0);
  37167. positions.push(center.x, center.y, center.z);
  37168. normals.push(0, isTop ? 1 : -1, 0);
  37169. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37170. if (c) {
  37171. colors.push(c.r, c.g, c.b, c.a);
  37172. }
  37173. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37174. for (i = 0; i <= tessellation; i++) {
  37175. angle = Math.PI * 2 * i * arc / tessellation;
  37176. var cos = Math.cos(-angle);
  37177. var sin = Math.sin(-angle);
  37178. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37179. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37180. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37181. normals.push(0, isTop ? 1 : -1, 0);
  37182. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37183. if (c) {
  37184. colors.push(c.r, c.g, c.b, c.a);
  37185. }
  37186. }
  37187. // Cap indices
  37188. for (i = 0; i < tessellation; i++) {
  37189. if (!isTop) {
  37190. indices.push(vbase);
  37191. indices.push(vbase + (i + 1));
  37192. indices.push(vbase + (i + 2));
  37193. }
  37194. else {
  37195. indices.push(vbase);
  37196. indices.push(vbase + (i + 2));
  37197. indices.push(vbase + (i + 1));
  37198. }
  37199. }
  37200. };
  37201. // add caps to geometry
  37202. createCylinderCap(false);
  37203. createCylinderCap(true);
  37204. // Sides
  37205. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37206. var vertexData = new VertexData();
  37207. vertexData.indices = indices;
  37208. vertexData.positions = positions;
  37209. vertexData.normals = normals;
  37210. vertexData.uvs = uvs;
  37211. if (faceColors) {
  37212. vertexData.colors = colors;
  37213. }
  37214. return vertexData;
  37215. };
  37216. /**
  37217. * Creates the VertexData for a torus
  37218. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37219. * * diameter the diameter of the torus, optional default 1
  37220. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37221. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37222. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37223. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37224. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37225. * @returns the VertexData of the torus
  37226. */
  37227. VertexData.CreateTorus = function (options) {
  37228. var indices = [];
  37229. var positions = [];
  37230. var normals = [];
  37231. var uvs = [];
  37232. var diameter = options.diameter || 1;
  37233. var thickness = options.thickness || 0.5;
  37234. var tessellation = options.tessellation || 16;
  37235. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37236. var stride = tessellation + 1;
  37237. for (var i = 0; i <= tessellation; i++) {
  37238. var u = i / tessellation;
  37239. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37240. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37241. for (var j = 0; j <= tessellation; j++) {
  37242. var v = 1 - j / tessellation;
  37243. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37244. var dx = Math.cos(innerAngle);
  37245. var dy = Math.sin(innerAngle);
  37246. // Create a vertex.
  37247. var normal = new BABYLON.Vector3(dx, dy, 0);
  37248. var position = normal.scale(thickness / 2);
  37249. var textureCoordinate = new BABYLON.Vector2(u, v);
  37250. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37251. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37252. positions.push(position.x, position.y, position.z);
  37253. normals.push(normal.x, normal.y, normal.z);
  37254. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37255. // And create indices for two triangles.
  37256. var nextI = (i + 1) % stride;
  37257. var nextJ = (j + 1) % stride;
  37258. indices.push(i * stride + j);
  37259. indices.push(i * stride + nextJ);
  37260. indices.push(nextI * stride + j);
  37261. indices.push(i * stride + nextJ);
  37262. indices.push(nextI * stride + nextJ);
  37263. indices.push(nextI * stride + j);
  37264. }
  37265. }
  37266. // Sides
  37267. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37268. // Result
  37269. var vertexData = new VertexData();
  37270. vertexData.indices = indices;
  37271. vertexData.positions = positions;
  37272. vertexData.normals = normals;
  37273. vertexData.uvs = uvs;
  37274. return vertexData;
  37275. };
  37276. /**
  37277. * Creates the VertexData of the LineSystem
  37278. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37279. * - lines an array of lines, each line being an array of successive Vector3
  37280. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37281. * @returns the VertexData of the LineSystem
  37282. */
  37283. VertexData.CreateLineSystem = function (options) {
  37284. var indices = [];
  37285. var positions = [];
  37286. var lines = options.lines;
  37287. var colors = options.colors;
  37288. var vertexColors = [];
  37289. var idx = 0;
  37290. for (var l = 0; l < lines.length; l++) {
  37291. var points = lines[l];
  37292. for (var index = 0; index < points.length; index++) {
  37293. positions.push(points[index].x, points[index].y, points[index].z);
  37294. if (colors) {
  37295. var color = colors[l];
  37296. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37297. }
  37298. if (index > 0) {
  37299. indices.push(idx - 1);
  37300. indices.push(idx);
  37301. }
  37302. idx++;
  37303. }
  37304. }
  37305. var vertexData = new VertexData();
  37306. vertexData.indices = indices;
  37307. vertexData.positions = positions;
  37308. if (colors) {
  37309. vertexData.colors = vertexColors;
  37310. }
  37311. return vertexData;
  37312. };
  37313. /**
  37314. * Create the VertexData for a DashedLines
  37315. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37316. * - points an array successive Vector3
  37317. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37318. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37319. * - dashNb the intended total number of dashes, optional, default 200
  37320. * @returns the VertexData for the DashedLines
  37321. */
  37322. VertexData.CreateDashedLines = function (options) {
  37323. var dashSize = options.dashSize || 3;
  37324. var gapSize = options.gapSize || 1;
  37325. var dashNb = options.dashNb || 200;
  37326. var points = options.points;
  37327. var positions = new Array();
  37328. var indices = new Array();
  37329. var curvect = BABYLON.Vector3.Zero();
  37330. var lg = 0;
  37331. var nb = 0;
  37332. var shft = 0;
  37333. var dashshft = 0;
  37334. var curshft = 0;
  37335. var idx = 0;
  37336. var i = 0;
  37337. for (i = 0; i < points.length - 1; i++) {
  37338. points[i + 1].subtractToRef(points[i], curvect);
  37339. lg += curvect.length();
  37340. }
  37341. shft = lg / dashNb;
  37342. dashshft = dashSize * shft / (dashSize + gapSize);
  37343. for (i = 0; i < points.length - 1; i++) {
  37344. points[i + 1].subtractToRef(points[i], curvect);
  37345. nb = Math.floor(curvect.length() / shft);
  37346. curvect.normalize();
  37347. for (var j = 0; j < nb; j++) {
  37348. curshft = shft * j;
  37349. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37350. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37351. indices.push(idx, idx + 1);
  37352. idx += 2;
  37353. }
  37354. }
  37355. // Result
  37356. var vertexData = new VertexData();
  37357. vertexData.positions = positions;
  37358. vertexData.indices = indices;
  37359. return vertexData;
  37360. };
  37361. /**
  37362. * Creates the VertexData for a Ground
  37363. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37364. * - width the width (x direction) of the ground, optional, default 1
  37365. * - height the height (z direction) of the ground, optional, default 1
  37366. * - subdivisions the number of subdivisions per side, optional, default 1
  37367. * @returns the VertexData of the Ground
  37368. */
  37369. VertexData.CreateGround = function (options) {
  37370. var indices = [];
  37371. var positions = [];
  37372. var normals = [];
  37373. var uvs = [];
  37374. var row, col;
  37375. var width = options.width || 1;
  37376. var height = options.height || 1;
  37377. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37378. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37379. for (row = 0; row <= subdivisionsY; row++) {
  37380. for (col = 0; col <= subdivisionsX; col++) {
  37381. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37382. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37383. positions.push(position.x, position.y, position.z);
  37384. normals.push(normal.x, normal.y, normal.z);
  37385. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37386. }
  37387. }
  37388. for (row = 0; row < subdivisionsY; row++) {
  37389. for (col = 0; col < subdivisionsX; col++) {
  37390. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37391. indices.push(col + 1 + row * (subdivisionsX + 1));
  37392. indices.push(col + row * (subdivisionsX + 1));
  37393. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37394. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37395. indices.push(col + row * (subdivisionsX + 1));
  37396. }
  37397. }
  37398. // Result
  37399. var vertexData = new VertexData();
  37400. vertexData.indices = indices;
  37401. vertexData.positions = positions;
  37402. vertexData.normals = normals;
  37403. vertexData.uvs = uvs;
  37404. return vertexData;
  37405. };
  37406. /**
  37407. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37408. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37409. * * xmin the ground minimum X coordinate, optional, default -1
  37410. * * zmin the ground minimum Z coordinate, optional, default -1
  37411. * * xmax the ground maximum X coordinate, optional, default 1
  37412. * * zmax the ground maximum Z coordinate, optional, default 1
  37413. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37414. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37415. * @returns the VertexData of the TiledGround
  37416. */
  37417. VertexData.CreateTiledGround = function (options) {
  37418. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37419. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37420. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37421. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37422. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37423. var precision = options.precision || { w: 1, h: 1 };
  37424. var indices = new Array();
  37425. var positions = new Array();
  37426. var normals = new Array();
  37427. var uvs = new Array();
  37428. var row, col, tileRow, tileCol;
  37429. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37430. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37431. precision.w = (precision.w < 1) ? 1 : precision.w;
  37432. precision.h = (precision.h < 1) ? 1 : precision.h;
  37433. var tileSize = {
  37434. 'w': (xmax - xmin) / subdivisions.w,
  37435. 'h': (zmax - zmin) / subdivisions.h
  37436. };
  37437. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37438. // Indices
  37439. var base = positions.length / 3;
  37440. var rowLength = precision.w + 1;
  37441. for (row = 0; row < precision.h; row++) {
  37442. for (col = 0; col < precision.w; col++) {
  37443. var square = [
  37444. base + col + row * rowLength,
  37445. base + (col + 1) + row * rowLength,
  37446. base + (col + 1) + (row + 1) * rowLength,
  37447. base + col + (row + 1) * rowLength
  37448. ];
  37449. indices.push(square[1]);
  37450. indices.push(square[2]);
  37451. indices.push(square[3]);
  37452. indices.push(square[0]);
  37453. indices.push(square[1]);
  37454. indices.push(square[3]);
  37455. }
  37456. }
  37457. // Position, normals and uvs
  37458. var position = BABYLON.Vector3.Zero();
  37459. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37460. for (row = 0; row <= precision.h; row++) {
  37461. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37462. for (col = 0; col <= precision.w; col++) {
  37463. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37464. position.y = 0;
  37465. positions.push(position.x, position.y, position.z);
  37466. normals.push(normal.x, normal.y, normal.z);
  37467. uvs.push(col / precision.w, row / precision.h);
  37468. }
  37469. }
  37470. }
  37471. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37472. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37473. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37474. }
  37475. }
  37476. // Result
  37477. var vertexData = new VertexData();
  37478. vertexData.indices = indices;
  37479. vertexData.positions = positions;
  37480. vertexData.normals = normals;
  37481. vertexData.uvs = uvs;
  37482. return vertexData;
  37483. };
  37484. /**
  37485. * Creates the VertexData of the Ground designed from a heightmap
  37486. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37487. * * width the width (x direction) of the ground
  37488. * * height the height (z direction) of the ground
  37489. * * subdivisions the number of subdivisions per side
  37490. * * minHeight the minimum altitude on the ground, optional, default 0
  37491. * * maxHeight the maximum altitude on the ground, optional default 1
  37492. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37493. * * buffer the array holding the image color data
  37494. * * bufferWidth the width of image
  37495. * * bufferHeight the height of image
  37496. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  37497. * @returns the VertexData of the Ground designed from a heightmap
  37498. */
  37499. VertexData.CreateGroundFromHeightMap = function (options) {
  37500. var indices = [];
  37501. var positions = [];
  37502. var normals = [];
  37503. var uvs = [];
  37504. var row, col;
  37505. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37506. var alphaFilter = options.alphaFilter || 0.0;
  37507. // Vertices
  37508. for (row = 0; row <= options.subdivisions; row++) {
  37509. for (col = 0; col <= options.subdivisions; col++) {
  37510. 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));
  37511. // Compute height
  37512. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37513. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37514. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37515. var r = options.buffer[pos] / 255.0;
  37516. var g = options.buffer[pos + 1] / 255.0;
  37517. var b = options.buffer[pos + 2] / 255.0;
  37518. var a = options.buffer[pos + 3] / 255.0;
  37519. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37520. // If our alpha channel is not within our filter then we will assign a 'special' height
  37521. // Then when building the indices, we will ignore any vertex that is using the special height
  37522. if (a >= alphaFilter)
  37523. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37524. else {
  37525. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  37526. }
  37527. // Add vertex
  37528. positions.push(position.x, position.y, position.z);
  37529. normals.push(0, 0, 0);
  37530. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37531. }
  37532. }
  37533. // Indices
  37534. for (row = 0; row < options.subdivisions; row++) {
  37535. for (col = 0; col < options.subdivisions; col++) {
  37536. // Calculate Indices
  37537. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  37538. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  37539. var idx3 = (col + row * (options.subdivisions + 1));
  37540. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  37541. // Check that all indices are visible (based on our special height)
  37542. // Only display the vertex if all Indices are visible
  37543. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  37544. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  37545. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  37546. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  37547. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  37548. indices.push(idx1);
  37549. indices.push(idx2);
  37550. indices.push(idx3);
  37551. }
  37552. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  37553. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  37554. indices.push(idx4);
  37555. indices.push(idx1);
  37556. indices.push(idx3);
  37557. }
  37558. }
  37559. }
  37560. // Normals
  37561. VertexData.ComputeNormals(positions, indices, normals);
  37562. // Result
  37563. var vertexData = new VertexData();
  37564. vertexData.indices = indices;
  37565. vertexData.positions = positions;
  37566. vertexData.normals = normals;
  37567. vertexData.uvs = uvs;
  37568. return vertexData;
  37569. };
  37570. /**
  37571. * Creates the VertexData for a Plane
  37572. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37573. * * size sets the width and height of the plane to the value of size, optional default 1
  37574. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37575. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37576. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37577. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37578. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37579. * @returns the VertexData of the box
  37580. */
  37581. VertexData.CreatePlane = function (options) {
  37582. var indices = [];
  37583. var positions = [];
  37584. var normals = [];
  37585. var uvs = [];
  37586. var width = options.width || options.size || 1;
  37587. var height = options.height || options.size || 1;
  37588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37589. // Vertices
  37590. var halfWidth = width / 2.0;
  37591. var halfHeight = height / 2.0;
  37592. positions.push(-halfWidth, -halfHeight, 0);
  37593. normals.push(0, 0, -1.0);
  37594. uvs.push(0.0, 0.0);
  37595. positions.push(halfWidth, -halfHeight, 0);
  37596. normals.push(0, 0, -1.0);
  37597. uvs.push(1.0, 0.0);
  37598. positions.push(halfWidth, halfHeight, 0);
  37599. normals.push(0, 0, -1.0);
  37600. uvs.push(1.0, 1.0);
  37601. positions.push(-halfWidth, halfHeight, 0);
  37602. normals.push(0, 0, -1.0);
  37603. uvs.push(0.0, 1.0);
  37604. // Indices
  37605. indices.push(0);
  37606. indices.push(1);
  37607. indices.push(2);
  37608. indices.push(0);
  37609. indices.push(2);
  37610. indices.push(3);
  37611. // Sides
  37612. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37613. // Result
  37614. var vertexData = new VertexData();
  37615. vertexData.indices = indices;
  37616. vertexData.positions = positions;
  37617. vertexData.normals = normals;
  37618. vertexData.uvs = uvs;
  37619. return vertexData;
  37620. };
  37621. /**
  37622. * Creates the VertexData of the Disc or regular Polygon
  37623. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37624. * * radius the radius of the disc, optional default 0.5
  37625. * * tessellation the number of polygon sides, optional, default 64
  37626. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  37627. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37628. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37629. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37630. * @returns the VertexData of the box
  37631. */
  37632. VertexData.CreateDisc = function (options) {
  37633. var positions = new Array();
  37634. var indices = new Array();
  37635. var normals = new Array();
  37636. var uvs = new Array();
  37637. var radius = options.radius || 0.5;
  37638. var tessellation = options.tessellation || 64;
  37639. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37640. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37641. // positions and uvs
  37642. positions.push(0, 0, 0); // disc center first
  37643. uvs.push(0.5, 0.5);
  37644. var theta = Math.PI * 2 * arc;
  37645. var step = theta / tessellation;
  37646. for (var a = 0; a < theta; a += step) {
  37647. var x = Math.cos(a);
  37648. var y = Math.sin(a);
  37649. var u = (x + 1) / 2;
  37650. var v = (1 - y) / 2;
  37651. positions.push(radius * x, radius * y, 0);
  37652. uvs.push(u, v);
  37653. }
  37654. if (arc === 1) {
  37655. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37656. uvs.push(uvs[2], uvs[3]);
  37657. }
  37658. //indices
  37659. var vertexNb = positions.length / 3;
  37660. for (var i = 1; i < vertexNb - 1; i++) {
  37661. indices.push(i + 1, 0, i);
  37662. }
  37663. // result
  37664. VertexData.ComputeNormals(positions, indices, normals);
  37665. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37666. var vertexData = new VertexData();
  37667. vertexData.indices = indices;
  37668. vertexData.positions = positions;
  37669. vertexData.normals = normals;
  37670. vertexData.uvs = uvs;
  37671. return vertexData;
  37672. };
  37673. /**
  37674. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37675. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37676. * @param polygon a mesh built from polygonTriangulation.build()
  37677. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37678. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37679. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37680. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37681. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37682. * @returns the VertexData of the Polygon
  37683. */
  37684. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37685. var faceUV = fUV || new Array(3);
  37686. var faceColors = fColors;
  37687. var colors = [];
  37688. // default face colors and UV if undefined
  37689. for (var f = 0; f < 3; f++) {
  37690. if (faceUV[f] === undefined) {
  37691. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37692. }
  37693. if (faceColors && faceColors[f] === undefined) {
  37694. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37695. }
  37696. }
  37697. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37698. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37699. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37700. var indices = polygon.getIndices();
  37701. // set face colours and textures
  37702. var idx = 0;
  37703. var face = 0;
  37704. for (var index = 0; index < normals.length; index += 3) {
  37705. //Edge Face no. 1
  37706. if (Math.abs(normals[index + 1]) < 0.001) {
  37707. face = 1;
  37708. }
  37709. //Top Face no. 0
  37710. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37711. face = 0;
  37712. }
  37713. //Bottom Face no. 2
  37714. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37715. face = 2;
  37716. }
  37717. idx = index / 3;
  37718. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37719. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37720. if (faceColors) {
  37721. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37722. }
  37723. }
  37724. // sides
  37725. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37726. // Result
  37727. var vertexData = new VertexData();
  37728. vertexData.indices = indices;
  37729. vertexData.positions = positions;
  37730. vertexData.normals = normals;
  37731. vertexData.uvs = uvs;
  37732. if (faceColors) {
  37733. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37734. vertexData.colors = totalColors;
  37735. }
  37736. return vertexData;
  37737. };
  37738. /**
  37739. * Creates the VertexData of the IcoSphere
  37740. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37741. * * radius the radius of the IcoSphere, optional default 1
  37742. * * radiusX allows stretching in the x direction, optional, default radius
  37743. * * radiusY allows stretching in the y direction, optional, default radius
  37744. * * radiusZ allows stretching in the z direction, optional, default radius
  37745. * * flat when true creates a flat shaded mesh, optional, default true
  37746. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37747. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37748. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37749. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37750. * @returns the VertexData of the IcoSphere
  37751. */
  37752. VertexData.CreateIcoSphere = function (options) {
  37753. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37754. var radius = options.radius || 1;
  37755. var flat = (options.flat === undefined) ? true : options.flat;
  37756. var subdivisions = options.subdivisions || 4;
  37757. var radiusX = options.radiusX || radius;
  37758. var radiusY = options.radiusY || radius;
  37759. var radiusZ = options.radiusZ || radius;
  37760. var t = (1 + Math.sqrt(5)) / 2;
  37761. // 12 vertex x,y,z
  37762. var ico_vertices = [
  37763. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37764. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37765. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37766. ];
  37767. // index of 3 vertex makes a face of icopshere
  37768. var ico_indices = [
  37769. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37770. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37771. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37772. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37773. ];
  37774. // vertex for uv have aliased position, not for UV
  37775. var vertices_unalias_id = [
  37776. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37777. // vertex alias
  37778. 0,
  37779. 2,
  37780. 3,
  37781. 3,
  37782. 3,
  37783. 4,
  37784. 7,
  37785. 8,
  37786. 9,
  37787. 9,
  37788. 10,
  37789. 11 // 23: B + 12
  37790. ];
  37791. // uv as integer step (not pixels !)
  37792. var ico_vertexuv = [
  37793. 5, 1, 3, 1, 6, 4, 0, 0,
  37794. 5, 3, 4, 2, 2, 2, 4, 0,
  37795. 2, 0, 1, 1, 6, 0, 6, 2,
  37796. // vertex alias (for same vertex on different faces)
  37797. 0, 4,
  37798. 3, 3,
  37799. 4, 4,
  37800. 3, 1,
  37801. 4, 2,
  37802. 4, 4,
  37803. 0, 2,
  37804. 1, 1,
  37805. 2, 2,
  37806. 3, 3,
  37807. 1, 3,
  37808. 2, 4 // 23: B + 12
  37809. ];
  37810. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37811. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37812. // First island of uv mapping
  37813. // v = 4h 3+ 2
  37814. // v = 3h 9+ 4
  37815. // v = 2h 9+ 5 B
  37816. // v = 1h 9 1 0
  37817. // v = 0h 3 8 7 A
  37818. // u = 0 1 2 3 4 5 6 *a
  37819. // Second island of uv mapping
  37820. // v = 4h 0+ B+ 4+
  37821. // v = 3h A+ 2+
  37822. // v = 2h 7+ 6 3+
  37823. // v = 1h 8+ 3+
  37824. // v = 0h
  37825. // u = 0 1 2 3 4 5 6 *a
  37826. // Face layout on texture UV mapping
  37827. // ============
  37828. // \ 4 /\ 16 / ======
  37829. // \ / \ / /\ 11 /
  37830. // \/ 7 \/ / \ /
  37831. // ======= / 10 \/
  37832. // /\ 17 /\ =======
  37833. // / \ / \ \ 15 /\
  37834. // / 8 \/ 12 \ \ / \
  37835. // ============ \/ 6 \
  37836. // \ 18 /\ ============
  37837. // \ / \ \ 5 /\ 0 /
  37838. // \/ 13 \ \ / \ /
  37839. // ======= \/ 1 \/
  37840. // =============
  37841. // /\ 19 /\ 2 /\
  37842. // / \ / \ / \
  37843. // / 14 \/ 9 \/ 3 \
  37844. // ===================
  37845. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37846. var ustep = 138 / 1024;
  37847. var vstep = 239 / 1024;
  37848. var uoffset = 60 / 1024;
  37849. var voffset = 26 / 1024;
  37850. // Second island should have margin, not to touch the first island
  37851. // avoid any borderline artefact in pixel rounding
  37852. var island_u_offset = -40 / 1024;
  37853. var island_v_offset = +20 / 1024;
  37854. // face is either island 0 or 1 :
  37855. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37856. var island = [
  37857. 0, 0, 0, 0, 1,
  37858. 0, 0, 1, 1, 0,
  37859. 0, 0, 1, 1, 0,
  37860. 0, 1, 1, 1, 0 // 15 - 19
  37861. ];
  37862. var indices = new Array();
  37863. var positions = new Array();
  37864. var normals = new Array();
  37865. var uvs = new Array();
  37866. var current_indice = 0;
  37867. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37868. var face_vertex_pos = new Array(3);
  37869. var face_vertex_uv = new Array(3);
  37870. var v012;
  37871. for (v012 = 0; v012 < 3; v012++) {
  37872. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37873. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37874. }
  37875. // create all with normals
  37876. for (var face = 0; face < 20; face++) {
  37877. // 3 vertex per face
  37878. for (v012 = 0; v012 < 3; v012++) {
  37879. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37880. var v_id = ico_indices[3 * face + v012];
  37881. // vertex have 3D position (x,y,z)
  37882. 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]);
  37883. // Normalize to get normal, then scale to radius
  37884. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37885. // uv Coordinates from vertex ID
  37886. 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);
  37887. }
  37888. // Subdivide the face (interpolate pos, norm, uv)
  37889. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37890. // - norm is linear interpolation of vertex corner normal
  37891. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37892. // - uv is linear interpolation
  37893. //
  37894. // Topology is as below for sub-divide by 2
  37895. // vertex shown as v0,v1,v2
  37896. // interp index is i1 to progress in range [v0,v1[
  37897. // interp index is i2 to progress in range [v0,v2[
  37898. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37899. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37900. //
  37901. //
  37902. // i2 v2
  37903. // ^ ^
  37904. // / / \
  37905. // / / \
  37906. // / / \
  37907. // / / (0,1) \
  37908. // / #---------\
  37909. // / / \ (0,0)'/ \
  37910. // / / \ / \
  37911. // / / \ / \
  37912. // / / (0,0) \ / (1,0) \
  37913. // / #---------#---------\
  37914. // v0 v1
  37915. //
  37916. // --------------------> i1
  37917. //
  37918. // interp of (i1,i2):
  37919. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37920. // along i1 : lerp(x0,x1, i1/(S-i2))
  37921. //
  37922. // centroid of triangle is needed to get help normal computation
  37923. // (c1,c2) are used for centroid location
  37924. var interp_vertex = function (i1, i2, c1, c2) {
  37925. // vertex is interpolated from
  37926. // - face_vertex_pos[0..2]
  37927. // - face_vertex_uv[0..2]
  37928. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37929. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37930. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37931. pos_interp.normalize();
  37932. var vertex_normal;
  37933. if (flat) {
  37934. // in flat mode, recalculate normal as face centroid normal
  37935. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37936. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37937. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37938. }
  37939. else {
  37940. // in smooth mode, recalculate normal from each single vertex position
  37941. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37942. }
  37943. // Vertex normal need correction due to X,Y,Z radius scaling
  37944. vertex_normal.x /= radiusX;
  37945. vertex_normal.y /= radiusY;
  37946. vertex_normal.z /= radiusZ;
  37947. vertex_normal.normalize();
  37948. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37949. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37950. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37951. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37952. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37953. uvs.push(uv_interp.x, uv_interp.y);
  37954. // push each vertex has member of a face
  37955. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37956. indices.push(current_indice);
  37957. current_indice++;
  37958. };
  37959. for (var i2 = 0; i2 < subdivisions; i2++) {
  37960. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37961. // face : (i1,i2) for /\ :
  37962. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37963. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37964. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37965. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37966. if (i1 + i2 + 1 < subdivisions) {
  37967. // face : (i1,i2)' for \/ :
  37968. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37969. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37970. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37971. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37972. }
  37973. }
  37974. }
  37975. }
  37976. // Sides
  37977. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37978. // Result
  37979. var vertexData = new VertexData();
  37980. vertexData.indices = indices;
  37981. vertexData.positions = positions;
  37982. vertexData.normals = normals;
  37983. vertexData.uvs = uvs;
  37984. return vertexData;
  37985. };
  37986. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37987. /**
  37988. * Creates the VertexData for a Polyhedron
  37989. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37990. * * type provided types are:
  37991. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37992. * * 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)
  37993. * * size the size of the IcoSphere, optional default 1
  37994. * * sizeX allows stretching in the x direction, optional, default size
  37995. * * sizeY allows stretching in the y direction, optional, default size
  37996. * * sizeZ allows stretching in the z direction, optional, default size
  37997. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  37998. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37999. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38000. * * flat when true creates a flat shaded mesh, optional, default true
  38001. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38002. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38003. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38004. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38005. * @returns the VertexData of the Polyhedron
  38006. */
  38007. VertexData.CreatePolyhedron = function (options) {
  38008. // provided polyhedron types :
  38009. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38010. // 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)
  38011. var polyhedra = [];
  38012. 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]] };
  38013. 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]] };
  38014. polyhedra[2] = {
  38015. 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]],
  38016. 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]]
  38017. };
  38018. polyhedra[3] = {
  38019. 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]],
  38020. 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]]
  38021. };
  38022. polyhedra[4] = {
  38023. 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]],
  38024. 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]]
  38025. };
  38026. 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]] };
  38027. 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]] };
  38028. 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]] };
  38029. 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]] };
  38030. 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]] };
  38031. 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]] };
  38032. 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]] };
  38033. 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]] };
  38034. 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]] };
  38035. polyhedra[14] = {
  38036. 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]],
  38037. 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]]
  38038. };
  38039. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38040. var size = options.size;
  38041. var sizeX = options.sizeX || size || 1;
  38042. var sizeY = options.sizeY || size || 1;
  38043. var sizeZ = options.sizeZ || size || 1;
  38044. var data = options.custom || polyhedra[type];
  38045. var nbfaces = data.face.length;
  38046. var faceUV = options.faceUV || new Array(nbfaces);
  38047. var faceColors = options.faceColors;
  38048. var flat = (options.flat === undefined) ? true : options.flat;
  38049. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38050. var positions = new Array();
  38051. var indices = new Array();
  38052. var normals = new Array();
  38053. var uvs = new Array();
  38054. var colors = new Array();
  38055. var index = 0;
  38056. var faceIdx = 0; // face cursor in the array "indexes"
  38057. var indexes = new Array();
  38058. var i = 0;
  38059. var f = 0;
  38060. var u, v, ang, x, y, tmp;
  38061. // default face colors and UV if undefined
  38062. if (flat) {
  38063. for (f = 0; f < nbfaces; f++) {
  38064. if (faceColors && faceColors[f] === undefined) {
  38065. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38066. }
  38067. if (faceUV && faceUV[f] === undefined) {
  38068. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38069. }
  38070. }
  38071. }
  38072. if (!flat) {
  38073. for (i = 0; i < data.vertex.length; i++) {
  38074. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38075. uvs.push(0, 0);
  38076. }
  38077. for (f = 0; f < nbfaces; f++) {
  38078. for (i = 0; i < data.face[f].length - 2; i++) {
  38079. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38080. }
  38081. }
  38082. }
  38083. else {
  38084. for (f = 0; f < nbfaces; f++) {
  38085. var fl = data.face[f].length; // number of vertices of the current face
  38086. ang = 2 * Math.PI / fl;
  38087. x = 0.5 * Math.tan(ang / 2);
  38088. y = 0.5;
  38089. // positions, uvs, colors
  38090. for (i = 0; i < fl; i++) {
  38091. // positions
  38092. 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);
  38093. indexes.push(index);
  38094. index++;
  38095. // uvs
  38096. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38097. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38098. uvs.push(u, v);
  38099. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38100. y = x * Math.sin(ang) + y * Math.cos(ang);
  38101. x = tmp;
  38102. // colors
  38103. if (faceColors) {
  38104. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38105. }
  38106. }
  38107. // indices from indexes
  38108. for (i = 0; i < fl - 2; i++) {
  38109. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38110. }
  38111. faceIdx += fl;
  38112. }
  38113. }
  38114. VertexData.ComputeNormals(positions, indices, normals);
  38115. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38116. var vertexData = new VertexData();
  38117. vertexData.positions = positions;
  38118. vertexData.indices = indices;
  38119. vertexData.normals = normals;
  38120. vertexData.uvs = uvs;
  38121. if (faceColors && flat) {
  38122. vertexData.colors = colors;
  38123. }
  38124. return vertexData;
  38125. };
  38126. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38127. /**
  38128. * Creates the VertexData for a TorusKnot
  38129. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38130. * * radius the radius of the torus knot, optional, default 2
  38131. * * tube the thickness of the tube, optional, default 0.5
  38132. * * radialSegments the number of sides on each tube segments, optional, default 32
  38133. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38134. * * p the number of windings around the z axis, optional, default 2
  38135. * * q the number of windings around the x axis, optional, default 3
  38136. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38137. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38138. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38139. * @returns the VertexData of the Torus Knot
  38140. */
  38141. VertexData.CreateTorusKnot = function (options) {
  38142. var indices = new Array();
  38143. var positions = new Array();
  38144. var normals = new Array();
  38145. var uvs = new Array();
  38146. var radius = options.radius || 2;
  38147. var tube = options.tube || 0.5;
  38148. var radialSegments = options.radialSegments || 32;
  38149. var tubularSegments = options.tubularSegments || 32;
  38150. var p = options.p || 2;
  38151. var q = options.q || 3;
  38152. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38153. // Helper
  38154. var getPos = function (angle) {
  38155. var cu = Math.cos(angle);
  38156. var su = Math.sin(angle);
  38157. var quOverP = q / p * angle;
  38158. var cs = Math.cos(quOverP);
  38159. var tx = radius * (2 + cs) * 0.5 * cu;
  38160. var ty = radius * (2 + cs) * su * 0.5;
  38161. var tz = radius * Math.sin(quOverP) * 0.5;
  38162. return new BABYLON.Vector3(tx, ty, tz);
  38163. };
  38164. // Vertices
  38165. var i;
  38166. var j;
  38167. for (i = 0; i <= radialSegments; i++) {
  38168. var modI = i % radialSegments;
  38169. var u = modI / radialSegments * 2 * p * Math.PI;
  38170. var p1 = getPos(u);
  38171. var p2 = getPos(u + 0.01);
  38172. var tang = p2.subtract(p1);
  38173. var n = p2.add(p1);
  38174. var bitan = BABYLON.Vector3.Cross(tang, n);
  38175. n = BABYLON.Vector3.Cross(bitan, tang);
  38176. bitan.normalize();
  38177. n.normalize();
  38178. for (j = 0; j < tubularSegments; j++) {
  38179. var modJ = j % tubularSegments;
  38180. var v = modJ / tubularSegments * 2 * Math.PI;
  38181. var cx = -tube * Math.cos(v);
  38182. var cy = tube * Math.sin(v);
  38183. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38184. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38185. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38186. uvs.push(i / radialSegments);
  38187. uvs.push(j / tubularSegments);
  38188. }
  38189. }
  38190. for (i = 0; i < radialSegments; i++) {
  38191. for (j = 0; j < tubularSegments; j++) {
  38192. var jNext = (j + 1) % tubularSegments;
  38193. var a = i * tubularSegments + j;
  38194. var b = (i + 1) * tubularSegments + j;
  38195. var c = (i + 1) * tubularSegments + jNext;
  38196. var d = i * tubularSegments + jNext;
  38197. indices.push(d);
  38198. indices.push(b);
  38199. indices.push(a);
  38200. indices.push(d);
  38201. indices.push(c);
  38202. indices.push(b);
  38203. }
  38204. }
  38205. // Normals
  38206. VertexData.ComputeNormals(positions, indices, normals);
  38207. // Sides
  38208. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38209. // Result
  38210. var vertexData = new VertexData();
  38211. vertexData.indices = indices;
  38212. vertexData.positions = positions;
  38213. vertexData.normals = normals;
  38214. vertexData.uvs = uvs;
  38215. return vertexData;
  38216. };
  38217. // Tools
  38218. /**
  38219. * Compute normals for given positions and indices
  38220. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38221. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38222. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38223. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38224. * * facetNormals : optional array of facet normals (vector3)
  38225. * * facetPositions : optional array of facet positions (vector3)
  38226. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38227. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38228. * * bInfo : optional bounding info, required for facetPartitioning computation
  38229. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38230. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38231. * * useRightHandedSystem: optional boolean to for right handed system computation
  38232. * * depthSort : optional boolean to enable the facet depth sort computation
  38233. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38234. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38235. */
  38236. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38237. // temporary scalar variables
  38238. var index = 0; // facet index
  38239. var p1p2x = 0.0; // p1p2 vector x coordinate
  38240. var p1p2y = 0.0; // p1p2 vector y coordinate
  38241. var p1p2z = 0.0; // p1p2 vector z coordinate
  38242. var p3p2x = 0.0; // p3p2 vector x coordinate
  38243. var p3p2y = 0.0; // p3p2 vector y coordinate
  38244. var p3p2z = 0.0; // p3p2 vector z coordinate
  38245. var faceNormalx = 0.0; // facet normal x coordinate
  38246. var faceNormaly = 0.0; // facet normal y coordinate
  38247. var faceNormalz = 0.0; // facet normal z coordinate
  38248. var length = 0.0; // facet normal length before normalization
  38249. var v1x = 0; // vector1 x index in the positions array
  38250. var v1y = 0; // vector1 y index in the positions array
  38251. var v1z = 0; // vector1 z index in the positions array
  38252. var v2x = 0; // vector2 x index in the positions array
  38253. var v2y = 0; // vector2 y index in the positions array
  38254. var v2z = 0; // vector2 z index in the positions array
  38255. var v3x = 0; // vector3 x index in the positions array
  38256. var v3y = 0; // vector3 y index in the positions array
  38257. var v3z = 0; // vector3 z index in the positions array
  38258. var computeFacetNormals = false;
  38259. var computeFacetPositions = false;
  38260. var computeFacetPartitioning = false;
  38261. var computeDepthSort = false;
  38262. var faceNormalSign = 1;
  38263. var ratio = 0;
  38264. var distanceTo = null;
  38265. if (options) {
  38266. computeFacetNormals = (options.facetNormals) ? true : false;
  38267. computeFacetPositions = (options.facetPositions) ? true : false;
  38268. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38269. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38270. ratio = options.ratio || 0;
  38271. computeDepthSort = (options.depthSort) ? true : false;
  38272. distanceTo = (options.distanceTo);
  38273. if (computeDepthSort) {
  38274. if (distanceTo === undefined) {
  38275. distanceTo = BABYLON.Vector3.Zero();
  38276. }
  38277. var depthSortedFacets = options.depthSortedFacets;
  38278. }
  38279. }
  38280. // facetPartitioning reinit if needed
  38281. var xSubRatio = 0;
  38282. var ySubRatio = 0;
  38283. var zSubRatio = 0;
  38284. var subSq = 0;
  38285. if (computeFacetPartitioning && options && options.bbSize) {
  38286. var ox = 0; // X partitioning index for facet position
  38287. var oy = 0; // Y partinioning index for facet position
  38288. var oz = 0; // Z partinioning index for facet position
  38289. var b1x = 0; // X partitioning index for facet v1 vertex
  38290. var b1y = 0; // Y partitioning index for facet v1 vertex
  38291. var b1z = 0; // z partitioning index for facet v1 vertex
  38292. var b2x = 0; // X partitioning index for facet v2 vertex
  38293. var b2y = 0; // Y partitioning index for facet v2 vertex
  38294. var b2z = 0; // Z partitioning index for facet v2 vertex
  38295. var b3x = 0; // X partitioning index for facet v3 vertex
  38296. var b3y = 0; // Y partitioning index for facet v3 vertex
  38297. var b3z = 0; // Z partitioning index for facet v3 vertex
  38298. var block_idx_o = 0; // facet barycenter block index
  38299. var block_idx_v1 = 0; // v1 vertex block index
  38300. var block_idx_v2 = 0; // v2 vertex block index
  38301. var block_idx_v3 = 0; // v3 vertex block index
  38302. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38303. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38304. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38305. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38306. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38307. subSq = options.subDiv.max * options.subDiv.max;
  38308. options.facetPartitioning.length = 0;
  38309. }
  38310. // reset the normals
  38311. for (index = 0; index < positions.length; index++) {
  38312. normals[index] = 0.0;
  38313. }
  38314. // Loop : 1 indice triplet = 1 facet
  38315. var nbFaces = (indices.length / 3) | 0;
  38316. for (index = 0; index < nbFaces; index++) {
  38317. // get the indexes of the coordinates of each vertex of the facet
  38318. v1x = indices[index * 3] * 3;
  38319. v1y = v1x + 1;
  38320. v1z = v1x + 2;
  38321. v2x = indices[index * 3 + 1] * 3;
  38322. v2y = v2x + 1;
  38323. v2z = v2x + 2;
  38324. v3x = indices[index * 3 + 2] * 3;
  38325. v3y = v3x + 1;
  38326. v3z = v3x + 2;
  38327. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38328. p1p2y = positions[v1y] - positions[v2y];
  38329. p1p2z = positions[v1z] - positions[v2z];
  38330. p3p2x = positions[v3x] - positions[v2x];
  38331. p3p2y = positions[v3y] - positions[v2y];
  38332. p3p2z = positions[v3z] - positions[v2z];
  38333. // compute the face normal with the cross product
  38334. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38335. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38336. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38337. // normalize this normal and store it in the array facetData
  38338. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38339. length = (length === 0) ? 1.0 : length;
  38340. faceNormalx /= length;
  38341. faceNormaly /= length;
  38342. faceNormalz /= length;
  38343. if (computeFacetNormals && options) {
  38344. options.facetNormals[index].x = faceNormalx;
  38345. options.facetNormals[index].y = faceNormaly;
  38346. options.facetNormals[index].z = faceNormalz;
  38347. }
  38348. if (computeFacetPositions && options) {
  38349. // compute and the facet barycenter coordinates in the array facetPositions
  38350. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38351. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38352. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38353. }
  38354. if (computeFacetPartitioning && options) {
  38355. // store the facet indexes in arrays in the main facetPartitioning array :
  38356. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38357. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38358. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38359. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38360. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38361. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38362. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38363. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38364. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38365. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38366. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38367. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38368. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38369. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38370. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38371. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38372. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38373. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38374. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38375. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38376. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38377. // push each facet index in each block containing the vertex
  38378. options.facetPartitioning[block_idx_v1].push(index);
  38379. if (block_idx_v2 != block_idx_v1) {
  38380. options.facetPartitioning[block_idx_v2].push(index);
  38381. }
  38382. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38383. options.facetPartitioning[block_idx_v3].push(index);
  38384. }
  38385. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38386. options.facetPartitioning[block_idx_o].push(index);
  38387. }
  38388. }
  38389. if (computeDepthSort && options && options.facetPositions) {
  38390. var dsf = depthSortedFacets[index];
  38391. dsf.ind = index * 3;
  38392. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38393. }
  38394. // compute the normals anyway
  38395. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38396. normals[v1y] += faceNormaly;
  38397. normals[v1z] += faceNormalz;
  38398. normals[v2x] += faceNormalx;
  38399. normals[v2y] += faceNormaly;
  38400. normals[v2z] += faceNormalz;
  38401. normals[v3x] += faceNormalx;
  38402. normals[v3y] += faceNormaly;
  38403. normals[v3z] += faceNormalz;
  38404. }
  38405. // last normalization of each normal
  38406. for (index = 0; index < normals.length / 3; index++) {
  38407. faceNormalx = normals[index * 3];
  38408. faceNormaly = normals[index * 3 + 1];
  38409. faceNormalz = normals[index * 3 + 2];
  38410. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38411. length = (length === 0) ? 1.0 : length;
  38412. faceNormalx /= length;
  38413. faceNormaly /= length;
  38414. faceNormalz /= length;
  38415. normals[index * 3] = faceNormalx;
  38416. normals[index * 3 + 1] = faceNormaly;
  38417. normals[index * 3 + 2] = faceNormalz;
  38418. }
  38419. };
  38420. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38421. var li = indices.length;
  38422. var ln = normals.length;
  38423. var i;
  38424. var n;
  38425. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38426. switch (sideOrientation) {
  38427. case BABYLON.Mesh.FRONTSIDE:
  38428. // nothing changed
  38429. break;
  38430. case BABYLON.Mesh.BACKSIDE:
  38431. var tmp;
  38432. // indices
  38433. for (i = 0; i < li; i += 3) {
  38434. tmp = indices[i];
  38435. indices[i] = indices[i + 2];
  38436. indices[i + 2] = tmp;
  38437. }
  38438. // normals
  38439. for (n = 0; n < ln; n++) {
  38440. normals[n] = -normals[n];
  38441. }
  38442. break;
  38443. case BABYLON.Mesh.DOUBLESIDE:
  38444. // positions
  38445. var lp = positions.length;
  38446. var l = lp / 3;
  38447. for (var p = 0; p < lp; p++) {
  38448. positions[lp + p] = positions[p];
  38449. }
  38450. // indices
  38451. for (i = 0; i < li; i += 3) {
  38452. indices[i + li] = indices[i + 2] + l;
  38453. indices[i + 1 + li] = indices[i + 1] + l;
  38454. indices[i + 2 + li] = indices[i] + l;
  38455. }
  38456. // normals
  38457. for (n = 0; n < ln; n++) {
  38458. normals[ln + n] = -normals[n];
  38459. }
  38460. // uvs
  38461. var lu = uvs.length;
  38462. var u = 0;
  38463. for (u = 0; u < lu; u++) {
  38464. uvs[u + lu] = uvs[u];
  38465. }
  38466. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38467. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38468. u = 0;
  38469. for (i = 0; i < lu / 2; i++) {
  38470. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38471. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38472. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38473. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38474. u += 2;
  38475. }
  38476. break;
  38477. }
  38478. };
  38479. /**
  38480. * Applies VertexData created from the imported parameters to the geometry
  38481. * @param parsedVertexData the parsed data from an imported file
  38482. * @param geometry the geometry to apply the VertexData to
  38483. */
  38484. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38485. var vertexData = new VertexData();
  38486. // positions
  38487. var positions = parsedVertexData.positions;
  38488. if (positions) {
  38489. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38490. }
  38491. // normals
  38492. var normals = parsedVertexData.normals;
  38493. if (normals) {
  38494. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38495. }
  38496. // tangents
  38497. var tangents = parsedVertexData.tangents;
  38498. if (tangents) {
  38499. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38500. }
  38501. // uvs
  38502. var uvs = parsedVertexData.uvs;
  38503. if (uvs) {
  38504. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38505. }
  38506. // uv2s
  38507. var uv2s = parsedVertexData.uv2s;
  38508. if (uv2s) {
  38509. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38510. }
  38511. // uv3s
  38512. var uv3s = parsedVertexData.uv3s;
  38513. if (uv3s) {
  38514. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38515. }
  38516. // uv4s
  38517. var uv4s = parsedVertexData.uv4s;
  38518. if (uv4s) {
  38519. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38520. }
  38521. // uv5s
  38522. var uv5s = parsedVertexData.uv5s;
  38523. if (uv5s) {
  38524. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38525. }
  38526. // uv6s
  38527. var uv6s = parsedVertexData.uv6s;
  38528. if (uv6s) {
  38529. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38530. }
  38531. // colors
  38532. var colors = parsedVertexData.colors;
  38533. if (colors) {
  38534. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38535. }
  38536. // matricesIndices
  38537. var matricesIndices = parsedVertexData.matricesIndices;
  38538. if (matricesIndices) {
  38539. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38540. }
  38541. // matricesWeights
  38542. var matricesWeights = parsedVertexData.matricesWeights;
  38543. if (matricesWeights) {
  38544. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38545. }
  38546. // indices
  38547. var indices = parsedVertexData.indices;
  38548. if (indices) {
  38549. vertexData.indices = indices;
  38550. }
  38551. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38552. };
  38553. return VertexData;
  38554. }());
  38555. BABYLON.VertexData = VertexData;
  38556. })(BABYLON || (BABYLON = {}));
  38557. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38558. var BABYLON;
  38559. (function (BABYLON) {
  38560. /**
  38561. * Class used to store geometry data (vertex buffers + index buffer)
  38562. */
  38563. var Geometry = /** @class */ (function () {
  38564. /**
  38565. * Creates a new geometry
  38566. * @param id defines the unique ID
  38567. * @param scene defines the hosting scene
  38568. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38569. * @param updatable defines if geometry must be updatable (false by default)
  38570. * @param mesh defines the mesh that will be associated with the geometry
  38571. */
  38572. function Geometry(id, scene, vertexData, updatable, mesh) {
  38573. if (updatable === void 0) { updatable = false; }
  38574. if (mesh === void 0) { mesh = null; }
  38575. /**
  38576. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38577. */
  38578. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38579. this._totalVertices = 0;
  38580. this._isDisposed = false;
  38581. this._indexBufferIsUpdatable = false;
  38582. this.id = id;
  38583. this._engine = scene.getEngine();
  38584. this._meshes = [];
  38585. this._scene = scene;
  38586. //Init vertex buffer cache
  38587. this._vertexBuffers = {};
  38588. this._indices = [];
  38589. this._updatable = updatable;
  38590. // vertexData
  38591. if (vertexData) {
  38592. this.setAllVerticesData(vertexData, updatable);
  38593. }
  38594. else {
  38595. this._totalVertices = 0;
  38596. this._indices = [];
  38597. }
  38598. if (this._engine.getCaps().vertexArrayObject) {
  38599. this._vertexArrayObjects = {};
  38600. }
  38601. // applyToMesh
  38602. if (mesh) {
  38603. if (mesh.getClassName() === "LinesMesh") {
  38604. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38605. this._updateExtend();
  38606. }
  38607. this.applyToMesh(mesh);
  38608. mesh.computeWorldMatrix(true);
  38609. }
  38610. }
  38611. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38612. /**
  38613. * 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
  38614. */
  38615. get: function () {
  38616. return this._boundingBias;
  38617. },
  38618. /**
  38619. * 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
  38620. */
  38621. set: function (value) {
  38622. if (this._boundingBias && this._boundingBias.equals(value)) {
  38623. return;
  38624. }
  38625. this._boundingBias = value.clone();
  38626. this._updateBoundingInfo(true, null);
  38627. },
  38628. enumerable: true,
  38629. configurable: true
  38630. });
  38631. /**
  38632. * Static function used to attach a new empty geometry to a mesh
  38633. * @param mesh defines the mesh to attach the geometry to
  38634. * @returns the new {BABYLON.Geometry}
  38635. */
  38636. Geometry.CreateGeometryForMesh = function (mesh) {
  38637. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38638. geometry.applyToMesh(mesh);
  38639. return geometry;
  38640. };
  38641. Object.defineProperty(Geometry.prototype, "extend", {
  38642. /**
  38643. * Gets the current extend of the geometry
  38644. */
  38645. get: function () {
  38646. return this._extend;
  38647. },
  38648. enumerable: true,
  38649. configurable: true
  38650. });
  38651. /**
  38652. * Gets the hosting scene
  38653. * @returns the hosting {BABYLON.Scene}
  38654. */
  38655. Geometry.prototype.getScene = function () {
  38656. return this._scene;
  38657. };
  38658. /**
  38659. * Gets the hosting engine
  38660. * @returns the hosting {BABYLON.Engine}
  38661. */
  38662. Geometry.prototype.getEngine = function () {
  38663. return this._engine;
  38664. };
  38665. /**
  38666. * Defines if the geometry is ready to use
  38667. * @returns true if the geometry is ready to be used
  38668. */
  38669. Geometry.prototype.isReady = function () {
  38670. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38671. };
  38672. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38673. /**
  38674. * Gets a value indicating that the geometry should not be serialized
  38675. */
  38676. get: function () {
  38677. for (var index = 0; index < this._meshes.length; index++) {
  38678. if (!this._meshes[index].doNotSerialize) {
  38679. return false;
  38680. }
  38681. }
  38682. return true;
  38683. },
  38684. enumerable: true,
  38685. configurable: true
  38686. });
  38687. /** @hidden */
  38688. Geometry.prototype._rebuild = function () {
  38689. if (this._vertexArrayObjects) {
  38690. this._vertexArrayObjects = {};
  38691. }
  38692. // Index buffer
  38693. if (this._meshes.length !== 0 && this._indices) {
  38694. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38695. }
  38696. // Vertex buffers
  38697. for (var key in this._vertexBuffers) {
  38698. var vertexBuffer = this._vertexBuffers[key];
  38699. vertexBuffer._rebuild();
  38700. }
  38701. };
  38702. /**
  38703. * Affects all geometry data in one call
  38704. * @param vertexData defines the geometry data
  38705. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38706. */
  38707. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38708. vertexData.applyToGeometry(this, updatable);
  38709. this.notifyUpdate();
  38710. };
  38711. /**
  38712. * Set specific vertex data
  38713. * @param kind defines the data kind (Position, normal, etc...)
  38714. * @param data defines the vertex data to use
  38715. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38716. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38717. */
  38718. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38719. if (updatable === void 0) { updatable = false; }
  38720. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38721. this.setVerticesBuffer(buffer);
  38722. };
  38723. /**
  38724. * Removes a specific vertex data
  38725. * @param kind defines the data kind (Position, normal, etc...)
  38726. */
  38727. Geometry.prototype.removeVerticesData = function (kind) {
  38728. if (this._vertexBuffers[kind]) {
  38729. this._vertexBuffers[kind].dispose();
  38730. delete this._vertexBuffers[kind];
  38731. }
  38732. };
  38733. /**
  38734. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38735. * @param buffer defines the vertex buffer to use
  38736. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38737. */
  38738. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38739. if (totalVertices === void 0) { totalVertices = null; }
  38740. var kind = buffer.getKind();
  38741. if (this._vertexBuffers[kind]) {
  38742. this._vertexBuffers[kind].dispose();
  38743. }
  38744. this._vertexBuffers[kind] = buffer;
  38745. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38746. var data = buffer.getData();
  38747. if (totalVertices != null) {
  38748. this._totalVertices = totalVertices;
  38749. }
  38750. else {
  38751. if (data != null) {
  38752. this._totalVertices = data.length / (buffer.byteStride / 4);
  38753. }
  38754. }
  38755. this._updateExtend(data);
  38756. this._resetPointsArrayCache();
  38757. var meshes = this._meshes;
  38758. var numOfMeshes = meshes.length;
  38759. for (var index = 0; index < numOfMeshes; index++) {
  38760. var mesh = meshes[index];
  38761. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38762. mesh._createGlobalSubMesh(false);
  38763. mesh.computeWorldMatrix(true);
  38764. }
  38765. }
  38766. this.notifyUpdate(kind);
  38767. if (this._vertexArrayObjects) {
  38768. this._disposeVertexArrayObjects();
  38769. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38770. }
  38771. };
  38772. /**
  38773. * Update a specific vertex buffer
  38774. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38775. * It will do nothing if the buffer is not updatable
  38776. * @param kind defines the data kind (Position, normal, etc...)
  38777. * @param data defines the data to use
  38778. * @param offset defines the offset in the target buffer where to store the data
  38779. * @param useBytes set to true if the offset is in bytes
  38780. */
  38781. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38782. if (useBytes === void 0) { useBytes = false; }
  38783. var vertexBuffer = this.getVertexBuffer(kind);
  38784. if (!vertexBuffer) {
  38785. return;
  38786. }
  38787. vertexBuffer.updateDirectly(data, offset, useBytes);
  38788. this.notifyUpdate(kind);
  38789. };
  38790. /**
  38791. * Update a specific vertex buffer
  38792. * This function will create a new buffer if the current one is not updatable
  38793. * @param kind defines the data kind (Position, normal, etc...)
  38794. * @param data defines the data to use
  38795. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38796. */
  38797. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38798. if (updateExtends === void 0) { updateExtends = false; }
  38799. var vertexBuffer = this.getVertexBuffer(kind);
  38800. if (!vertexBuffer) {
  38801. return;
  38802. }
  38803. vertexBuffer.update(data);
  38804. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38805. this._updateBoundingInfo(updateExtends, data);
  38806. }
  38807. this.notifyUpdate(kind);
  38808. };
  38809. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38810. if (updateExtends) {
  38811. this._updateExtend(data);
  38812. }
  38813. var meshes = this._meshes;
  38814. var numOfMeshes = meshes.length;
  38815. this._resetPointsArrayCache();
  38816. for (var index = 0; index < numOfMeshes; index++) {
  38817. var mesh = meshes[index];
  38818. if (updateExtends) {
  38819. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38820. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38821. var subMesh = mesh.subMeshes[subIndex];
  38822. subMesh.refreshBoundingInfo();
  38823. }
  38824. }
  38825. }
  38826. };
  38827. /** @hidden */
  38828. Geometry.prototype._bind = function (effect, indexToBind) {
  38829. if (!effect) {
  38830. return;
  38831. }
  38832. if (indexToBind === undefined) {
  38833. indexToBind = this._indexBuffer;
  38834. }
  38835. var vbs = this.getVertexBuffers();
  38836. if (!vbs) {
  38837. return;
  38838. }
  38839. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38840. this._engine.bindBuffers(vbs, indexToBind, effect);
  38841. return;
  38842. }
  38843. // Using VAO
  38844. if (!this._vertexArrayObjects[effect.key]) {
  38845. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38846. }
  38847. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38848. };
  38849. /**
  38850. * Gets total number of vertices
  38851. * @returns the total number of vertices
  38852. */
  38853. Geometry.prototype.getTotalVertices = function () {
  38854. if (!this.isReady()) {
  38855. return 0;
  38856. }
  38857. return this._totalVertices;
  38858. };
  38859. /**
  38860. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38861. * @param kind defines the data kind (Position, normal, etc...)
  38862. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38863. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38864. * @returns a float array containing vertex data
  38865. */
  38866. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38867. var vertexBuffer = this.getVertexBuffer(kind);
  38868. if (!vertexBuffer) {
  38869. return null;
  38870. }
  38871. var data = vertexBuffer.getData();
  38872. if (!data) {
  38873. return null;
  38874. }
  38875. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38876. var count = this._totalVertices * vertexBuffer.getSize();
  38877. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38878. var copy_1 = new Array(count);
  38879. vertexBuffer.forEach(count, function (value, index) {
  38880. copy_1[index] = value;
  38881. });
  38882. return copy_1;
  38883. }
  38884. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38885. if (data instanceof Array) {
  38886. var offset = vertexBuffer.byteOffset / 4;
  38887. return BABYLON.Tools.Slice(data, offset, offset + count);
  38888. }
  38889. else if (data instanceof ArrayBuffer) {
  38890. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38891. }
  38892. else {
  38893. var offset = data.byteOffset + vertexBuffer.byteOffset;
  38894. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38895. var result = new Float32Array(count);
  38896. var source = new Float32Array(data.buffer, offset, count);
  38897. result.set(source);
  38898. return result;
  38899. }
  38900. return new Float32Array(data.buffer, offset, count);
  38901. }
  38902. }
  38903. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38904. return BABYLON.Tools.Slice(data);
  38905. }
  38906. return data;
  38907. };
  38908. /**
  38909. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38910. * @param kind defines the data kind (Position, normal, etc...)
  38911. * @returns true if the vertex buffer with the specified kind is updatable
  38912. */
  38913. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38914. var vb = this._vertexBuffers[kind];
  38915. if (!vb) {
  38916. return false;
  38917. }
  38918. return vb.isUpdatable();
  38919. };
  38920. /**
  38921. * Gets a specific vertex buffer
  38922. * @param kind defines the data kind (Position, normal, etc...)
  38923. * @returns a {BABYLON.VertexBuffer}
  38924. */
  38925. Geometry.prototype.getVertexBuffer = function (kind) {
  38926. if (!this.isReady()) {
  38927. return null;
  38928. }
  38929. return this._vertexBuffers[kind];
  38930. };
  38931. /**
  38932. * Returns all vertex buffers
  38933. * @return an object holding all vertex buffers indexed by kind
  38934. */
  38935. Geometry.prototype.getVertexBuffers = function () {
  38936. if (!this.isReady()) {
  38937. return null;
  38938. }
  38939. return this._vertexBuffers;
  38940. };
  38941. /**
  38942. * Gets a boolean indicating if specific vertex buffer is present
  38943. * @param kind defines the data kind (Position, normal, etc...)
  38944. * @returns true if data is present
  38945. */
  38946. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38947. if (!this._vertexBuffers) {
  38948. if (this._delayInfo) {
  38949. return this._delayInfo.indexOf(kind) !== -1;
  38950. }
  38951. return false;
  38952. }
  38953. return this._vertexBuffers[kind] !== undefined;
  38954. };
  38955. /**
  38956. * Gets a list of all attached data kinds (Position, normal, etc...)
  38957. * @returns a list of string containing all kinds
  38958. */
  38959. Geometry.prototype.getVerticesDataKinds = function () {
  38960. var result = [];
  38961. var kind;
  38962. if (!this._vertexBuffers && this._delayInfo) {
  38963. for (kind in this._delayInfo) {
  38964. result.push(kind);
  38965. }
  38966. }
  38967. else {
  38968. for (kind in this._vertexBuffers) {
  38969. result.push(kind);
  38970. }
  38971. }
  38972. return result;
  38973. };
  38974. /**
  38975. * Update index buffer
  38976. * @param indices defines the indices to store in the index buffer
  38977. * @param offset defines the offset in the target buffer where to store the data
  38978. */
  38979. Geometry.prototype.updateIndices = function (indices, offset) {
  38980. if (!this._indexBuffer) {
  38981. return;
  38982. }
  38983. if (!this._indexBufferIsUpdatable) {
  38984. this.setIndices(indices, null, true);
  38985. }
  38986. else {
  38987. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38988. }
  38989. };
  38990. /**
  38991. * Creates a new index buffer
  38992. * @param indices defines the indices to store in the index buffer
  38993. * @param totalVertices defines the total number of vertices (could be null)
  38994. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38995. */
  38996. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38997. if (totalVertices === void 0) { totalVertices = null; }
  38998. if (updatable === void 0) { updatable = false; }
  38999. if (this._indexBuffer) {
  39000. this._engine._releaseBuffer(this._indexBuffer);
  39001. }
  39002. this._disposeVertexArrayObjects();
  39003. this._indices = indices;
  39004. this._indexBufferIsUpdatable = updatable;
  39005. if (this._meshes.length !== 0 && this._indices) {
  39006. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39007. }
  39008. if (totalVertices != undefined) { // including null and undefined
  39009. this._totalVertices = totalVertices;
  39010. }
  39011. var meshes = this._meshes;
  39012. var numOfMeshes = meshes.length;
  39013. for (var index = 0; index < numOfMeshes; index++) {
  39014. meshes[index]._createGlobalSubMesh(true);
  39015. }
  39016. this.notifyUpdate();
  39017. };
  39018. /**
  39019. * Return the total number of indices
  39020. * @returns the total number of indices
  39021. */
  39022. Geometry.prototype.getTotalIndices = function () {
  39023. if (!this.isReady()) {
  39024. return 0;
  39025. }
  39026. return this._indices.length;
  39027. };
  39028. /**
  39029. * Gets the index buffer array
  39030. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39031. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39032. * @returns the index buffer array
  39033. */
  39034. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39035. if (!this.isReady()) {
  39036. return null;
  39037. }
  39038. var orig = this._indices;
  39039. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39040. return orig;
  39041. }
  39042. else {
  39043. var len = orig.length;
  39044. var copy = [];
  39045. for (var i = 0; i < len; i++) {
  39046. copy.push(orig[i]);
  39047. }
  39048. return copy;
  39049. }
  39050. };
  39051. /**
  39052. * Gets the index buffer
  39053. * @return the index buffer
  39054. */
  39055. Geometry.prototype.getIndexBuffer = function () {
  39056. if (!this.isReady()) {
  39057. return null;
  39058. }
  39059. return this._indexBuffer;
  39060. };
  39061. /** @hidden */
  39062. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39063. if (effect === void 0) { effect = null; }
  39064. if (!effect || !this._vertexArrayObjects) {
  39065. return;
  39066. }
  39067. if (this._vertexArrayObjects[effect.key]) {
  39068. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39069. delete this._vertexArrayObjects[effect.key];
  39070. }
  39071. };
  39072. /**
  39073. * Release the associated resources for a specific mesh
  39074. * @param mesh defines the source mesh
  39075. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39076. */
  39077. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39078. var meshes = this._meshes;
  39079. var index = meshes.indexOf(mesh);
  39080. if (index === -1) {
  39081. return;
  39082. }
  39083. meshes.splice(index, 1);
  39084. mesh._geometry = null;
  39085. if (meshes.length === 0 && shouldDispose) {
  39086. this.dispose();
  39087. }
  39088. };
  39089. /**
  39090. * Apply current geometry to a given mesh
  39091. * @param mesh defines the mesh to apply geometry to
  39092. */
  39093. Geometry.prototype.applyToMesh = function (mesh) {
  39094. if (mesh._geometry === this) {
  39095. return;
  39096. }
  39097. var previousGeometry = mesh._geometry;
  39098. if (previousGeometry) {
  39099. previousGeometry.releaseForMesh(mesh);
  39100. }
  39101. var meshes = this._meshes;
  39102. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39103. mesh._geometry = this;
  39104. this._scene.pushGeometry(this);
  39105. meshes.push(mesh);
  39106. if (this.isReady()) {
  39107. this._applyToMesh(mesh);
  39108. }
  39109. else {
  39110. mesh._boundingInfo = this._boundingInfo;
  39111. }
  39112. };
  39113. Geometry.prototype._updateExtend = function (data) {
  39114. if (data === void 0) { data = null; }
  39115. if (!data) {
  39116. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39117. }
  39118. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39119. };
  39120. Geometry.prototype._applyToMesh = function (mesh) {
  39121. var numOfMeshes = this._meshes.length;
  39122. // vertexBuffers
  39123. for (var kind in this._vertexBuffers) {
  39124. if (numOfMeshes === 1) {
  39125. this._vertexBuffers[kind].create();
  39126. }
  39127. var buffer = this._vertexBuffers[kind].getBuffer();
  39128. if (buffer)
  39129. buffer.references = numOfMeshes;
  39130. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39131. if (!this._extend) {
  39132. this._updateExtend();
  39133. }
  39134. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39135. mesh._createGlobalSubMesh(false);
  39136. //bounding info was just created again, world matrix should be applied again.
  39137. mesh._updateBoundingInfo();
  39138. }
  39139. }
  39140. // indexBuffer
  39141. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39142. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39143. }
  39144. if (this._indexBuffer) {
  39145. this._indexBuffer.references = numOfMeshes;
  39146. }
  39147. };
  39148. Geometry.prototype.notifyUpdate = function (kind) {
  39149. if (this.onGeometryUpdated) {
  39150. this.onGeometryUpdated(this, kind);
  39151. }
  39152. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39153. var mesh = _a[_i];
  39154. mesh._markSubMeshesAsAttributesDirty();
  39155. }
  39156. };
  39157. /**
  39158. * Load the geometry if it was flagged as delay loaded
  39159. * @param scene defines the hosting scene
  39160. * @param onLoaded defines a callback called when the geometry is loaded
  39161. */
  39162. Geometry.prototype.load = function (scene, onLoaded) {
  39163. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39164. return;
  39165. }
  39166. if (this.isReady()) {
  39167. if (onLoaded) {
  39168. onLoaded();
  39169. }
  39170. return;
  39171. }
  39172. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39173. this._queueLoad(scene, onLoaded);
  39174. };
  39175. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39176. var _this = this;
  39177. if (!this.delayLoadingFile) {
  39178. return;
  39179. }
  39180. scene._addPendingData(this);
  39181. scene._loadFile(this.delayLoadingFile, function (data) {
  39182. if (!_this._delayLoadingFunction) {
  39183. return;
  39184. }
  39185. _this._delayLoadingFunction(JSON.parse(data), _this);
  39186. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39187. _this._delayInfo = [];
  39188. scene._removePendingData(_this);
  39189. var meshes = _this._meshes;
  39190. var numOfMeshes = meshes.length;
  39191. for (var index = 0; index < numOfMeshes; index++) {
  39192. _this._applyToMesh(meshes[index]);
  39193. }
  39194. if (onLoaded) {
  39195. onLoaded();
  39196. }
  39197. }, undefined, true);
  39198. };
  39199. /**
  39200. * Invert the geometry to move from a right handed system to a left handed one.
  39201. */
  39202. Geometry.prototype.toLeftHanded = function () {
  39203. // Flip faces
  39204. var tIndices = this.getIndices(false);
  39205. if (tIndices != null && tIndices.length > 0) {
  39206. for (var i = 0; i < tIndices.length; i += 3) {
  39207. var tTemp = tIndices[i + 0];
  39208. tIndices[i + 0] = tIndices[i + 2];
  39209. tIndices[i + 2] = tTemp;
  39210. }
  39211. this.setIndices(tIndices);
  39212. }
  39213. // Negate position.z
  39214. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39215. if (tPositions != null && tPositions.length > 0) {
  39216. for (var i = 0; i < tPositions.length; i += 3) {
  39217. tPositions[i + 2] = -tPositions[i + 2];
  39218. }
  39219. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39220. }
  39221. // Negate normal.z
  39222. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39223. if (tNormals != null && tNormals.length > 0) {
  39224. for (var i = 0; i < tNormals.length; i += 3) {
  39225. tNormals[i + 2] = -tNormals[i + 2];
  39226. }
  39227. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39228. }
  39229. };
  39230. // Cache
  39231. /** @hidden */
  39232. Geometry.prototype._resetPointsArrayCache = function () {
  39233. this._positions = null;
  39234. };
  39235. /** @hidden */
  39236. Geometry.prototype._generatePointsArray = function () {
  39237. if (this._positions)
  39238. return true;
  39239. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39240. if (!data || data.length === 0) {
  39241. return false;
  39242. }
  39243. this._positions = [];
  39244. for (var index = 0; index < data.length; index += 3) {
  39245. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39246. }
  39247. return true;
  39248. };
  39249. /**
  39250. * Gets a value indicating if the geometry is disposed
  39251. * @returns true if the geometry was disposed
  39252. */
  39253. Geometry.prototype.isDisposed = function () {
  39254. return this._isDisposed;
  39255. };
  39256. Geometry.prototype._disposeVertexArrayObjects = function () {
  39257. if (this._vertexArrayObjects) {
  39258. for (var kind in this._vertexArrayObjects) {
  39259. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39260. }
  39261. this._vertexArrayObjects = {};
  39262. }
  39263. };
  39264. /**
  39265. * Free all associated resources
  39266. */
  39267. Geometry.prototype.dispose = function () {
  39268. var meshes = this._meshes;
  39269. var numOfMeshes = meshes.length;
  39270. var index;
  39271. for (index = 0; index < numOfMeshes; index++) {
  39272. this.releaseForMesh(meshes[index]);
  39273. }
  39274. this._meshes = [];
  39275. this._disposeVertexArrayObjects();
  39276. for (var kind in this._vertexBuffers) {
  39277. this._vertexBuffers[kind].dispose();
  39278. }
  39279. this._vertexBuffers = {};
  39280. this._totalVertices = 0;
  39281. if (this._indexBuffer) {
  39282. this._engine._releaseBuffer(this._indexBuffer);
  39283. }
  39284. this._indexBuffer = null;
  39285. this._indices = [];
  39286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39287. this.delayLoadingFile = null;
  39288. this._delayLoadingFunction = null;
  39289. this._delayInfo = [];
  39290. this._boundingInfo = null;
  39291. this._scene.removeGeometry(this);
  39292. this._isDisposed = true;
  39293. };
  39294. /**
  39295. * Clone the current geometry into a new geometry
  39296. * @param id defines the unique ID of the new geometry
  39297. * @returns a new geometry object
  39298. */
  39299. Geometry.prototype.copy = function (id) {
  39300. var vertexData = new BABYLON.VertexData();
  39301. vertexData.indices = [];
  39302. var indices = this.getIndices();
  39303. if (indices) {
  39304. for (var index = 0; index < indices.length; index++) {
  39305. vertexData.indices.push(indices[index]);
  39306. }
  39307. }
  39308. var updatable = false;
  39309. var stopChecking = false;
  39310. var kind;
  39311. for (kind in this._vertexBuffers) {
  39312. // using slice() to make a copy of the array and not just reference it
  39313. var data = this.getVerticesData(kind);
  39314. if (data instanceof Float32Array) {
  39315. vertexData.set(new Float32Array(data), kind);
  39316. }
  39317. else {
  39318. vertexData.set(data.slice(0), kind);
  39319. }
  39320. if (!stopChecking) {
  39321. var vb = this.getVertexBuffer(kind);
  39322. if (vb) {
  39323. updatable = vb.isUpdatable();
  39324. stopChecking = !updatable;
  39325. }
  39326. }
  39327. }
  39328. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39329. geometry.delayLoadState = this.delayLoadState;
  39330. geometry.delayLoadingFile = this.delayLoadingFile;
  39331. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39332. for (kind in this._delayInfo) {
  39333. geometry._delayInfo = geometry._delayInfo || [];
  39334. geometry._delayInfo.push(kind);
  39335. }
  39336. // Bounding info
  39337. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39338. return geometry;
  39339. };
  39340. /**
  39341. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39342. * @return a JSON representation of the current geometry data (without the vertices data)
  39343. */
  39344. Geometry.prototype.serialize = function () {
  39345. var serializationObject = {};
  39346. serializationObject.id = this.id;
  39347. serializationObject.updatable = this._updatable;
  39348. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39349. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39350. }
  39351. return serializationObject;
  39352. };
  39353. Geometry.prototype.toNumberArray = function (origin) {
  39354. if (Array.isArray(origin)) {
  39355. return origin;
  39356. }
  39357. else {
  39358. return Array.prototype.slice.call(origin);
  39359. }
  39360. };
  39361. /**
  39362. * Serialize all vertices data into a JSON oject
  39363. * @returns a JSON representation of the current geometry data
  39364. */
  39365. Geometry.prototype.serializeVerticeData = function () {
  39366. var serializationObject = this.serialize();
  39367. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39368. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39369. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39370. serializationObject.positions._updatable = true;
  39371. }
  39372. }
  39373. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39374. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39375. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39376. serializationObject.normals._updatable = true;
  39377. }
  39378. }
  39379. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39380. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39381. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39382. serializationObject.tangets._updatable = true;
  39383. }
  39384. }
  39385. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39386. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39387. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39388. serializationObject.uvs._updatable = true;
  39389. }
  39390. }
  39391. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39392. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39393. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39394. serializationObject.uv2s._updatable = true;
  39395. }
  39396. }
  39397. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39398. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39399. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39400. serializationObject.uv3s._updatable = true;
  39401. }
  39402. }
  39403. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39404. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39405. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39406. serializationObject.uv4s._updatable = true;
  39407. }
  39408. }
  39409. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39410. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39411. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39412. serializationObject.uv5s._updatable = true;
  39413. }
  39414. }
  39415. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39416. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39417. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39418. serializationObject.uv6s._updatable = true;
  39419. }
  39420. }
  39421. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39422. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39423. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39424. serializationObject.colors._updatable = true;
  39425. }
  39426. }
  39427. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39428. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39429. serializationObject.matricesIndices._isExpanded = true;
  39430. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39431. serializationObject.matricesIndices._updatable = true;
  39432. }
  39433. }
  39434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39435. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39436. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39437. serializationObject.matricesWeights._updatable = true;
  39438. }
  39439. }
  39440. serializationObject.indices = this.toNumberArray(this.getIndices());
  39441. return serializationObject;
  39442. };
  39443. // Statics
  39444. /**
  39445. * Extracts a clone of a mesh geometry
  39446. * @param mesh defines the source mesh
  39447. * @param id defines the unique ID of the new geometry object
  39448. * @returns the new geometry object
  39449. */
  39450. Geometry.ExtractFromMesh = function (mesh, id) {
  39451. var geometry = mesh._geometry;
  39452. if (!geometry) {
  39453. return null;
  39454. }
  39455. return geometry.copy(id);
  39456. };
  39457. /**
  39458. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39459. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39460. * Be aware Math.random() could cause collisions, but:
  39461. * "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"
  39462. * @returns a string containing a new GUID
  39463. */
  39464. Geometry.RandomId = function () {
  39465. return BABYLON.Tools.RandomId();
  39466. };
  39467. /** @hidden */
  39468. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39469. var scene = mesh.getScene();
  39470. // Geometry
  39471. var geometryId = parsedGeometry.geometryId;
  39472. if (geometryId) {
  39473. var geometry = scene.getGeometryByID(geometryId);
  39474. if (geometry) {
  39475. geometry.applyToMesh(mesh);
  39476. }
  39477. }
  39478. else if (parsedGeometry instanceof ArrayBuffer) {
  39479. var binaryInfo = mesh._binaryInfo;
  39480. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39481. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39482. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39483. }
  39484. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39485. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39486. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39487. }
  39488. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39489. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39490. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39491. }
  39492. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39493. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39494. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39495. }
  39496. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39497. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39498. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39499. }
  39500. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39501. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39502. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39503. }
  39504. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39505. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39506. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39507. }
  39508. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39509. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39510. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39511. }
  39512. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39513. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39514. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39515. }
  39516. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39517. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39518. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39519. }
  39520. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39521. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39522. var floatIndices = [];
  39523. for (var i = 0; i < matricesIndicesData.length; i++) {
  39524. var index = matricesIndicesData[i];
  39525. floatIndices.push(index & 0x000000FF);
  39526. floatIndices.push((index & 0x0000FF00) >> 8);
  39527. floatIndices.push((index & 0x00FF0000) >> 16);
  39528. floatIndices.push(index >> 24);
  39529. }
  39530. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39531. }
  39532. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39533. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39534. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39535. }
  39536. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39537. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39538. mesh.setIndices(indicesData, null);
  39539. }
  39540. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39541. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39542. mesh.subMeshes = [];
  39543. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39544. var materialIndex = subMeshesData[(i * 5) + 0];
  39545. var verticesStart = subMeshesData[(i * 5) + 1];
  39546. var verticesCount = subMeshesData[(i * 5) + 2];
  39547. var indexStart = subMeshesData[(i * 5) + 3];
  39548. var indexCount = subMeshesData[(i * 5) + 4];
  39549. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39550. }
  39551. }
  39552. }
  39553. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39554. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39555. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39556. if (parsedGeometry.tangents) {
  39557. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39558. }
  39559. if (parsedGeometry.uvs) {
  39560. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39561. }
  39562. if (parsedGeometry.uvs2) {
  39563. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39564. }
  39565. if (parsedGeometry.uvs3) {
  39566. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39567. }
  39568. if (parsedGeometry.uvs4) {
  39569. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39570. }
  39571. if (parsedGeometry.uvs5) {
  39572. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39573. }
  39574. if (parsedGeometry.uvs6) {
  39575. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39576. }
  39577. if (parsedGeometry.colors) {
  39578. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39579. }
  39580. if (parsedGeometry.matricesIndices) {
  39581. if (!parsedGeometry.matricesIndices._isExpanded) {
  39582. var floatIndices = [];
  39583. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39584. var matricesIndex = parsedGeometry.matricesIndices[i];
  39585. floatIndices.push(matricesIndex & 0x000000FF);
  39586. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39587. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39588. floatIndices.push(matricesIndex >> 24);
  39589. }
  39590. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39591. }
  39592. else {
  39593. delete parsedGeometry.matricesIndices._isExpanded;
  39594. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39595. }
  39596. }
  39597. if (parsedGeometry.matricesIndicesExtra) {
  39598. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39599. var floatIndices = [];
  39600. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39601. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39602. floatIndices.push(matricesIndex & 0x000000FF);
  39603. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39604. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39605. floatIndices.push(matricesIndex >> 24);
  39606. }
  39607. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39608. }
  39609. else {
  39610. delete parsedGeometry.matricesIndices._isExpanded;
  39611. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39612. }
  39613. }
  39614. if (parsedGeometry.matricesWeights) {
  39615. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39616. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39617. }
  39618. if (parsedGeometry.matricesWeightsExtra) {
  39619. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39620. }
  39621. mesh.setIndices(parsedGeometry.indices, null);
  39622. }
  39623. // SubMeshes
  39624. if (parsedGeometry.subMeshes) {
  39625. mesh.subMeshes = [];
  39626. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39627. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39628. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39629. }
  39630. }
  39631. // Flat shading
  39632. if (mesh._shouldGenerateFlatShading) {
  39633. mesh.convertToFlatShadedMesh();
  39634. delete mesh._shouldGenerateFlatShading;
  39635. }
  39636. // Update
  39637. mesh.computeWorldMatrix(true);
  39638. scene.onMeshImportedObservable.notifyObservers(mesh);
  39639. };
  39640. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39641. var epsilon = 1e-3;
  39642. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39643. return;
  39644. }
  39645. var noInfluenceBoneIndex = 0.0;
  39646. if (parsedGeometry.skeletonId > -1) {
  39647. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39648. if (!skeleton) {
  39649. return;
  39650. }
  39651. noInfluenceBoneIndex = skeleton.bones.length;
  39652. }
  39653. else {
  39654. return;
  39655. }
  39656. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39657. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39658. var matricesWeights = parsedGeometry.matricesWeights;
  39659. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39660. var influencers = parsedGeometry.numBoneInfluencer;
  39661. var size = matricesWeights.length;
  39662. for (var i = 0; i < size; i += 4) {
  39663. var weight = 0.0;
  39664. var firstZeroWeight = -1;
  39665. for (var j = 0; j < 4; j++) {
  39666. var w = matricesWeights[i + j];
  39667. weight += w;
  39668. if (w < epsilon && firstZeroWeight < 0) {
  39669. firstZeroWeight = j;
  39670. }
  39671. }
  39672. if (matricesWeightsExtra) {
  39673. for (var j = 0; j < 4; j++) {
  39674. var w = matricesWeightsExtra[i + j];
  39675. weight += w;
  39676. if (w < epsilon && firstZeroWeight < 0) {
  39677. firstZeroWeight = j + 4;
  39678. }
  39679. }
  39680. }
  39681. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39682. firstZeroWeight = influencers - 1;
  39683. }
  39684. if (weight > epsilon) {
  39685. var mweight = 1.0 / weight;
  39686. for (var j = 0; j < 4; j++) {
  39687. matricesWeights[i + j] *= mweight;
  39688. }
  39689. if (matricesWeightsExtra) {
  39690. for (var j = 0; j < 4; j++) {
  39691. matricesWeightsExtra[i + j] *= mweight;
  39692. }
  39693. }
  39694. }
  39695. else {
  39696. if (firstZeroWeight >= 4) {
  39697. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39698. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39699. }
  39700. else {
  39701. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39702. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39703. }
  39704. }
  39705. }
  39706. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39707. if (parsedGeometry.matricesWeightsExtra) {
  39708. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39709. }
  39710. };
  39711. /**
  39712. * Create a new geometry from persisted data (Using .babylon file format)
  39713. * @param parsedVertexData defines the persisted data
  39714. * @param scene defines the hosting scene
  39715. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39716. * @returns the new geometry object
  39717. */
  39718. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39719. if (scene.getGeometryByID(parsedVertexData.id)) {
  39720. return null; // null since geometry could be something else than a box...
  39721. }
  39722. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39723. if (BABYLON.Tags) {
  39724. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39725. }
  39726. if (parsedVertexData.delayLoadingFile) {
  39727. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39728. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39729. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39730. geometry._delayInfo = [];
  39731. if (parsedVertexData.hasUVs) {
  39732. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39733. }
  39734. if (parsedVertexData.hasUVs2) {
  39735. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39736. }
  39737. if (parsedVertexData.hasUVs3) {
  39738. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39739. }
  39740. if (parsedVertexData.hasUVs4) {
  39741. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39742. }
  39743. if (parsedVertexData.hasUVs5) {
  39744. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39745. }
  39746. if (parsedVertexData.hasUVs6) {
  39747. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39748. }
  39749. if (parsedVertexData.hasColors) {
  39750. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39751. }
  39752. if (parsedVertexData.hasMatricesIndices) {
  39753. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39754. }
  39755. if (parsedVertexData.hasMatricesWeights) {
  39756. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39757. }
  39758. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39759. }
  39760. else {
  39761. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39762. }
  39763. scene.pushGeometry(geometry, true);
  39764. return geometry;
  39765. };
  39766. return Geometry;
  39767. }());
  39768. BABYLON.Geometry = Geometry;
  39769. // Primitives
  39770. /// Abstract class
  39771. /**
  39772. * Abstract class used to provide common services for all typed geometries
  39773. * @hidden
  39774. */
  39775. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39776. __extends(_PrimitiveGeometry, _super);
  39777. /**
  39778. * Creates a new typed geometry
  39779. * @param id defines the unique ID of the geometry
  39780. * @param scene defines the hosting scene
  39781. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39782. * @param mesh defines the hosting mesh (can be null)
  39783. */
  39784. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39785. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39786. if (mesh === void 0) { mesh = null; }
  39787. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39788. _this._canBeRegenerated = _canBeRegenerated;
  39789. _this._beingRegenerated = true;
  39790. _this.regenerate();
  39791. _this._beingRegenerated = false;
  39792. return _this;
  39793. }
  39794. /**
  39795. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39796. * @returns true if the geometry can be regenerated
  39797. */
  39798. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39799. return this._canBeRegenerated;
  39800. };
  39801. /**
  39802. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39803. */
  39804. _PrimitiveGeometry.prototype.regenerate = function () {
  39805. if (!this._canBeRegenerated) {
  39806. return;
  39807. }
  39808. this._beingRegenerated = true;
  39809. this.setAllVerticesData(this._regenerateVertexData(), false);
  39810. this._beingRegenerated = false;
  39811. };
  39812. /**
  39813. * Clone the geometry
  39814. * @param id defines the unique ID of the new geometry
  39815. * @returns the new geometry
  39816. */
  39817. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39818. return _super.prototype.copy.call(this, id);
  39819. };
  39820. // overrides
  39821. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39822. if (!this._beingRegenerated) {
  39823. return;
  39824. }
  39825. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39826. };
  39827. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39828. if (!this._beingRegenerated) {
  39829. return;
  39830. }
  39831. _super.prototype.setVerticesData.call(this, kind, data, false);
  39832. };
  39833. // to override
  39834. /** @hidden */
  39835. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39836. throw new Error("Abstract method");
  39837. };
  39838. _PrimitiveGeometry.prototype.copy = function (id) {
  39839. throw new Error("Must be overriden in sub-classes.");
  39840. };
  39841. _PrimitiveGeometry.prototype.serialize = function () {
  39842. var serializationObject = _super.prototype.serialize.call(this);
  39843. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39844. return serializationObject;
  39845. };
  39846. return _PrimitiveGeometry;
  39847. }(Geometry));
  39848. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39849. /**
  39850. * Creates a ribbon geometry
  39851. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39852. */
  39853. var RibbonGeometry = /** @class */ (function (_super) {
  39854. __extends(RibbonGeometry, _super);
  39855. /**
  39856. * Creates a ribbon geometry
  39857. * @param id defines the unique ID of the geometry
  39858. * @param scene defines the hosting scene
  39859. * @param pathArray defines the array of paths to use
  39860. * @param closeArray defines if the last path and the first path must be joined
  39861. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39862. * @param offset defines the offset between points
  39863. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39864. * @param mesh defines the hosting mesh (can be null)
  39865. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39866. */
  39867. function RibbonGeometry(id, scene,
  39868. /**
  39869. * Defines the array of paths to use
  39870. */
  39871. pathArray,
  39872. /**
  39873. * Defines if the last and first points of each path in your pathArray must be joined
  39874. */
  39875. closeArray,
  39876. /**
  39877. * Defines if the last and first points of each path in your pathArray must be joined
  39878. */
  39879. closePath,
  39880. /**
  39881. * Defines the offset between points
  39882. */
  39883. offset, canBeRegenerated, mesh,
  39884. /**
  39885. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39886. */
  39887. side) {
  39888. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39889. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39890. _this.pathArray = pathArray;
  39891. _this.closeArray = closeArray;
  39892. _this.closePath = closePath;
  39893. _this.offset = offset;
  39894. _this.side = side;
  39895. return _this;
  39896. }
  39897. /** @hidden */
  39898. RibbonGeometry.prototype._regenerateVertexData = function () {
  39899. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39900. };
  39901. RibbonGeometry.prototype.copy = function (id) {
  39902. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39903. };
  39904. return RibbonGeometry;
  39905. }(_PrimitiveGeometry));
  39906. BABYLON.RibbonGeometry = RibbonGeometry;
  39907. /**
  39908. * Creates a box geometry
  39909. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39910. */
  39911. var BoxGeometry = /** @class */ (function (_super) {
  39912. __extends(BoxGeometry, _super);
  39913. /**
  39914. * Creates a box geometry
  39915. * @param id defines the unique ID of the geometry
  39916. * @param scene defines the hosting scene
  39917. * @param size defines the zise of the box (width, height and depth are the same)
  39918. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39919. * @param mesh defines the hosting mesh (can be null)
  39920. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39921. */
  39922. function BoxGeometry(id, scene,
  39923. /**
  39924. * Defines the zise of the box (width, height and depth are the same)
  39925. */
  39926. size, canBeRegenerated, mesh,
  39927. /**
  39928. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39929. */
  39930. side) {
  39931. if (mesh === void 0) { mesh = null; }
  39932. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39933. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39934. _this.size = size;
  39935. _this.side = side;
  39936. return _this;
  39937. }
  39938. /** @hidden */
  39939. BoxGeometry.prototype._regenerateVertexData = function () {
  39940. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39941. };
  39942. BoxGeometry.prototype.copy = function (id) {
  39943. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39944. };
  39945. BoxGeometry.prototype.serialize = function () {
  39946. var serializationObject = _super.prototype.serialize.call(this);
  39947. serializationObject.size = this.size;
  39948. return serializationObject;
  39949. };
  39950. BoxGeometry.Parse = function (parsedBox, scene) {
  39951. if (scene.getGeometryByID(parsedBox.id)) {
  39952. return null; // null since geometry could be something else than a box...
  39953. }
  39954. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39955. if (BABYLON.Tags) {
  39956. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39957. }
  39958. scene.pushGeometry(box, true);
  39959. return box;
  39960. };
  39961. return BoxGeometry;
  39962. }(_PrimitiveGeometry));
  39963. BABYLON.BoxGeometry = BoxGeometry;
  39964. /**
  39965. * Creates a sphere geometry
  39966. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39967. */
  39968. var SphereGeometry = /** @class */ (function (_super) {
  39969. __extends(SphereGeometry, _super);
  39970. /**
  39971. * Create a new sphere geometry
  39972. * @param id defines the unique ID of the geometry
  39973. * @param scene defines the hosting scene
  39974. * @param segments defines the number of segments to use to create the sphere
  39975. * @param diameter defines the diameter of the sphere
  39976. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39977. * @param mesh defines the hosting mesh (can be null)
  39978. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39979. */
  39980. function SphereGeometry(id, scene,
  39981. /**
  39982. * Defines the number of segments to use to create the sphere
  39983. */
  39984. segments,
  39985. /**
  39986. * Defines the diameter of the sphere
  39987. */
  39988. diameter, canBeRegenerated, mesh,
  39989. /**
  39990. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39991. */
  39992. side) {
  39993. if (mesh === void 0) { mesh = null; }
  39994. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39995. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39996. _this.segments = segments;
  39997. _this.diameter = diameter;
  39998. _this.side = side;
  39999. return _this;
  40000. }
  40001. /** @hidden */
  40002. SphereGeometry.prototype._regenerateVertexData = function () {
  40003. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40004. };
  40005. SphereGeometry.prototype.copy = function (id) {
  40006. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40007. };
  40008. SphereGeometry.prototype.serialize = function () {
  40009. var serializationObject = _super.prototype.serialize.call(this);
  40010. serializationObject.segments = this.segments;
  40011. serializationObject.diameter = this.diameter;
  40012. return serializationObject;
  40013. };
  40014. SphereGeometry.Parse = function (parsedSphere, scene) {
  40015. if (scene.getGeometryByID(parsedSphere.id)) {
  40016. return null; // null since geometry could be something else than a sphere...
  40017. }
  40018. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40019. if (BABYLON.Tags) {
  40020. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40021. }
  40022. scene.pushGeometry(sphere, true);
  40023. return sphere;
  40024. };
  40025. return SphereGeometry;
  40026. }(_PrimitiveGeometry));
  40027. BABYLON.SphereGeometry = SphereGeometry;
  40028. /**
  40029. * Creates a disc geometry
  40030. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40031. */
  40032. var DiscGeometry = /** @class */ (function (_super) {
  40033. __extends(DiscGeometry, _super);
  40034. /**
  40035. * Creates a new disc geometry
  40036. * @param id defines the unique ID of the geometry
  40037. * @param scene defines the hosting scene
  40038. * @param radius defines the radius of the disc
  40039. * @param tessellation defines the tesselation factor to apply to the disc
  40040. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40041. * @param mesh defines the hosting mesh (can be null)
  40042. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40043. */
  40044. function DiscGeometry(id, scene,
  40045. /**
  40046. * Defines the radius of the disc
  40047. */
  40048. radius,
  40049. /**
  40050. * Defines the tesselation factor to apply to the disc
  40051. */
  40052. tessellation, canBeRegenerated, mesh,
  40053. /**
  40054. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40055. */
  40056. side) {
  40057. if (mesh === void 0) { mesh = null; }
  40058. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40059. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40060. _this.radius = radius;
  40061. _this.tessellation = tessellation;
  40062. _this.side = side;
  40063. return _this;
  40064. }
  40065. /** @hidden */
  40066. DiscGeometry.prototype._regenerateVertexData = function () {
  40067. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40068. };
  40069. DiscGeometry.prototype.copy = function (id) {
  40070. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40071. };
  40072. return DiscGeometry;
  40073. }(_PrimitiveGeometry));
  40074. BABYLON.DiscGeometry = DiscGeometry;
  40075. /**
  40076. * Creates a new cylinder geometry
  40077. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40078. */
  40079. var CylinderGeometry = /** @class */ (function (_super) {
  40080. __extends(CylinderGeometry, _super);
  40081. /**
  40082. * Creates a new cylinder geometry
  40083. * @param id defines the unique ID of the geometry
  40084. * @param scene defines the hosting scene
  40085. * @param height defines the height of the cylinder
  40086. * @param diameterTop defines the diameter of the cylinder's top cap
  40087. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40088. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40089. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40090. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40091. * @param mesh defines the hosting mesh (can be null)
  40092. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40093. */
  40094. function CylinderGeometry(id, scene,
  40095. /**
  40096. * Defines the height of the cylinder
  40097. */
  40098. height,
  40099. /**
  40100. * Defines the diameter of the cylinder's top cap
  40101. */
  40102. diameterTop,
  40103. /**
  40104. * Defines the diameter of the cylinder's bottom cap
  40105. */
  40106. diameterBottom,
  40107. /**
  40108. * Defines the tessellation factor to apply to the cylinder
  40109. */
  40110. tessellation,
  40111. /**
  40112. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40113. */
  40114. subdivisions, canBeRegenerated, mesh,
  40115. /**
  40116. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40117. */
  40118. side) {
  40119. if (subdivisions === void 0) { subdivisions = 1; }
  40120. if (mesh === void 0) { mesh = null; }
  40121. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40122. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40123. _this.height = height;
  40124. _this.diameterTop = diameterTop;
  40125. _this.diameterBottom = diameterBottom;
  40126. _this.tessellation = tessellation;
  40127. _this.subdivisions = subdivisions;
  40128. _this.side = side;
  40129. return _this;
  40130. }
  40131. /** @hidden */
  40132. CylinderGeometry.prototype._regenerateVertexData = function () {
  40133. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40134. };
  40135. CylinderGeometry.prototype.copy = function (id) {
  40136. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40137. };
  40138. CylinderGeometry.prototype.serialize = function () {
  40139. var serializationObject = _super.prototype.serialize.call(this);
  40140. serializationObject.height = this.height;
  40141. serializationObject.diameterTop = this.diameterTop;
  40142. serializationObject.diameterBottom = this.diameterBottom;
  40143. serializationObject.tessellation = this.tessellation;
  40144. return serializationObject;
  40145. };
  40146. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40147. if (scene.getGeometryByID(parsedCylinder.id)) {
  40148. return null; // null since geometry could be something else than a cylinder...
  40149. }
  40150. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40151. if (BABYLON.Tags) {
  40152. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40153. }
  40154. scene.pushGeometry(cylinder, true);
  40155. return cylinder;
  40156. };
  40157. return CylinderGeometry;
  40158. }(_PrimitiveGeometry));
  40159. BABYLON.CylinderGeometry = CylinderGeometry;
  40160. /**
  40161. * Creates a new torus geometry
  40162. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40163. */
  40164. var TorusGeometry = /** @class */ (function (_super) {
  40165. __extends(TorusGeometry, _super);
  40166. /**
  40167. * Creates a new torus geometry
  40168. * @param id defines the unique ID of the geometry
  40169. * @param scene defines the hosting scene
  40170. * @param diameter defines the diameter of the torus
  40171. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40172. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40173. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40174. * @param mesh defines the hosting mesh (can be null)
  40175. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40176. */
  40177. function TorusGeometry(id, scene,
  40178. /**
  40179. * Defines the diameter of the torus
  40180. */
  40181. diameter,
  40182. /**
  40183. * Defines the thickness of the torus (ie. internal diameter)
  40184. */
  40185. thickness,
  40186. /**
  40187. * Defines the tesselation factor to apply to the torus
  40188. */
  40189. tessellation, canBeRegenerated, mesh,
  40190. /**
  40191. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40192. */
  40193. side) {
  40194. if (mesh === void 0) { mesh = null; }
  40195. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40196. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40197. _this.diameter = diameter;
  40198. _this.thickness = thickness;
  40199. _this.tessellation = tessellation;
  40200. _this.side = side;
  40201. return _this;
  40202. }
  40203. /** @hidden */
  40204. TorusGeometry.prototype._regenerateVertexData = function () {
  40205. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40206. };
  40207. TorusGeometry.prototype.copy = function (id) {
  40208. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40209. };
  40210. TorusGeometry.prototype.serialize = function () {
  40211. var serializationObject = _super.prototype.serialize.call(this);
  40212. serializationObject.diameter = this.diameter;
  40213. serializationObject.thickness = this.thickness;
  40214. serializationObject.tessellation = this.tessellation;
  40215. return serializationObject;
  40216. };
  40217. TorusGeometry.Parse = function (parsedTorus, scene) {
  40218. if (scene.getGeometryByID(parsedTorus.id)) {
  40219. return null; // null since geometry could be something else than a torus...
  40220. }
  40221. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40222. if (BABYLON.Tags) {
  40223. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40224. }
  40225. scene.pushGeometry(torus, true);
  40226. return torus;
  40227. };
  40228. return TorusGeometry;
  40229. }(_PrimitiveGeometry));
  40230. BABYLON.TorusGeometry = TorusGeometry;
  40231. /**
  40232. * Creates a new ground geometry
  40233. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40234. */
  40235. var GroundGeometry = /** @class */ (function (_super) {
  40236. __extends(GroundGeometry, _super);
  40237. /**
  40238. * Creates a new ground geometry
  40239. * @param id defines the unique ID of the geometry
  40240. * @param scene defines the hosting scene
  40241. * @param width defines the width of the ground
  40242. * @param height defines the height of the ground
  40243. * @param subdivisions defines the subdivisions to apply to the ground
  40244. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40245. * @param mesh defines the hosting mesh (can be null)
  40246. */
  40247. function GroundGeometry(id, scene,
  40248. /**
  40249. * Defines the width of the ground
  40250. */
  40251. width,
  40252. /**
  40253. * Defines the height of the ground
  40254. */
  40255. height,
  40256. /**
  40257. * Defines the subdivisions to apply to the ground
  40258. */
  40259. subdivisions, canBeRegenerated, mesh) {
  40260. if (mesh === void 0) { mesh = null; }
  40261. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40262. _this.width = width;
  40263. _this.height = height;
  40264. _this.subdivisions = subdivisions;
  40265. return _this;
  40266. }
  40267. /** @hidden */
  40268. GroundGeometry.prototype._regenerateVertexData = function () {
  40269. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40270. };
  40271. GroundGeometry.prototype.copy = function (id) {
  40272. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40273. };
  40274. GroundGeometry.prototype.serialize = function () {
  40275. var serializationObject = _super.prototype.serialize.call(this);
  40276. serializationObject.width = this.width;
  40277. serializationObject.height = this.height;
  40278. serializationObject.subdivisions = this.subdivisions;
  40279. return serializationObject;
  40280. };
  40281. GroundGeometry.Parse = function (parsedGround, scene) {
  40282. if (scene.getGeometryByID(parsedGround.id)) {
  40283. return null; // null since geometry could be something else than a ground...
  40284. }
  40285. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40286. if (BABYLON.Tags) {
  40287. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40288. }
  40289. scene.pushGeometry(ground, true);
  40290. return ground;
  40291. };
  40292. return GroundGeometry;
  40293. }(_PrimitiveGeometry));
  40294. BABYLON.GroundGeometry = GroundGeometry;
  40295. /**
  40296. * Creates a tiled ground geometry
  40297. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40298. */
  40299. var TiledGroundGeometry = /** @class */ (function (_super) {
  40300. __extends(TiledGroundGeometry, _super);
  40301. /**
  40302. * Creates a tiled ground geometry
  40303. * @param id defines the unique ID of the geometry
  40304. * @param scene defines the hosting scene
  40305. * @param xmin defines the minimum value on X axis
  40306. * @param zmin defines the minimum value on Z axis
  40307. * @param xmax defines the maximum value on X axis
  40308. * @param zmax defines the maximum value on Z axis
  40309. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40310. * @param precision defines the precision to use when computing the tiles
  40311. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40312. * @param mesh defines the hosting mesh (can be null)
  40313. */
  40314. function TiledGroundGeometry(id, scene,
  40315. /**
  40316. * Defines the minimum value on X axis
  40317. */
  40318. xmin,
  40319. /**
  40320. * Defines the minimum value on Z axis
  40321. */
  40322. zmin,
  40323. /**
  40324. * Defines the maximum value on X axis
  40325. */
  40326. xmax,
  40327. /**
  40328. * Defines the maximum value on Z axis
  40329. */
  40330. zmax,
  40331. /**
  40332. * Defines the subdivisions to apply to the ground
  40333. */
  40334. subdivisions,
  40335. /**
  40336. * Defines the precision to use when computing the tiles
  40337. */
  40338. precision, canBeRegenerated, mesh) {
  40339. if (mesh === void 0) { mesh = null; }
  40340. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40341. _this.xmin = xmin;
  40342. _this.zmin = zmin;
  40343. _this.xmax = xmax;
  40344. _this.zmax = zmax;
  40345. _this.subdivisions = subdivisions;
  40346. _this.precision = precision;
  40347. return _this;
  40348. }
  40349. /** @hidden */
  40350. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40351. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40352. };
  40353. TiledGroundGeometry.prototype.copy = function (id) {
  40354. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40355. };
  40356. return TiledGroundGeometry;
  40357. }(_PrimitiveGeometry));
  40358. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40359. /**
  40360. * Creates a plane geometry
  40361. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40362. */
  40363. var PlaneGeometry = /** @class */ (function (_super) {
  40364. __extends(PlaneGeometry, _super);
  40365. /**
  40366. * Creates a plane geometry
  40367. * @param id defines the unique ID of the geometry
  40368. * @param scene defines the hosting scene
  40369. * @param size defines the size of the plane (width === height)
  40370. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40371. * @param mesh defines the hosting mesh (can be null)
  40372. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40373. */
  40374. function PlaneGeometry(id, scene,
  40375. /**
  40376. * Defines the size of the plane (width === height)
  40377. */
  40378. size, canBeRegenerated, mesh,
  40379. /**
  40380. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40381. */
  40382. side) {
  40383. if (mesh === void 0) { mesh = null; }
  40384. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40385. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40386. _this.size = size;
  40387. _this.side = side;
  40388. return _this;
  40389. }
  40390. /** @hidden */
  40391. PlaneGeometry.prototype._regenerateVertexData = function () {
  40392. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40393. };
  40394. PlaneGeometry.prototype.copy = function (id) {
  40395. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40396. };
  40397. PlaneGeometry.prototype.serialize = function () {
  40398. var serializationObject = _super.prototype.serialize.call(this);
  40399. serializationObject.size = this.size;
  40400. return serializationObject;
  40401. };
  40402. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40403. if (scene.getGeometryByID(parsedPlane.id)) {
  40404. return null; // null since geometry could be something else than a ground...
  40405. }
  40406. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40407. if (BABYLON.Tags) {
  40408. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40409. }
  40410. scene.pushGeometry(plane, true);
  40411. return plane;
  40412. };
  40413. return PlaneGeometry;
  40414. }(_PrimitiveGeometry));
  40415. BABYLON.PlaneGeometry = PlaneGeometry;
  40416. /**
  40417. * Creates a torus knot geometry
  40418. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40419. */
  40420. var TorusKnotGeometry = /** @class */ (function (_super) {
  40421. __extends(TorusKnotGeometry, _super);
  40422. /**
  40423. * Creates a torus knot geometry
  40424. * @param id defines the unique ID of the geometry
  40425. * @param scene defines the hosting scene
  40426. * @param radius defines the radius of the torus knot
  40427. * @param tube defines the thickness of the torus knot tube
  40428. * @param radialSegments defines the number of radial segments
  40429. * @param tubularSegments defines the number of tubular segments
  40430. * @param p defines the first number of windings
  40431. * @param q defines the second number of windings
  40432. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40433. * @param mesh defines the hosting mesh (can be null)
  40434. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40435. */
  40436. function TorusKnotGeometry(id, scene,
  40437. /**
  40438. * Defines the radius of the torus knot
  40439. */
  40440. radius,
  40441. /**
  40442. * Defines the thickness of the torus knot tube
  40443. */
  40444. tube,
  40445. /**
  40446. * Defines the number of radial segments
  40447. */
  40448. radialSegments,
  40449. /**
  40450. * Defines the number of tubular segments
  40451. */
  40452. tubularSegments,
  40453. /**
  40454. * Defines the first number of windings
  40455. */
  40456. p,
  40457. /**
  40458. * Defines the second number of windings
  40459. */
  40460. q, canBeRegenerated, mesh,
  40461. /**
  40462. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40463. */
  40464. side) {
  40465. if (mesh === void 0) { mesh = null; }
  40466. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40467. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40468. _this.radius = radius;
  40469. _this.tube = tube;
  40470. _this.radialSegments = radialSegments;
  40471. _this.tubularSegments = tubularSegments;
  40472. _this.p = p;
  40473. _this.q = q;
  40474. _this.side = side;
  40475. return _this;
  40476. }
  40477. /** @hidden */
  40478. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40479. 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 });
  40480. };
  40481. TorusKnotGeometry.prototype.copy = function (id) {
  40482. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40483. };
  40484. TorusKnotGeometry.prototype.serialize = function () {
  40485. var serializationObject = _super.prototype.serialize.call(this);
  40486. serializationObject.radius = this.radius;
  40487. serializationObject.tube = this.tube;
  40488. serializationObject.radialSegments = this.radialSegments;
  40489. serializationObject.tubularSegments = this.tubularSegments;
  40490. serializationObject.p = this.p;
  40491. serializationObject.q = this.q;
  40492. return serializationObject;
  40493. };
  40494. ;
  40495. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40496. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40497. return null; // null since geometry could be something else than a ground...
  40498. }
  40499. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40500. if (BABYLON.Tags) {
  40501. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40502. }
  40503. scene.pushGeometry(torusKnot, true);
  40504. return torusKnot;
  40505. };
  40506. return TorusKnotGeometry;
  40507. }(_PrimitiveGeometry));
  40508. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40509. //}
  40510. })(BABYLON || (BABYLON = {}));
  40511. //# sourceMappingURL=babylon.geometry.js.map
  40512. var BABYLON;
  40513. (function (BABYLON) {
  40514. /**
  40515. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40516. */
  40517. var PerformanceMonitor = /** @class */ (function () {
  40518. /**
  40519. * constructor
  40520. * @param frameSampleSize The number of samples required to saturate the sliding window
  40521. */
  40522. function PerformanceMonitor(frameSampleSize) {
  40523. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40524. this._enabled = true;
  40525. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40526. }
  40527. /**
  40528. * Samples current frame
  40529. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40530. */
  40531. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40532. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40533. if (!this._enabled)
  40534. return;
  40535. if (this._lastFrameTimeMs != null) {
  40536. var dt = timeMs - this._lastFrameTimeMs;
  40537. this._rollingFrameTime.add(dt);
  40538. }
  40539. this._lastFrameTimeMs = timeMs;
  40540. };
  40541. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40542. /**
  40543. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40544. * @return Average frame time in milliseconds
  40545. */
  40546. get: function () {
  40547. return this._rollingFrameTime.average;
  40548. },
  40549. enumerable: true,
  40550. configurable: true
  40551. });
  40552. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40553. /**
  40554. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40555. * @return Frame time variance in milliseconds squared
  40556. */
  40557. get: function () {
  40558. return this._rollingFrameTime.variance;
  40559. },
  40560. enumerable: true,
  40561. configurable: true
  40562. });
  40563. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40564. /**
  40565. * Returns the frame time of the most recent frame
  40566. * @return Frame time in milliseconds
  40567. */
  40568. get: function () {
  40569. return this._rollingFrameTime.history(0);
  40570. },
  40571. enumerable: true,
  40572. configurable: true
  40573. });
  40574. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40575. /**
  40576. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40577. * @return Framerate in frames per second
  40578. */
  40579. get: function () {
  40580. return 1000.0 / this._rollingFrameTime.average;
  40581. },
  40582. enumerable: true,
  40583. configurable: true
  40584. });
  40585. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40586. /**
  40587. * Returns the average framerate in frames per second using the most recent frame time
  40588. * @return Framerate in frames per second
  40589. */
  40590. get: function () {
  40591. var history = this._rollingFrameTime.history(0);
  40592. if (history === 0) {
  40593. return 0;
  40594. }
  40595. return 1000.0 / history;
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40601. /**
  40602. * Returns true if enough samples have been taken to completely fill the sliding window
  40603. * @return true if saturated
  40604. */
  40605. get: function () {
  40606. return this._rollingFrameTime.isSaturated();
  40607. },
  40608. enumerable: true,
  40609. configurable: true
  40610. });
  40611. /**
  40612. * Enables contributions to the sliding window sample set
  40613. */
  40614. PerformanceMonitor.prototype.enable = function () {
  40615. this._enabled = true;
  40616. };
  40617. /**
  40618. * Disables contributions to the sliding window sample set
  40619. * Samples will not be interpolated over the disabled period
  40620. */
  40621. PerformanceMonitor.prototype.disable = function () {
  40622. this._enabled = false;
  40623. //clear last sample to avoid interpolating over the disabled period when next enabled
  40624. this._lastFrameTimeMs = null;
  40625. };
  40626. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40627. /**
  40628. * Returns true if sampling is enabled
  40629. * @return true if enabled
  40630. */
  40631. get: function () {
  40632. return this._enabled;
  40633. },
  40634. enumerable: true,
  40635. configurable: true
  40636. });
  40637. /**
  40638. * Resets performance monitor
  40639. */
  40640. PerformanceMonitor.prototype.reset = function () {
  40641. //clear last sample to avoid interpolating over the disabled period when next enabled
  40642. this._lastFrameTimeMs = null;
  40643. //wipe record
  40644. this._rollingFrameTime.reset();
  40645. };
  40646. return PerformanceMonitor;
  40647. }());
  40648. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40649. /**
  40650. * RollingAverage
  40651. *
  40652. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40653. */
  40654. var RollingAverage = /** @class */ (function () {
  40655. /**
  40656. * constructor
  40657. * @param length The number of samples required to saturate the sliding window
  40658. */
  40659. function RollingAverage(length) {
  40660. this._samples = new Array(length);
  40661. this.reset();
  40662. }
  40663. /**
  40664. * Adds a sample to the sample set
  40665. * @param v The sample value
  40666. */
  40667. RollingAverage.prototype.add = function (v) {
  40668. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40669. var delta;
  40670. //we need to check if we've already wrapped round
  40671. if (this.isSaturated()) {
  40672. //remove bottom of stack from mean
  40673. var bottomValue = this._samples[this._pos];
  40674. delta = bottomValue - this.average;
  40675. this.average -= delta / (this._sampleCount - 1);
  40676. this._m2 -= delta * (bottomValue - this.average);
  40677. }
  40678. else {
  40679. this._sampleCount++;
  40680. }
  40681. //add new value to mean
  40682. delta = v - this.average;
  40683. this.average += delta / (this._sampleCount);
  40684. this._m2 += delta * (v - this.average);
  40685. //set the new variance
  40686. this.variance = this._m2 / (this._sampleCount - 1);
  40687. this._samples[this._pos] = v;
  40688. this._pos++;
  40689. this._pos %= this._samples.length; //positive wrap around
  40690. };
  40691. /**
  40692. * Returns previously added values or null if outside of history or outside the sliding window domain
  40693. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40694. * @return Value previously recorded with add() or null if outside of range
  40695. */
  40696. RollingAverage.prototype.history = function (i) {
  40697. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40698. return 0;
  40699. }
  40700. var i0 = this._wrapPosition(this._pos - 1.0);
  40701. return this._samples[this._wrapPosition(i0 - i)];
  40702. };
  40703. /**
  40704. * Returns true if enough samples have been taken to completely fill the sliding window
  40705. * @return true if sample-set saturated
  40706. */
  40707. RollingAverage.prototype.isSaturated = function () {
  40708. return this._sampleCount >= this._samples.length;
  40709. };
  40710. /**
  40711. * Resets the rolling average (equivalent to 0 samples taken so far)
  40712. */
  40713. RollingAverage.prototype.reset = function () {
  40714. this.average = 0;
  40715. this.variance = 0;
  40716. this._sampleCount = 0;
  40717. this._pos = 0;
  40718. this._m2 = 0;
  40719. };
  40720. /**
  40721. * Wraps a value around the sample range boundaries
  40722. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40723. * @return Wrapped position in sample range
  40724. */
  40725. RollingAverage.prototype._wrapPosition = function (i) {
  40726. var max = this._samples.length;
  40727. return ((i % max) + max) % max;
  40728. };
  40729. return RollingAverage;
  40730. }());
  40731. BABYLON.RollingAverage = RollingAverage;
  40732. })(BABYLON || (BABYLON = {}));
  40733. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40734. var BABYLON;
  40735. (function (BABYLON) {
  40736. /**
  40737. * "Static Class" containing the most commonly used helper while dealing with material for
  40738. * rendering purpose.
  40739. *
  40740. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  40741. *
  40742. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  40743. */
  40744. var MaterialHelper = /** @class */ (function () {
  40745. function MaterialHelper() {
  40746. }
  40747. /**
  40748. * Bind the current view position to an effect.
  40749. * @param effect The effect to be bound
  40750. * @param scene The scene the eyes position is used from
  40751. */
  40752. MaterialHelper.BindEyePosition = function (effect, scene) {
  40753. if (scene._forcedViewPosition) {
  40754. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  40755. return;
  40756. }
  40757. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  40758. };
  40759. /**
  40760. * Helps preparing the defines values about the UVs in used in the effect.
  40761. * UVs are shared as much as we can accross chanels in the shaders.
  40762. * @param texture The texture we are preparing the UVs for
  40763. * @param defines The defines to update
  40764. * @param key The chanel key "diffuse", "specular"... used in the shader
  40765. */
  40766. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  40767. defines._needUVs = true;
  40768. defines[key] = true;
  40769. if (texture.getTextureMatrix().isIdentity(true)) {
  40770. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  40771. if (texture.coordinatesIndex === 0) {
  40772. defines["MAINUV1"] = true;
  40773. }
  40774. else {
  40775. defines["MAINUV2"] = true;
  40776. }
  40777. }
  40778. else {
  40779. defines[key + "DIRECTUV"] = 0;
  40780. }
  40781. };
  40782. /**
  40783. * Binds a texture matrix value to its corrsponding uniform
  40784. * @param texture The texture to bind the matrix for
  40785. * @param uniformBuffer The uniform buffer receivin the data
  40786. * @param key The chanel key "diffuse", "specular"... used in the shader
  40787. */
  40788. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  40789. var matrix = texture.getTextureMatrix();
  40790. if (!matrix.isIdentity(true)) {
  40791. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  40792. }
  40793. };
  40794. /**
  40795. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  40796. * @param mesh defines the current mesh
  40797. * @param scene defines the current scene
  40798. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  40799. * @param pointsCloud defines if point cloud rendering has to be turned on
  40800. * @param fogEnabled defines if fog has to be turned on
  40801. * @param alphaTest defines if alpha testing has to be turned on
  40802. * @param defines defines the current list of defines
  40803. */
  40804. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  40805. if (defines._areMiscDirty) {
  40806. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  40807. defines["POINTSIZE"] = pointsCloud;
  40808. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  40809. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  40810. defines["ALPHATEST"] = alphaTest;
  40811. }
  40812. };
  40813. /**
  40814. * Helper used to prepare the list of defines associated with frame values for shader compilation
  40815. * @param scene defines the current scene
  40816. * @param engine defines the current engine
  40817. * @param defines specifies the list of active defines
  40818. * @param useInstances defines if instances have to be turned on
  40819. * @param useClipPlane defines if clip plane have to be turned on
  40820. */
  40821. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  40822. if (useClipPlane === void 0) { useClipPlane = null; }
  40823. var changed = false;
  40824. var useClipPlane1 = false;
  40825. var useClipPlane2 = false;
  40826. var useClipPlane3 = false;
  40827. var useClipPlane4 = false;
  40828. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  40829. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  40830. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  40831. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  40832. if (defines["CLIPPLANE"] !== useClipPlane1) {
  40833. defines["CLIPPLANE"] = useClipPlane1;
  40834. changed = true;
  40835. }
  40836. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  40837. defines["CLIPPLANE2"] = useClipPlane2;
  40838. changed = true;
  40839. }
  40840. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  40841. defines["CLIPPLANE3"] = useClipPlane3;
  40842. changed = true;
  40843. }
  40844. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  40845. defines["CLIPPLANE4"] = useClipPlane4;
  40846. changed = true;
  40847. }
  40848. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  40849. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  40850. changed = true;
  40851. }
  40852. if (defines["INSTANCES"] !== useInstances) {
  40853. defines["INSTANCES"] = useInstances;
  40854. changed = true;
  40855. }
  40856. if (changed) {
  40857. defines.markAsUnprocessed();
  40858. }
  40859. };
  40860. /**
  40861. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  40862. * @param mesh The mesh containing the geometry data we will draw
  40863. * @param defines The defines to update
  40864. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  40865. * @param useBones Precise whether bones should be used or not (override mesh info)
  40866. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  40867. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  40868. * @returns false if defines are considered not dirty and have not been checked
  40869. */
  40870. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  40871. if (useMorphTargets === void 0) { useMorphTargets = false; }
  40872. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  40873. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  40874. return false;
  40875. }
  40876. defines._normals = defines._needNormals;
  40877. defines._uvs = defines._needUVs;
  40878. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  40879. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40880. defines["TANGENT"] = true;
  40881. }
  40882. if (defines._needUVs) {
  40883. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  40884. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  40885. }
  40886. else {
  40887. defines["UV1"] = false;
  40888. defines["UV2"] = false;
  40889. }
  40890. if (useVertexColor) {
  40891. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  40892. defines["VERTEXCOLOR"] = hasVertexColors;
  40893. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  40894. }
  40895. if (useBones) {
  40896. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40897. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  40898. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  40899. }
  40900. else {
  40901. defines["NUM_BONE_INFLUENCERS"] = 0;
  40902. defines["BonesPerMesh"] = 0;
  40903. }
  40904. }
  40905. if (useMorphTargets) {
  40906. var manager = mesh.morphTargetManager;
  40907. if (manager) {
  40908. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  40909. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  40910. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  40911. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  40912. }
  40913. else {
  40914. defines["MORPHTARGETS_TANGENT"] = false;
  40915. defines["MORPHTARGETS_NORMAL"] = false;
  40916. defines["MORPHTARGETS"] = false;
  40917. defines["NUM_MORPH_INFLUENCERS"] = 0;
  40918. }
  40919. }
  40920. return true;
  40921. };
  40922. /**
  40923. * Prepares the defines related to the light information passed in parameter
  40924. * @param scene The scene we are intending to draw
  40925. * @param mesh The mesh the effect is compiling for
  40926. * @param defines The defines to update
  40927. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  40928. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  40929. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  40930. * @returns true if normals will be required for the rest of the effect
  40931. */
  40932. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  40933. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  40934. if (disableLighting === void 0) { disableLighting = false; }
  40935. if (!defines._areLightsDirty) {
  40936. return defines._needNormals;
  40937. }
  40938. var lightIndex = 0;
  40939. var needNormals = false;
  40940. var needRebuild = false;
  40941. var lightmapMode = false;
  40942. var shadowEnabled = false;
  40943. var specularEnabled = false;
  40944. if (scene.lightsEnabled && !disableLighting) {
  40945. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  40946. var light = _a[_i];
  40947. needNormals = true;
  40948. if (defines["LIGHT" + lightIndex] === undefined) {
  40949. needRebuild = true;
  40950. }
  40951. defines["LIGHT" + lightIndex] = true;
  40952. defines["SPOTLIGHT" + lightIndex] = false;
  40953. defines["HEMILIGHT" + lightIndex] = false;
  40954. defines["POINTLIGHT" + lightIndex] = false;
  40955. defines["DIRLIGHT" + lightIndex] = false;
  40956. light.prepareLightSpecificDefines(defines, lightIndex);
  40957. // FallOff.
  40958. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  40959. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  40960. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  40961. switch (light.falloffType) {
  40962. case BABYLON.Light.FALLOFF_GLTF:
  40963. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  40964. break;
  40965. case BABYLON.Light.FALLOFF_PHYSICAL:
  40966. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  40967. break;
  40968. case BABYLON.Light.FALLOFF_STANDARD:
  40969. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  40970. break;
  40971. }
  40972. // Specular
  40973. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  40974. specularEnabled = true;
  40975. }
  40976. // Shadows
  40977. defines["SHADOW" + lightIndex] = false;
  40978. defines["SHADOWPCF" + lightIndex] = false;
  40979. defines["SHADOWPCSS" + lightIndex] = false;
  40980. defines["SHADOWPOISSON" + lightIndex] = false;
  40981. defines["SHADOWESM" + lightIndex] = false;
  40982. defines["SHADOWCUBE" + lightIndex] = false;
  40983. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  40984. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  40985. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  40986. var shadowGenerator = light.getShadowGenerator();
  40987. if (shadowGenerator) {
  40988. var shadowMap = shadowGenerator.getShadowMap();
  40989. if (shadowMap) {
  40990. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  40991. shadowEnabled = true;
  40992. shadowGenerator.prepareDefines(defines, lightIndex);
  40993. }
  40994. }
  40995. }
  40996. }
  40997. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  40998. lightmapMode = true;
  40999. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41000. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41001. }
  41002. else {
  41003. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41004. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41005. }
  41006. lightIndex++;
  41007. if (lightIndex === maxSimultaneousLights)
  41008. break;
  41009. }
  41010. }
  41011. defines["SPECULARTERM"] = specularEnabled;
  41012. defines["SHADOWS"] = shadowEnabled;
  41013. // Resetting all other lights if any
  41014. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41015. if (defines["LIGHT" + index] !== undefined) {
  41016. defines["LIGHT" + index] = false;
  41017. defines["HEMILIGHT" + lightIndex] = false;
  41018. defines["POINTLIGHT" + lightIndex] = false;
  41019. defines["DIRLIGHT" + lightIndex] = false;
  41020. defines["SPOTLIGHT" + lightIndex] = false;
  41021. defines["SHADOW" + lightIndex] = false;
  41022. }
  41023. }
  41024. var caps = scene.getEngine().getCaps();
  41025. if (defines["SHADOWFLOAT"] === undefined) {
  41026. needRebuild = true;
  41027. }
  41028. defines["SHADOWFLOAT"] = shadowEnabled &&
  41029. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41030. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41031. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41032. if (needRebuild) {
  41033. defines.rebuild();
  41034. }
  41035. return needNormals;
  41036. };
  41037. /**
  41038. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41039. * that won t be acctive due to defines being turned off.
  41040. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41041. * @param samplersList The samplers list
  41042. * @param defines The defines helping in the list generation
  41043. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41044. */
  41045. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41046. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41047. var uniformsList;
  41048. var uniformBuffersList = null;
  41049. if (uniformsListOrOptions.uniformsNames) {
  41050. var options = uniformsListOrOptions;
  41051. uniformsList = options.uniformsNames;
  41052. uniformBuffersList = options.uniformBuffersNames;
  41053. samplersList = options.samplers;
  41054. defines = options.defines;
  41055. maxSimultaneousLights = options.maxSimultaneousLights;
  41056. }
  41057. else {
  41058. uniformsList = uniformsListOrOptions;
  41059. if (!samplersList) {
  41060. samplersList = [];
  41061. }
  41062. }
  41063. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41064. if (!defines["LIGHT" + lightIndex]) {
  41065. break;
  41066. }
  41067. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41068. if (uniformBuffersList) {
  41069. uniformBuffersList.push("Light" + lightIndex);
  41070. }
  41071. samplersList.push("shadowSampler" + lightIndex);
  41072. samplersList.push("depthSampler" + lightIndex);
  41073. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41074. samplersList.push("projectionLightSampler" + lightIndex);
  41075. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41076. }
  41077. }
  41078. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41079. uniformsList.push("morphTargetInfluences");
  41080. }
  41081. };
  41082. /**
  41083. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41084. * @param defines The defines to update while falling back
  41085. * @param fallbacks The authorized effect fallbacks
  41086. * @param maxSimultaneousLights The maximum number of lights allowed
  41087. * @param rank the current rank of the Effect
  41088. * @returns The newly affected rank
  41089. */
  41090. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41091. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41092. if (rank === void 0) { rank = 0; }
  41093. var lightFallbackRank = 0;
  41094. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41095. if (!defines["LIGHT" + lightIndex]) {
  41096. break;
  41097. }
  41098. if (lightIndex > 0) {
  41099. lightFallbackRank = rank + lightIndex;
  41100. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41101. }
  41102. if (!defines["SHADOWS"]) {
  41103. if (defines["SHADOW" + lightIndex]) {
  41104. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41105. }
  41106. if (defines["SHADOWPCF" + lightIndex]) {
  41107. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41108. }
  41109. if (defines["SHADOWPCSS" + lightIndex]) {
  41110. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41111. }
  41112. if (defines["SHADOWPOISSON" + lightIndex]) {
  41113. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41114. }
  41115. if (defines["SHADOWESM" + lightIndex]) {
  41116. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41117. }
  41118. }
  41119. }
  41120. return lightFallbackRank++;
  41121. };
  41122. /**
  41123. * Prepares the list of attributes required for morph targets according to the effect defines.
  41124. * @param attribs The current list of supported attribs
  41125. * @param mesh The mesh to prepare the morph targets attributes for
  41126. * @param defines The current Defines of the effect
  41127. */
  41128. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41129. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41130. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41131. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41132. var manager = mesh.morphTargetManager;
  41133. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41134. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41135. for (var index = 0; index < influencers; index++) {
  41136. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41137. if (normal) {
  41138. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41139. }
  41140. if (tangent) {
  41141. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41142. }
  41143. if (attribs.length > maxAttributesCount) {
  41144. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41145. }
  41146. }
  41147. }
  41148. };
  41149. /**
  41150. * Prepares the list of attributes required for bones according to the effect defines.
  41151. * @param attribs The current list of supported attribs
  41152. * @param mesh The mesh to prepare the bones attributes for
  41153. * @param defines The current Defines of the effect
  41154. * @param fallbacks The current efffect fallback strategy
  41155. */
  41156. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41157. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41158. fallbacks.addCPUSkinningFallback(0, mesh);
  41159. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41160. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41161. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41162. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41163. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41164. }
  41165. }
  41166. };
  41167. /**
  41168. * Prepares the list of attributes required for instances according to the effect defines.
  41169. * @param attribs The current list of supported attribs
  41170. * @param defines The current Defines of the effect
  41171. */
  41172. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41173. if (defines["INSTANCES"]) {
  41174. attribs.push("world0");
  41175. attribs.push("world1");
  41176. attribs.push("world2");
  41177. attribs.push("world3");
  41178. }
  41179. };
  41180. /**
  41181. * Binds the light shadow information to the effect for the given mesh.
  41182. * @param light The light containing the generator
  41183. * @param scene The scene the lights belongs to
  41184. * @param mesh The mesh we are binding the information to render
  41185. * @param lightIndex The light index in the effect used to render the mesh
  41186. * @param effect The effect we are binding the data to
  41187. */
  41188. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41189. if (light.shadowEnabled && mesh.receiveShadows) {
  41190. var shadowGenerator = light.getShadowGenerator();
  41191. if (shadowGenerator) {
  41192. shadowGenerator.bindShadowLight(lightIndex, effect);
  41193. }
  41194. }
  41195. };
  41196. /**
  41197. * Binds the light information to the effect.
  41198. * @param light The light containing the generator
  41199. * @param effect The effect we are binding the data to
  41200. * @param lightIndex The light index in the effect used to render
  41201. */
  41202. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41203. light.transferToEffect(effect, lightIndex + "");
  41204. };
  41205. /**
  41206. * Binds the lights information from the scene to the effect for the given mesh.
  41207. * @param scene The scene the lights belongs to
  41208. * @param mesh The mesh we are binding the information to render
  41209. * @param effect The effect we are binding the data to
  41210. * @param defines The generated defines for the effect
  41211. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41212. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41213. */
  41214. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41215. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41216. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41217. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41218. for (var i = 0; i < len; i++) {
  41219. var light = mesh._lightSources[i];
  41220. var iAsString = i.toString();
  41221. var scaledIntensity = light.getScaledIntensity();
  41222. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41223. MaterialHelper.BindLightProperties(light, effect, i);
  41224. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41225. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41226. if (defines["SPECULARTERM"]) {
  41227. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41228. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41229. }
  41230. // Shadows
  41231. if (scene.shadowsEnabled) {
  41232. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41233. }
  41234. light._uniformBuffer.update();
  41235. }
  41236. };
  41237. /**
  41238. * Binds the fog information from the scene to the effect for the given mesh.
  41239. * @param scene The scene the lights belongs to
  41240. * @param mesh The mesh we are binding the information to render
  41241. * @param effect The effect we are binding the data to
  41242. */
  41243. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41244. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41245. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41246. effect.setColor3("vFogColor", scene.fogColor);
  41247. }
  41248. };
  41249. /**
  41250. * Binds the bones information from the mesh to the effect.
  41251. * @param mesh The mesh we are binding the information to render
  41252. * @param effect The effect we are binding the data to
  41253. */
  41254. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41255. if (!effect || !mesh) {
  41256. return;
  41257. }
  41258. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41259. mesh.computeBonesUsingShaders = false;
  41260. }
  41261. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41262. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41263. if (matrices) {
  41264. effect.setMatrices("mBones", matrices);
  41265. }
  41266. }
  41267. };
  41268. /**
  41269. * Binds the morph targets information from the mesh to the effect.
  41270. * @param abstractMesh The mesh we are binding the information to render
  41271. * @param effect The effect we are binding the data to
  41272. */
  41273. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41274. var manager = abstractMesh.morphTargetManager;
  41275. if (!abstractMesh || !manager) {
  41276. return;
  41277. }
  41278. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41279. };
  41280. /**
  41281. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41282. * @param defines The generated defines used in the effect
  41283. * @param effect The effect we are binding the data to
  41284. * @param scene The scene we are willing to render with logarithmic scale for
  41285. */
  41286. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41287. if (defines["LOGARITHMICDEPTH"]) {
  41288. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41289. }
  41290. };
  41291. /**
  41292. * Binds the clip plane information from the scene to the effect.
  41293. * @param scene The scene the clip plane information are extracted from
  41294. * @param effect The effect we are binding the data to
  41295. */
  41296. MaterialHelper.BindClipPlane = function (effect, scene) {
  41297. if (scene.clipPlane) {
  41298. var clipPlane = scene.clipPlane;
  41299. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41300. }
  41301. if (scene.clipPlane2) {
  41302. var clipPlane = scene.clipPlane2;
  41303. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41304. }
  41305. if (scene.clipPlane3) {
  41306. var clipPlane = scene.clipPlane3;
  41307. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41308. }
  41309. if (scene.clipPlane4) {
  41310. var clipPlane = scene.clipPlane4;
  41311. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41312. }
  41313. };
  41314. return MaterialHelper;
  41315. }());
  41316. BABYLON.MaterialHelper = MaterialHelper;
  41317. })(BABYLON || (BABYLON = {}));
  41318. //# sourceMappingURL=babylon.materialHelper.js.map
  41319. var BABYLON;
  41320. (function (BABYLON) {
  41321. var PushMaterial = /** @class */ (function (_super) {
  41322. __extends(PushMaterial, _super);
  41323. function PushMaterial(name, scene) {
  41324. var _this = _super.call(this, name, scene) || this;
  41325. _this._normalMatrix = new BABYLON.Matrix();
  41326. _this.storeEffectOnSubMeshes = true;
  41327. return _this;
  41328. }
  41329. PushMaterial.prototype.getEffect = function () {
  41330. return this._activeEffect;
  41331. };
  41332. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41333. if (!mesh) {
  41334. return false;
  41335. }
  41336. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41337. return true;
  41338. }
  41339. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41340. };
  41341. /**
  41342. * Binds the given world matrix to the active effect
  41343. *
  41344. * @param world the matrix to bind
  41345. */
  41346. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41347. this._activeEffect.setMatrix("world", world);
  41348. };
  41349. /**
  41350. * Binds the given normal matrix to the active effect
  41351. *
  41352. * @param normalMatrix the matrix to bind
  41353. */
  41354. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41355. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41356. };
  41357. PushMaterial.prototype.bind = function (world, mesh) {
  41358. if (!mesh) {
  41359. return;
  41360. }
  41361. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41362. };
  41363. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41364. if (effect === void 0) { effect = null; }
  41365. _super.prototype._afterBind.call(this, mesh);
  41366. this.getScene()._cachedEffect = effect;
  41367. };
  41368. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41369. if (visibility === void 0) { visibility = 1; }
  41370. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41371. };
  41372. return PushMaterial;
  41373. }(BABYLON.Material));
  41374. BABYLON.PushMaterial = PushMaterial;
  41375. })(BABYLON || (BABYLON = {}));
  41376. //# sourceMappingURL=babylon.pushMaterial.js.map
  41377. var BABYLON;
  41378. (function (BABYLON) {
  41379. /** @hidden */
  41380. var StandardMaterialDefines = /** @class */ (function (_super) {
  41381. __extends(StandardMaterialDefines, _super);
  41382. function StandardMaterialDefines() {
  41383. var _this = _super.call(this) || this;
  41384. _this.MAINUV1 = false;
  41385. _this.MAINUV2 = false;
  41386. _this.DIFFUSE = false;
  41387. _this.DIFFUSEDIRECTUV = 0;
  41388. _this.AMBIENT = false;
  41389. _this.AMBIENTDIRECTUV = 0;
  41390. _this.OPACITY = false;
  41391. _this.OPACITYDIRECTUV = 0;
  41392. _this.OPACITYRGB = false;
  41393. _this.REFLECTION = false;
  41394. _this.EMISSIVE = false;
  41395. _this.EMISSIVEDIRECTUV = 0;
  41396. _this.SPECULAR = false;
  41397. _this.SPECULARDIRECTUV = 0;
  41398. _this.BUMP = false;
  41399. _this.BUMPDIRECTUV = 0;
  41400. _this.PARALLAX = false;
  41401. _this.PARALLAXOCCLUSION = false;
  41402. _this.SPECULAROVERALPHA = false;
  41403. _this.CLIPPLANE = false;
  41404. _this.CLIPPLANE2 = false;
  41405. _this.CLIPPLANE3 = false;
  41406. _this.CLIPPLANE4 = false;
  41407. _this.ALPHATEST = false;
  41408. _this.DEPTHPREPASS = false;
  41409. _this.ALPHAFROMDIFFUSE = false;
  41410. _this.POINTSIZE = false;
  41411. _this.FOG = false;
  41412. _this.SPECULARTERM = false;
  41413. _this.DIFFUSEFRESNEL = false;
  41414. _this.OPACITYFRESNEL = false;
  41415. _this.REFLECTIONFRESNEL = false;
  41416. _this.REFRACTIONFRESNEL = false;
  41417. _this.EMISSIVEFRESNEL = false;
  41418. _this.FRESNEL = false;
  41419. _this.NORMAL = false;
  41420. _this.UV1 = false;
  41421. _this.UV2 = false;
  41422. _this.VERTEXCOLOR = false;
  41423. _this.VERTEXALPHA = false;
  41424. _this.NUM_BONE_INFLUENCERS = 0;
  41425. _this.BonesPerMesh = 0;
  41426. _this.INSTANCES = false;
  41427. _this.GLOSSINESS = false;
  41428. _this.ROUGHNESS = false;
  41429. _this.EMISSIVEASILLUMINATION = false;
  41430. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41431. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41432. _this.LIGHTMAP = false;
  41433. _this.LIGHTMAPDIRECTUV = 0;
  41434. _this.OBJECTSPACE_NORMALMAP = false;
  41435. _this.USELIGHTMAPASSHADOWMAP = false;
  41436. _this.REFLECTIONMAP_3D = false;
  41437. _this.REFLECTIONMAP_SPHERICAL = false;
  41438. _this.REFLECTIONMAP_PLANAR = false;
  41439. _this.REFLECTIONMAP_CUBIC = false;
  41440. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41441. _this.REFLECTIONMAP_PROJECTION = false;
  41442. _this.REFLECTIONMAP_SKYBOX = false;
  41443. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  41444. _this.REFLECTIONMAP_EXPLICIT = false;
  41445. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41446. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41447. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41448. _this.INVERTCUBICMAP = false;
  41449. _this.LOGARITHMICDEPTH = false;
  41450. _this.REFRACTION = false;
  41451. _this.REFRACTIONMAP_3D = false;
  41452. _this.REFLECTIONOVERALPHA = false;
  41453. _this.TWOSIDEDLIGHTING = false;
  41454. _this.SHADOWFLOAT = false;
  41455. _this.MORPHTARGETS = false;
  41456. _this.MORPHTARGETS_NORMAL = false;
  41457. _this.MORPHTARGETS_TANGENT = false;
  41458. _this.NUM_MORPH_INFLUENCERS = 0;
  41459. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41460. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41461. _this.IMAGEPROCESSING = false;
  41462. _this.VIGNETTE = false;
  41463. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41464. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41465. _this.TONEMAPPING = false;
  41466. _this.TONEMAPPING_ACES = false;
  41467. _this.CONTRAST = false;
  41468. _this.COLORCURVES = false;
  41469. _this.COLORGRADING = false;
  41470. _this.COLORGRADING3D = false;
  41471. _this.SAMPLER3DGREENDEPTH = false;
  41472. _this.SAMPLER3DBGRMAP = false;
  41473. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41474. /**
  41475. * If the reflection texture on this material is in linear color space
  41476. * @hidden
  41477. */
  41478. _this.IS_REFLECTION_LINEAR = false;
  41479. /**
  41480. * If the refraction texture on this material is in linear color space
  41481. * @hidden
  41482. */
  41483. _this.IS_REFRACTION_LINEAR = false;
  41484. _this.EXPOSURE = false;
  41485. _this.rebuild();
  41486. return _this;
  41487. }
  41488. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41489. var modes = [
  41490. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41491. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41492. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41493. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41494. ];
  41495. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41496. var mode = modes_1[_i];
  41497. this[mode] = (mode === modeToEnable);
  41498. }
  41499. };
  41500. return StandardMaterialDefines;
  41501. }(BABYLON.MaterialDefines));
  41502. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41503. var StandardMaterial = /** @class */ (function (_super) {
  41504. __extends(StandardMaterial, _super);
  41505. function StandardMaterial(name, scene) {
  41506. var _this = _super.call(this, name, scene) || this;
  41507. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41508. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41509. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41510. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41511. _this.specularPower = 64;
  41512. _this._useAlphaFromDiffuseTexture = false;
  41513. _this._useEmissiveAsIllumination = false;
  41514. _this._linkEmissiveWithDiffuse = false;
  41515. _this._useSpecularOverAlpha = false;
  41516. _this._useReflectionOverAlpha = false;
  41517. _this._disableLighting = false;
  41518. _this._useObjectSpaceNormalMap = false;
  41519. _this._useParallax = false;
  41520. _this._useParallaxOcclusion = false;
  41521. _this.parallaxScaleBias = 0.05;
  41522. _this._roughness = 0;
  41523. _this.indexOfRefraction = 0.98;
  41524. _this.invertRefractionY = true;
  41525. /**
  41526. * Defines the alpha limits in alpha test mode
  41527. */
  41528. _this.alphaCutOff = 0.4;
  41529. _this._useLightmapAsShadowmap = false;
  41530. _this._useReflectionFresnelFromSpecular = false;
  41531. _this._useGlossinessFromSpecularMapAlpha = false;
  41532. _this._maxSimultaneousLights = 4;
  41533. /**
  41534. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41535. */
  41536. _this._invertNormalMapX = false;
  41537. /**
  41538. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41539. */
  41540. _this._invertNormalMapY = false;
  41541. /**
  41542. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41543. */
  41544. _this._twoSidedLighting = false;
  41545. _this._renderTargets = new BABYLON.SmartArray(16);
  41546. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41547. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41548. // Setup the default processing configuration to the scene.
  41549. _this._attachImageProcessingConfiguration(null);
  41550. _this.getRenderTargetTextures = function () {
  41551. _this._renderTargets.reset();
  41552. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41553. _this._renderTargets.push(_this._reflectionTexture);
  41554. }
  41555. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41556. _this._renderTargets.push(_this._refractionTexture);
  41557. }
  41558. return _this._renderTargets;
  41559. };
  41560. return _this;
  41561. }
  41562. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41563. /**
  41564. * Gets the image processing configuration used either in this material.
  41565. */
  41566. get: function () {
  41567. return this._imageProcessingConfiguration;
  41568. },
  41569. /**
  41570. * Sets the Default image processing configuration used either in the this material.
  41571. *
  41572. * If sets to null, the scene one is in use.
  41573. */
  41574. set: function (value) {
  41575. this._attachImageProcessingConfiguration(value);
  41576. // Ensure the effect will be rebuilt.
  41577. this._markAllSubMeshesAsTexturesDirty();
  41578. },
  41579. enumerable: true,
  41580. configurable: true
  41581. });
  41582. /**
  41583. * Attaches a new image processing configuration to the Standard Material.
  41584. * @param configuration
  41585. */
  41586. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41587. var _this = this;
  41588. if (configuration === this._imageProcessingConfiguration) {
  41589. return;
  41590. }
  41591. // Detaches observer.
  41592. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41593. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41594. }
  41595. // Pick the scene configuration if needed.
  41596. if (!configuration) {
  41597. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41598. }
  41599. else {
  41600. this._imageProcessingConfiguration = configuration;
  41601. }
  41602. // Attaches observer.
  41603. if (this._imageProcessingConfiguration) {
  41604. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41605. _this._markAllSubMeshesAsImageProcessingDirty();
  41606. });
  41607. }
  41608. };
  41609. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41610. /**
  41611. * Gets wether the color curves effect is enabled.
  41612. */
  41613. get: function () {
  41614. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41615. },
  41616. /**
  41617. * Sets wether the color curves effect is enabled.
  41618. */
  41619. set: function (value) {
  41620. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41621. },
  41622. enumerable: true,
  41623. configurable: true
  41624. });
  41625. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41626. /**
  41627. * Gets wether the color grading effect is enabled.
  41628. */
  41629. get: function () {
  41630. return this.imageProcessingConfiguration.colorGradingEnabled;
  41631. },
  41632. /**
  41633. * Gets wether the color grading effect is enabled.
  41634. */
  41635. set: function (value) {
  41636. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41637. },
  41638. enumerable: true,
  41639. configurable: true
  41640. });
  41641. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41642. /**
  41643. * Gets wether tonemapping is enabled or not.
  41644. */
  41645. get: function () {
  41646. return this._imageProcessingConfiguration.toneMappingEnabled;
  41647. },
  41648. /**
  41649. * Sets wether tonemapping is enabled or not
  41650. */
  41651. set: function (value) {
  41652. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41653. },
  41654. enumerable: true,
  41655. configurable: true
  41656. });
  41657. ;
  41658. ;
  41659. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41660. /**
  41661. * The camera exposure used on this material.
  41662. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41663. * This corresponds to a photographic exposure.
  41664. */
  41665. get: function () {
  41666. return this._imageProcessingConfiguration.exposure;
  41667. },
  41668. /**
  41669. * The camera exposure used on this material.
  41670. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41671. * This corresponds to a photographic exposure.
  41672. */
  41673. set: function (value) {
  41674. this._imageProcessingConfiguration.exposure = value;
  41675. },
  41676. enumerable: true,
  41677. configurable: true
  41678. });
  41679. ;
  41680. ;
  41681. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41682. /**
  41683. * Gets The camera contrast used on this material.
  41684. */
  41685. get: function () {
  41686. return this._imageProcessingConfiguration.contrast;
  41687. },
  41688. /**
  41689. * Sets The camera contrast used on this material.
  41690. */
  41691. set: function (value) {
  41692. this._imageProcessingConfiguration.contrast = value;
  41693. },
  41694. enumerable: true,
  41695. configurable: true
  41696. });
  41697. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41698. /**
  41699. * Gets the Color Grading 2D Lookup Texture.
  41700. */
  41701. get: function () {
  41702. return this._imageProcessingConfiguration.colorGradingTexture;
  41703. },
  41704. /**
  41705. * Sets the Color Grading 2D Lookup Texture.
  41706. */
  41707. set: function (value) {
  41708. this._imageProcessingConfiguration.colorGradingTexture = value;
  41709. },
  41710. enumerable: true,
  41711. configurable: true
  41712. });
  41713. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  41714. /**
  41715. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41716. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41717. * 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;
  41718. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41719. */
  41720. get: function () {
  41721. return this._imageProcessingConfiguration.colorCurves;
  41722. },
  41723. /**
  41724. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41725. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41726. * 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;
  41727. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41728. */
  41729. set: function (value) {
  41730. this._imageProcessingConfiguration.colorCurves = value;
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  41736. /**
  41737. * Gets a boolean indicating that current material needs to register RTT
  41738. */
  41739. get: function () {
  41740. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41741. return true;
  41742. }
  41743. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41744. return true;
  41745. }
  41746. return false;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. StandardMaterial.prototype.getClassName = function () {
  41752. return "StandardMaterial";
  41753. };
  41754. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41755. get: function () {
  41756. return this._useLogarithmicDepth;
  41757. },
  41758. set: function (value) {
  41759. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41760. this._markAllSubMeshesAsMiscDirty();
  41761. },
  41762. enumerable: true,
  41763. configurable: true
  41764. });
  41765. StandardMaterial.prototype.needAlphaBlending = function () {
  41766. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41767. };
  41768. StandardMaterial.prototype.needAlphaTesting = function () {
  41769. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41770. };
  41771. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41772. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41773. };
  41774. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41775. return this._diffuseTexture;
  41776. };
  41777. /**
  41778. * Child classes can use it to update shaders
  41779. */
  41780. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41781. if (useInstances === void 0) { useInstances = false; }
  41782. if (subMesh.effect && this.isFrozen) {
  41783. if (this._wasPreviouslyReady) {
  41784. return true;
  41785. }
  41786. }
  41787. if (!subMesh._materialDefines) {
  41788. subMesh._materialDefines = new StandardMaterialDefines();
  41789. }
  41790. var scene = this.getScene();
  41791. var defines = subMesh._materialDefines;
  41792. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41793. if (defines._renderId === scene.getRenderId()) {
  41794. return true;
  41795. }
  41796. }
  41797. var engine = scene.getEngine();
  41798. // Lights
  41799. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41800. // Textures
  41801. if (defines._areTexturesDirty) {
  41802. defines._needUVs = false;
  41803. defines.MAINUV1 = false;
  41804. defines.MAINUV2 = false;
  41805. if (scene.texturesEnabled) {
  41806. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41807. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41808. return false;
  41809. }
  41810. else {
  41811. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  41812. }
  41813. }
  41814. else {
  41815. defines.DIFFUSE = false;
  41816. }
  41817. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41818. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41819. return false;
  41820. }
  41821. else {
  41822. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41823. }
  41824. }
  41825. else {
  41826. defines.AMBIENT = false;
  41827. }
  41828. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41829. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41830. return false;
  41831. }
  41832. else {
  41833. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41834. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41835. }
  41836. }
  41837. else {
  41838. defines.OPACITY = false;
  41839. }
  41840. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41841. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41842. return false;
  41843. }
  41844. else {
  41845. defines._needNormals = true;
  41846. defines.REFLECTION = true;
  41847. defines.ROUGHNESS = (this._roughness > 0);
  41848. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41849. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41850. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41851. switch (this._reflectionTexture.coordinatesMode) {
  41852. case BABYLON.Texture.EXPLICIT_MODE:
  41853. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41854. break;
  41855. case BABYLON.Texture.PLANAR_MODE:
  41856. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41857. break;
  41858. case BABYLON.Texture.PROJECTION_MODE:
  41859. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41860. break;
  41861. case BABYLON.Texture.SKYBOX_MODE:
  41862. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41863. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  41864. break;
  41865. case BABYLON.Texture.SPHERICAL_MODE:
  41866. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41867. break;
  41868. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41869. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41870. break;
  41871. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41872. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41873. break;
  41874. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41875. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41876. break;
  41877. case BABYLON.Texture.CUBIC_MODE:
  41878. case BABYLON.Texture.INVCUBIC_MODE:
  41879. default:
  41880. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41881. break;
  41882. }
  41883. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  41884. }
  41885. }
  41886. else {
  41887. defines.REFLECTION = false;
  41888. }
  41889. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41890. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41891. return false;
  41892. }
  41893. else {
  41894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41895. }
  41896. }
  41897. else {
  41898. defines.EMISSIVE = false;
  41899. }
  41900. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41901. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41902. return false;
  41903. }
  41904. else {
  41905. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41906. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41907. }
  41908. }
  41909. else {
  41910. defines.LIGHTMAP = false;
  41911. }
  41912. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41913. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41914. return false;
  41915. }
  41916. else {
  41917. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  41918. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41919. }
  41920. }
  41921. else {
  41922. defines.SPECULAR = false;
  41923. }
  41924. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41925. // Bump texure can not be not blocking.
  41926. if (!this._bumpTexture.isReady()) {
  41927. return false;
  41928. }
  41929. else {
  41930. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41931. defines.PARALLAX = this._useParallax;
  41932. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41933. }
  41934. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41935. }
  41936. else {
  41937. defines.BUMP = false;
  41938. }
  41939. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41940. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41941. return false;
  41942. }
  41943. else {
  41944. defines._needUVs = true;
  41945. defines.REFRACTION = true;
  41946. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41947. }
  41948. }
  41949. else {
  41950. defines.REFRACTION = false;
  41951. }
  41952. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41953. }
  41954. else {
  41955. defines.DIFFUSE = false;
  41956. defines.AMBIENT = false;
  41957. defines.OPACITY = false;
  41958. defines.REFLECTION = false;
  41959. defines.EMISSIVE = false;
  41960. defines.LIGHTMAP = false;
  41961. defines.BUMP = false;
  41962. defines.REFRACTION = false;
  41963. }
  41964. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41965. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41966. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41967. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41968. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41969. }
  41970. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  41971. if (!this._imageProcessingConfiguration.isReady()) {
  41972. return false;
  41973. }
  41974. this._imageProcessingConfiguration.prepareDefines(defines);
  41975. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  41976. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  41977. }
  41978. if (defines._areFresnelDirty) {
  41979. if (StandardMaterial.FresnelEnabled) {
  41980. // Fresnel
  41981. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41982. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41983. this._reflectionFresnelParameters) {
  41984. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41985. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41986. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41987. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41988. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41989. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41990. defines._needNormals = true;
  41991. defines.FRESNEL = true;
  41992. }
  41993. }
  41994. else {
  41995. defines.FRESNEL = false;
  41996. }
  41997. }
  41998. // Misc.
  41999. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42000. // Attribs
  42001. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42002. // Values that need to be evaluated on every frame
  42003. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42004. // Get correct effect
  42005. if (defines.isDirty) {
  42006. defines.markAsProcessed();
  42007. scene.resetCachedMaterial();
  42008. // Fallbacks
  42009. var fallbacks = new BABYLON.EffectFallbacks();
  42010. if (defines.REFLECTION) {
  42011. fallbacks.addFallback(0, "REFLECTION");
  42012. }
  42013. if (defines.SPECULAR) {
  42014. fallbacks.addFallback(0, "SPECULAR");
  42015. }
  42016. if (defines.BUMP) {
  42017. fallbacks.addFallback(0, "BUMP");
  42018. }
  42019. if (defines.PARALLAX) {
  42020. fallbacks.addFallback(1, "PARALLAX");
  42021. }
  42022. if (defines.PARALLAXOCCLUSION) {
  42023. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42024. }
  42025. if (defines.SPECULAROVERALPHA) {
  42026. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42027. }
  42028. if (defines.FOG) {
  42029. fallbacks.addFallback(1, "FOG");
  42030. }
  42031. if (defines.POINTSIZE) {
  42032. fallbacks.addFallback(0, "POINTSIZE");
  42033. }
  42034. if (defines.LOGARITHMICDEPTH) {
  42035. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42036. }
  42037. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42038. if (defines.SPECULARTERM) {
  42039. fallbacks.addFallback(0, "SPECULARTERM");
  42040. }
  42041. if (defines.DIFFUSEFRESNEL) {
  42042. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42043. }
  42044. if (defines.OPACITYFRESNEL) {
  42045. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42046. }
  42047. if (defines.REFLECTIONFRESNEL) {
  42048. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42049. }
  42050. if (defines.EMISSIVEFRESNEL) {
  42051. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42052. }
  42053. if (defines.FRESNEL) {
  42054. fallbacks.addFallback(4, "FRESNEL");
  42055. }
  42056. //Attributes
  42057. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42058. if (defines.NORMAL) {
  42059. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42060. }
  42061. if (defines.UV1) {
  42062. attribs.push(BABYLON.VertexBuffer.UVKind);
  42063. }
  42064. if (defines.UV2) {
  42065. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42066. }
  42067. if (defines.VERTEXCOLOR) {
  42068. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42069. }
  42070. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42071. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42072. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42073. var shaderName = "default";
  42074. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42075. "vFogInfos", "vFogColor", "pointSize",
  42076. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42077. "mBones",
  42078. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42079. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42080. "vReflectionPosition", "vReflectionSize",
  42081. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42082. ];
  42083. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42084. var uniformBuffers = ["Material", "Scene"];
  42085. if (BABYLON.ImageProcessingConfiguration) {
  42086. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42087. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42088. }
  42089. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42090. uniformsNames: uniforms,
  42091. uniformBuffersNames: uniformBuffers,
  42092. samplers: samplers,
  42093. defines: defines,
  42094. maxSimultaneousLights: this._maxSimultaneousLights
  42095. });
  42096. if (this.customShaderNameResolve) {
  42097. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42098. }
  42099. var join = defines.toString();
  42100. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42101. attributes: attribs,
  42102. uniformsNames: uniforms,
  42103. uniformBuffersNames: uniformBuffers,
  42104. samplers: samplers,
  42105. defines: join,
  42106. fallbacks: fallbacks,
  42107. onCompiled: this.onCompiled,
  42108. onError: this.onError,
  42109. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42110. }, engine), defines);
  42111. this.buildUniformLayout();
  42112. }
  42113. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42114. return false;
  42115. }
  42116. defines._renderId = scene.getRenderId();
  42117. this._wasPreviouslyReady = true;
  42118. return true;
  42119. };
  42120. StandardMaterial.prototype.buildUniformLayout = function () {
  42121. // Order is important !
  42122. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42123. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42124. this._uniformBuffer.addUniform("opacityParts", 4);
  42125. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42126. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42127. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42128. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42129. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42130. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42131. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42132. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42133. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42134. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42135. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42136. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42137. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42138. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42139. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42140. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42141. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42142. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42143. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42144. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42145. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42146. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42147. this._uniformBuffer.addUniform("specularMatrix", 16);
  42148. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42149. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42150. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42151. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42152. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42153. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42154. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42155. this._uniformBuffer.addUniform("pointSize", 1);
  42156. this._uniformBuffer.create();
  42157. };
  42158. StandardMaterial.prototype.unbind = function () {
  42159. if (this._activeEffect) {
  42160. var needFlag = false;
  42161. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42162. this._activeEffect.setTexture("reflection2DSampler", null);
  42163. needFlag = true;
  42164. }
  42165. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42166. this._activeEffect.setTexture("refraction2DSampler", null);
  42167. needFlag = true;
  42168. }
  42169. if (needFlag) {
  42170. this._markAllSubMeshesAsTexturesDirty();
  42171. }
  42172. }
  42173. _super.prototype.unbind.call(this);
  42174. };
  42175. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42176. var scene = this.getScene();
  42177. var defines = subMesh._materialDefines;
  42178. if (!defines) {
  42179. return;
  42180. }
  42181. var effect = subMesh.effect;
  42182. if (!effect) {
  42183. return;
  42184. }
  42185. this._activeEffect = effect;
  42186. // Matrices
  42187. this.bindOnlyWorldMatrix(world);
  42188. // Normal Matrix
  42189. if (defines.OBJECTSPACE_NORMALMAP) {
  42190. world.toNormalMatrix(this._normalMatrix);
  42191. this.bindOnlyNormalMatrix(this._normalMatrix);
  42192. }
  42193. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42194. // Bones
  42195. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42196. if (mustRebind) {
  42197. this._uniformBuffer.bindToEffect(effect, "Material");
  42198. this.bindViewProjection(effect);
  42199. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42200. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42201. // Fresnel
  42202. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42203. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42204. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42205. }
  42206. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42207. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42208. }
  42209. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42210. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42211. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42212. }
  42213. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42214. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42215. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42216. }
  42217. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42218. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42219. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42220. }
  42221. }
  42222. // Textures
  42223. if (scene.texturesEnabled) {
  42224. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42225. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42226. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42227. if (this._diffuseTexture.hasAlpha) {
  42228. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42229. }
  42230. }
  42231. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42232. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42233. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42234. }
  42235. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42236. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42237. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42238. }
  42239. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42240. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42241. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42242. if (this._reflectionTexture.boundingBoxSize) {
  42243. var cubeTexture = this._reflectionTexture;
  42244. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42245. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42246. }
  42247. }
  42248. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42249. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42250. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42251. }
  42252. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42253. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42254. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42255. }
  42256. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42257. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42258. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42259. }
  42260. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42261. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42262. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42263. if (scene._mirroredCameraPosition) {
  42264. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42265. }
  42266. else {
  42267. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42268. }
  42269. }
  42270. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42271. var depth = 1.0;
  42272. if (!this._refractionTexture.isCube) {
  42273. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42274. if (this._refractionTexture.depth) {
  42275. depth = this._refractionTexture.depth;
  42276. }
  42277. }
  42278. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42279. }
  42280. }
  42281. // Point size
  42282. if (this.pointsCloud) {
  42283. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42284. }
  42285. if (defines.SPECULARTERM) {
  42286. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42287. }
  42288. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42289. // Diffuse
  42290. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42291. }
  42292. // Textures
  42293. if (scene.texturesEnabled) {
  42294. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42295. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42296. }
  42297. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42298. effect.setTexture("ambientSampler", this._ambientTexture);
  42299. }
  42300. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42301. effect.setTexture("opacitySampler", this._opacityTexture);
  42302. }
  42303. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42304. if (this._reflectionTexture.isCube) {
  42305. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42306. }
  42307. else {
  42308. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42309. }
  42310. }
  42311. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42312. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42313. }
  42314. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42315. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42316. }
  42317. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42318. effect.setTexture("specularSampler", this._specularTexture);
  42319. }
  42320. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42321. effect.setTexture("bumpSampler", this._bumpTexture);
  42322. }
  42323. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42324. var depth = 1.0;
  42325. if (this._refractionTexture.isCube) {
  42326. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42327. }
  42328. else {
  42329. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42330. }
  42331. }
  42332. }
  42333. // Clip plane
  42334. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42335. // Colors
  42336. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42337. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42338. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42339. }
  42340. if (mustRebind || !this.isFrozen) {
  42341. // Lights
  42342. if (scene.lightsEnabled && !this._disableLighting) {
  42343. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42344. }
  42345. // View
  42346. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42347. this.bindView(effect);
  42348. }
  42349. // Fog
  42350. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42351. // Morph targets
  42352. if (defines.NUM_MORPH_INFLUENCERS) {
  42353. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42354. }
  42355. // Log. depth
  42356. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42357. // image processing
  42358. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42359. this._imageProcessingConfiguration.bind(this._activeEffect);
  42360. }
  42361. }
  42362. this._uniformBuffer.update();
  42363. this._afterBind(mesh, this._activeEffect);
  42364. };
  42365. StandardMaterial.prototype.getAnimatables = function () {
  42366. var results = [];
  42367. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42368. results.push(this._diffuseTexture);
  42369. }
  42370. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42371. results.push(this._ambientTexture);
  42372. }
  42373. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42374. results.push(this._opacityTexture);
  42375. }
  42376. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42377. results.push(this._reflectionTexture);
  42378. }
  42379. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42380. results.push(this._emissiveTexture);
  42381. }
  42382. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42383. results.push(this._specularTexture);
  42384. }
  42385. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42386. results.push(this._bumpTexture);
  42387. }
  42388. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42389. results.push(this._lightmapTexture);
  42390. }
  42391. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42392. results.push(this._refractionTexture);
  42393. }
  42394. return results;
  42395. };
  42396. StandardMaterial.prototype.getActiveTextures = function () {
  42397. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42398. if (this._diffuseTexture) {
  42399. activeTextures.push(this._diffuseTexture);
  42400. }
  42401. if (this._ambientTexture) {
  42402. activeTextures.push(this._ambientTexture);
  42403. }
  42404. if (this._opacityTexture) {
  42405. activeTextures.push(this._opacityTexture);
  42406. }
  42407. if (this._reflectionTexture) {
  42408. activeTextures.push(this._reflectionTexture);
  42409. }
  42410. if (this._emissiveTexture) {
  42411. activeTextures.push(this._emissiveTexture);
  42412. }
  42413. if (this._specularTexture) {
  42414. activeTextures.push(this._specularTexture);
  42415. }
  42416. if (this._bumpTexture) {
  42417. activeTextures.push(this._bumpTexture);
  42418. }
  42419. if (this._lightmapTexture) {
  42420. activeTextures.push(this._lightmapTexture);
  42421. }
  42422. if (this._refractionTexture) {
  42423. activeTextures.push(this._refractionTexture);
  42424. }
  42425. return activeTextures;
  42426. };
  42427. StandardMaterial.prototype.hasTexture = function (texture) {
  42428. if (_super.prototype.hasTexture.call(this, texture)) {
  42429. return true;
  42430. }
  42431. if (this._diffuseTexture === texture) {
  42432. return true;
  42433. }
  42434. if (this._ambientTexture === texture) {
  42435. return true;
  42436. }
  42437. if (this._opacityTexture === texture) {
  42438. return true;
  42439. }
  42440. if (this._reflectionTexture === texture) {
  42441. return true;
  42442. }
  42443. if (this._emissiveTexture === texture) {
  42444. return true;
  42445. }
  42446. if (this._specularTexture === texture) {
  42447. return true;
  42448. }
  42449. if (this._bumpTexture === texture) {
  42450. return true;
  42451. }
  42452. if (this._lightmapTexture === texture) {
  42453. return true;
  42454. }
  42455. if (this._refractionTexture === texture) {
  42456. return true;
  42457. }
  42458. return false;
  42459. };
  42460. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42461. if (forceDisposeTextures) {
  42462. if (this._diffuseTexture) {
  42463. this._diffuseTexture.dispose();
  42464. }
  42465. if (this._ambientTexture) {
  42466. this._ambientTexture.dispose();
  42467. }
  42468. if (this._opacityTexture) {
  42469. this._opacityTexture.dispose();
  42470. }
  42471. if (this._reflectionTexture) {
  42472. this._reflectionTexture.dispose();
  42473. }
  42474. if (this._emissiveTexture) {
  42475. this._emissiveTexture.dispose();
  42476. }
  42477. if (this._specularTexture) {
  42478. this._specularTexture.dispose();
  42479. }
  42480. if (this._bumpTexture) {
  42481. this._bumpTexture.dispose();
  42482. }
  42483. if (this._lightmapTexture) {
  42484. this._lightmapTexture.dispose();
  42485. }
  42486. if (this._refractionTexture) {
  42487. this._refractionTexture.dispose();
  42488. }
  42489. }
  42490. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42491. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42492. }
  42493. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42494. };
  42495. StandardMaterial.prototype.clone = function (name) {
  42496. var _this = this;
  42497. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42498. result.name = name;
  42499. result.id = name;
  42500. return result;
  42501. };
  42502. StandardMaterial.prototype.serialize = function () {
  42503. return BABYLON.SerializationHelper.Serialize(this);
  42504. };
  42505. // Statics
  42506. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42507. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42508. };
  42509. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42510. get: function () {
  42511. return StandardMaterial._DiffuseTextureEnabled;
  42512. },
  42513. set: function (value) {
  42514. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42515. return;
  42516. }
  42517. StandardMaterial._DiffuseTextureEnabled = value;
  42518. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42519. },
  42520. enumerable: true,
  42521. configurable: true
  42522. });
  42523. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42524. get: function () {
  42525. return StandardMaterial._AmbientTextureEnabled;
  42526. },
  42527. set: function (value) {
  42528. if (StandardMaterial._AmbientTextureEnabled === value) {
  42529. return;
  42530. }
  42531. StandardMaterial._AmbientTextureEnabled = value;
  42532. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42533. },
  42534. enumerable: true,
  42535. configurable: true
  42536. });
  42537. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42538. get: function () {
  42539. return StandardMaterial._OpacityTextureEnabled;
  42540. },
  42541. set: function (value) {
  42542. if (StandardMaterial._OpacityTextureEnabled === value) {
  42543. return;
  42544. }
  42545. StandardMaterial._OpacityTextureEnabled = value;
  42546. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42547. },
  42548. enumerable: true,
  42549. configurable: true
  42550. });
  42551. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42552. get: function () {
  42553. return StandardMaterial._ReflectionTextureEnabled;
  42554. },
  42555. set: function (value) {
  42556. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42557. return;
  42558. }
  42559. StandardMaterial._ReflectionTextureEnabled = value;
  42560. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42561. },
  42562. enumerable: true,
  42563. configurable: true
  42564. });
  42565. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42566. get: function () {
  42567. return StandardMaterial._EmissiveTextureEnabled;
  42568. },
  42569. set: function (value) {
  42570. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42571. return;
  42572. }
  42573. StandardMaterial._EmissiveTextureEnabled = value;
  42574. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42575. },
  42576. enumerable: true,
  42577. configurable: true
  42578. });
  42579. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42580. get: function () {
  42581. return StandardMaterial._SpecularTextureEnabled;
  42582. },
  42583. set: function (value) {
  42584. if (StandardMaterial._SpecularTextureEnabled === value) {
  42585. return;
  42586. }
  42587. StandardMaterial._SpecularTextureEnabled = value;
  42588. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42589. },
  42590. enumerable: true,
  42591. configurable: true
  42592. });
  42593. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42594. get: function () {
  42595. return StandardMaterial._BumpTextureEnabled;
  42596. },
  42597. set: function (value) {
  42598. if (StandardMaterial._BumpTextureEnabled === value) {
  42599. return;
  42600. }
  42601. StandardMaterial._BumpTextureEnabled = value;
  42602. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42603. },
  42604. enumerable: true,
  42605. configurable: true
  42606. });
  42607. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42608. get: function () {
  42609. return StandardMaterial._LightmapTextureEnabled;
  42610. },
  42611. set: function (value) {
  42612. if (StandardMaterial._LightmapTextureEnabled === value) {
  42613. return;
  42614. }
  42615. StandardMaterial._LightmapTextureEnabled = value;
  42616. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42617. },
  42618. enumerable: true,
  42619. configurable: true
  42620. });
  42621. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42622. get: function () {
  42623. return StandardMaterial._RefractionTextureEnabled;
  42624. },
  42625. set: function (value) {
  42626. if (StandardMaterial._RefractionTextureEnabled === value) {
  42627. return;
  42628. }
  42629. StandardMaterial._RefractionTextureEnabled = value;
  42630. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42631. },
  42632. enumerable: true,
  42633. configurable: true
  42634. });
  42635. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42636. get: function () {
  42637. return StandardMaterial._ColorGradingTextureEnabled;
  42638. },
  42639. set: function (value) {
  42640. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42641. return;
  42642. }
  42643. StandardMaterial._ColorGradingTextureEnabled = value;
  42644. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42645. },
  42646. enumerable: true,
  42647. configurable: true
  42648. });
  42649. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42650. get: function () {
  42651. return StandardMaterial._FresnelEnabled;
  42652. },
  42653. set: function (value) {
  42654. if (StandardMaterial._FresnelEnabled === value) {
  42655. return;
  42656. }
  42657. StandardMaterial._FresnelEnabled = value;
  42658. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42659. },
  42660. enumerable: true,
  42661. configurable: true
  42662. });
  42663. // Flags used to enable or disable a type of texture for all Standard Materials
  42664. StandardMaterial._DiffuseTextureEnabled = true;
  42665. StandardMaterial._AmbientTextureEnabled = true;
  42666. StandardMaterial._OpacityTextureEnabled = true;
  42667. StandardMaterial._ReflectionTextureEnabled = true;
  42668. StandardMaterial._EmissiveTextureEnabled = true;
  42669. StandardMaterial._SpecularTextureEnabled = true;
  42670. StandardMaterial._BumpTextureEnabled = true;
  42671. StandardMaterial._LightmapTextureEnabled = true;
  42672. StandardMaterial._RefractionTextureEnabled = true;
  42673. StandardMaterial._ColorGradingTextureEnabled = true;
  42674. StandardMaterial._FresnelEnabled = true;
  42675. __decorate([
  42676. BABYLON.serializeAsTexture("diffuseTexture")
  42677. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42678. __decorate([
  42679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42680. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42681. __decorate([
  42682. BABYLON.serializeAsTexture("ambientTexture")
  42683. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42684. __decorate([
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42687. __decorate([
  42688. BABYLON.serializeAsTexture("opacityTexture")
  42689. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42690. __decorate([
  42691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42692. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42693. __decorate([
  42694. BABYLON.serializeAsTexture("reflectionTexture")
  42695. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42696. __decorate([
  42697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42698. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42699. __decorate([
  42700. BABYLON.serializeAsTexture("emissiveTexture")
  42701. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42702. __decorate([
  42703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42704. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42705. __decorate([
  42706. BABYLON.serializeAsTexture("specularTexture")
  42707. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42708. __decorate([
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42710. ], StandardMaterial.prototype, "specularTexture", void 0);
  42711. __decorate([
  42712. BABYLON.serializeAsTexture("bumpTexture")
  42713. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42714. __decorate([
  42715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42716. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42717. __decorate([
  42718. BABYLON.serializeAsTexture("lightmapTexture")
  42719. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42720. __decorate([
  42721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42722. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42723. __decorate([
  42724. BABYLON.serializeAsTexture("refractionTexture")
  42725. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42726. __decorate([
  42727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42728. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42729. __decorate([
  42730. BABYLON.serializeAsColor3("ambient")
  42731. ], StandardMaterial.prototype, "ambientColor", void 0);
  42732. __decorate([
  42733. BABYLON.serializeAsColor3("diffuse")
  42734. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42735. __decorate([
  42736. BABYLON.serializeAsColor3("specular")
  42737. ], StandardMaterial.prototype, "specularColor", void 0);
  42738. __decorate([
  42739. BABYLON.serializeAsColor3("emissive")
  42740. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42741. __decorate([
  42742. BABYLON.serialize()
  42743. ], StandardMaterial.prototype, "specularPower", void 0);
  42744. __decorate([
  42745. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42746. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42747. __decorate([
  42748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42749. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42750. __decorate([
  42751. BABYLON.serialize("useEmissiveAsIllumination")
  42752. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42753. __decorate([
  42754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42755. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42756. __decorate([
  42757. BABYLON.serialize("linkEmissiveWithDiffuse")
  42758. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42759. __decorate([
  42760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42761. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42762. __decorate([
  42763. BABYLON.serialize("useSpecularOverAlpha")
  42764. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42765. __decorate([
  42766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42767. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42768. __decorate([
  42769. BABYLON.serialize("useReflectionOverAlpha")
  42770. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42771. __decorate([
  42772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42773. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42774. __decorate([
  42775. BABYLON.serialize("disableLighting")
  42776. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42777. __decorate([
  42778. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42779. ], StandardMaterial.prototype, "disableLighting", void 0);
  42780. __decorate([
  42781. BABYLON.serialize("useObjectSpaceNormalMap")
  42782. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  42783. __decorate([
  42784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42785. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42786. __decorate([
  42787. BABYLON.serialize("useParallax")
  42788. ], StandardMaterial.prototype, "_useParallax", void 0);
  42789. __decorate([
  42790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42791. ], StandardMaterial.prototype, "useParallax", void 0);
  42792. __decorate([
  42793. BABYLON.serialize("useParallaxOcclusion")
  42794. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42795. __decorate([
  42796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42797. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42798. __decorate([
  42799. BABYLON.serialize()
  42800. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42801. __decorate([
  42802. BABYLON.serialize("roughness")
  42803. ], StandardMaterial.prototype, "_roughness", void 0);
  42804. __decorate([
  42805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42806. ], StandardMaterial.prototype, "roughness", void 0);
  42807. __decorate([
  42808. BABYLON.serialize()
  42809. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42810. __decorate([
  42811. BABYLON.serialize()
  42812. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42813. __decorate([
  42814. BABYLON.serialize()
  42815. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  42816. __decorate([
  42817. BABYLON.serialize("useLightmapAsShadowmap")
  42818. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42819. __decorate([
  42820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42821. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42822. __decorate([
  42823. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42824. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42825. __decorate([
  42826. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42827. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42828. __decorate([
  42829. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42830. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42831. __decorate([
  42832. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  42833. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42834. __decorate([
  42835. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42836. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42837. __decorate([
  42838. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42839. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42840. __decorate([
  42841. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42842. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42843. __decorate([
  42844. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42845. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42846. __decorate([
  42847. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42848. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42849. __decorate([
  42850. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42851. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42852. __decorate([
  42853. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42854. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42855. __decorate([
  42856. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42857. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42858. __decorate([
  42859. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42860. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42861. __decorate([
  42862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42863. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42864. __decorate([
  42865. BABYLON.serialize("maxSimultaneousLights")
  42866. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42867. __decorate([
  42868. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42869. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42870. __decorate([
  42871. BABYLON.serialize("invertNormalMapX")
  42872. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42873. __decorate([
  42874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42875. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42876. __decorate([
  42877. BABYLON.serialize("invertNormalMapY")
  42878. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42879. __decorate([
  42880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42881. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42882. __decorate([
  42883. BABYLON.serialize("twoSidedLighting")
  42884. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42885. __decorate([
  42886. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42887. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42888. __decorate([
  42889. BABYLON.serialize()
  42890. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42891. return StandardMaterial;
  42892. }(BABYLON.PushMaterial));
  42893. BABYLON.StandardMaterial = StandardMaterial;
  42894. })(BABYLON || (BABYLON = {}));
  42895. //# sourceMappingURL=babylon.standardMaterial.js.map
  42896. var BABYLON;
  42897. (function (BABYLON) {
  42898. /**
  42899. * Class representing spherical polynomial coefficients to the 3rd degree
  42900. */
  42901. var SphericalPolynomial = /** @class */ (function () {
  42902. function SphericalPolynomial() {
  42903. /**
  42904. * The x coefficients of the spherical polynomial
  42905. */
  42906. this.x = BABYLON.Vector3.Zero();
  42907. /**
  42908. * The y coefficients of the spherical polynomial
  42909. */
  42910. this.y = BABYLON.Vector3.Zero();
  42911. /**
  42912. * The z coefficients of the spherical polynomial
  42913. */
  42914. this.z = BABYLON.Vector3.Zero();
  42915. /**
  42916. * The xx coefficients of the spherical polynomial
  42917. */
  42918. this.xx = BABYLON.Vector3.Zero();
  42919. /**
  42920. * The yy coefficients of the spherical polynomial
  42921. */
  42922. this.yy = BABYLON.Vector3.Zero();
  42923. /**
  42924. * The zz coefficients of the spherical polynomial
  42925. */
  42926. this.zz = BABYLON.Vector3.Zero();
  42927. /**
  42928. * The xy coefficients of the spherical polynomial
  42929. */
  42930. this.xy = BABYLON.Vector3.Zero();
  42931. /**
  42932. * The yz coefficients of the spherical polynomial
  42933. */
  42934. this.yz = BABYLON.Vector3.Zero();
  42935. /**
  42936. * The zx coefficients of the spherical polynomial
  42937. */
  42938. this.zx = BABYLON.Vector3.Zero();
  42939. }
  42940. /**
  42941. * Adds an ambient color to the spherical polynomial
  42942. * @param color the color to add
  42943. */
  42944. SphericalPolynomial.prototype.addAmbient = function (color) {
  42945. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  42946. this.xx = this.xx.add(colorVector);
  42947. this.yy = this.yy.add(colorVector);
  42948. this.zz = this.zz.add(colorVector);
  42949. };
  42950. /**
  42951. * Scales the spherical polynomial by the given amount
  42952. * @param scale the amount to scale
  42953. */
  42954. SphericalPolynomial.prototype.scale = function (scale) {
  42955. this.x = this.x.scale(scale);
  42956. this.y = this.y.scale(scale);
  42957. this.z = this.z.scale(scale);
  42958. this.xx = this.xx.scale(scale);
  42959. this.yy = this.yy.scale(scale);
  42960. this.zz = this.zz.scale(scale);
  42961. this.yz = this.yz.scale(scale);
  42962. this.zx = this.zx.scale(scale);
  42963. this.xy = this.xy.scale(scale);
  42964. };
  42965. /**
  42966. * Gets the spherical polynomial from harmonics
  42967. * @param harmonics the spherical harmonics
  42968. * @returns the spherical polynomial
  42969. */
  42970. SphericalPolynomial.FromHarmonics = function (harmonics) {
  42971. var result = new SphericalPolynomial();
  42972. result.x = harmonics.l11.scale(1.02333);
  42973. result.y = harmonics.l1_1.scale(1.02333);
  42974. result.z = harmonics.l10.scale(1.02333);
  42975. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  42976. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  42977. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  42978. result.yz = harmonics.l2_1.scale(0.858086);
  42979. result.zx = harmonics.l21.scale(0.858086);
  42980. result.xy = harmonics.l2_2.scale(0.858086);
  42981. result.scale(1.0 / Math.PI);
  42982. return result;
  42983. };
  42984. /**
  42985. * Constructs a spherical polynomial from an array.
  42986. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  42987. * @returns the spherical polynomial
  42988. */
  42989. SphericalPolynomial.FromArray = function (data) {
  42990. var sp = new SphericalPolynomial();
  42991. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  42992. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  42993. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  42994. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  42995. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  42996. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  42997. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  42998. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  42999. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43000. return sp;
  43001. };
  43002. return SphericalPolynomial;
  43003. }());
  43004. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43005. /**
  43006. * Class representing spherical harmonics coefficients to the 3rd degree
  43007. */
  43008. var SphericalHarmonics = /** @class */ (function () {
  43009. function SphericalHarmonics() {
  43010. /**
  43011. * The l0,0 coefficients of the spherical harmonics
  43012. */
  43013. this.l00 = BABYLON.Vector3.Zero();
  43014. /**
  43015. * The l1,-1 coefficients of the spherical harmonics
  43016. */
  43017. this.l1_1 = BABYLON.Vector3.Zero();
  43018. /**
  43019. * The l1,0 coefficients of the spherical harmonics
  43020. */
  43021. this.l10 = BABYLON.Vector3.Zero();
  43022. /**
  43023. * The l1,1 coefficients of the spherical harmonics
  43024. */
  43025. this.l11 = BABYLON.Vector3.Zero();
  43026. /**
  43027. * The l2,-2 coefficients of the spherical harmonics
  43028. */
  43029. this.l2_2 = BABYLON.Vector3.Zero();
  43030. /**
  43031. * The l2,-1 coefficients of the spherical harmonics
  43032. */
  43033. this.l2_1 = BABYLON.Vector3.Zero();
  43034. /**
  43035. * The l2,0 coefficients of the spherical harmonics
  43036. */
  43037. this.l20 = BABYLON.Vector3.Zero();
  43038. /**
  43039. * The l2,1 coefficients of the spherical harmonics
  43040. */
  43041. this.l21 = BABYLON.Vector3.Zero();
  43042. /**
  43043. * The l2,2 coefficients of the spherical harmonics
  43044. */
  43045. this.lL22 = BABYLON.Vector3.Zero();
  43046. }
  43047. /**
  43048. * Adds a light to the spherical harmonics
  43049. * @param direction the direction of the light
  43050. * @param color the color of the light
  43051. * @param deltaSolidAngle the delta solid angle of the light
  43052. */
  43053. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43054. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43055. var c = colorVector.scale(deltaSolidAngle);
  43056. this.l00 = this.l00.add(c.scale(0.282095));
  43057. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43058. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43059. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43060. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43061. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43062. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43063. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43064. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43065. };
  43066. /**
  43067. * Scales the spherical harmonics by the given amount
  43068. * @param scale the amount to scale
  43069. */
  43070. SphericalHarmonics.prototype.scale = function (scale) {
  43071. this.l00 = this.l00.scale(scale);
  43072. this.l1_1 = this.l1_1.scale(scale);
  43073. this.l10 = this.l10.scale(scale);
  43074. this.l11 = this.l11.scale(scale);
  43075. this.l2_2 = this.l2_2.scale(scale);
  43076. this.l2_1 = this.l2_1.scale(scale);
  43077. this.l20 = this.l20.scale(scale);
  43078. this.l21 = this.l21.scale(scale);
  43079. this.lL22 = this.lL22.scale(scale);
  43080. };
  43081. /**
  43082. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43083. *
  43084. * ```
  43085. * E_lm = A_l * L_lm
  43086. * ```
  43087. *
  43088. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43089. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43090. * the scaling factors are given in equation 9.
  43091. */
  43092. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43093. // Constant (Band 0)
  43094. this.l00 = this.l00.scale(3.141593);
  43095. // Linear (Band 1)
  43096. this.l1_1 = this.l1_1.scale(2.094395);
  43097. this.l10 = this.l10.scale(2.094395);
  43098. this.l11 = this.l11.scale(2.094395);
  43099. // Quadratic (Band 2)
  43100. this.l2_2 = this.l2_2.scale(0.785398);
  43101. this.l2_1 = this.l2_1.scale(0.785398);
  43102. this.l20 = this.l20.scale(0.785398);
  43103. this.l21 = this.l21.scale(0.785398);
  43104. this.lL22 = this.lL22.scale(0.785398);
  43105. };
  43106. /**
  43107. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43108. *
  43109. * ```
  43110. * L = (1/pi) * E * rho
  43111. * ```
  43112. *
  43113. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43114. */
  43115. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43116. this.scale(1.0 / Math.PI);
  43117. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43118. // (The pixel shader must apply albedo after texture fetches, etc).
  43119. };
  43120. /**
  43121. * Gets the spherical harmonics from polynomial
  43122. * @param polynomial the spherical polynomial
  43123. * @returns the spherical harmonics
  43124. */
  43125. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43126. var result = new SphericalHarmonics();
  43127. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43128. result.l1_1 = polynomial.y.scale(0.977204);
  43129. result.l10 = polynomial.z.scale(0.977204);
  43130. result.l11 = polynomial.x.scale(0.977204);
  43131. result.l2_2 = polynomial.xy.scale(1.16538);
  43132. result.l2_1 = polynomial.yz.scale(1.16538);
  43133. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43134. result.l21 = polynomial.zx.scale(1.16538);
  43135. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43136. result.scale(Math.PI);
  43137. return result;
  43138. };
  43139. /**
  43140. * Constructs a spherical harmonics from an array.
  43141. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43142. * @returns the spherical harmonics
  43143. */
  43144. SphericalHarmonics.FromArray = function (data) {
  43145. var sh = new SphericalHarmonics();
  43146. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43147. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43148. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43149. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43150. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43151. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43152. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43153. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43154. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43155. return sh;
  43156. };
  43157. return SphericalHarmonics;
  43158. }());
  43159. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43160. })(BABYLON || (BABYLON = {}));
  43161. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43162. var BABYLON;
  43163. (function (BABYLON) {
  43164. var FileFaceOrientation = /** @class */ (function () {
  43165. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43166. this.name = name;
  43167. this.worldAxisForNormal = worldAxisForNormal;
  43168. this.worldAxisForFileX = worldAxisForFileX;
  43169. this.worldAxisForFileY = worldAxisForFileY;
  43170. }
  43171. return FileFaceOrientation;
  43172. }());
  43173. ;
  43174. /**
  43175. * Helper class dealing with the extraction of spherical polynomial dataArray
  43176. * from a cube map.
  43177. */
  43178. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43179. function CubeMapToSphericalPolynomialTools() {
  43180. }
  43181. /**
  43182. * Converts a texture to the according Spherical Polynomial data.
  43183. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43184. *
  43185. * @param texture The texture to extract the information from.
  43186. * @return The Spherical Polynomial data.
  43187. */
  43188. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43189. if (!texture.isCube) {
  43190. // Only supports cube Textures currently.
  43191. return null;
  43192. }
  43193. var size = texture.getSize().width;
  43194. var right = texture.readPixels(0);
  43195. var left = texture.readPixels(1);
  43196. var up;
  43197. var down;
  43198. if (texture.isRenderTarget) {
  43199. up = texture.readPixels(3);
  43200. down = texture.readPixels(2);
  43201. }
  43202. else {
  43203. up = texture.readPixels(2);
  43204. down = texture.readPixels(3);
  43205. }
  43206. var front = texture.readPixels(4);
  43207. var back = texture.readPixels(5);
  43208. var gammaSpace = texture.gammaSpace;
  43209. // Always read as RGBA.
  43210. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43211. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43212. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43213. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43214. }
  43215. var cubeInfo = {
  43216. size: size,
  43217. right: right,
  43218. left: left,
  43219. up: up,
  43220. down: down,
  43221. front: front,
  43222. back: back,
  43223. format: format,
  43224. type: type,
  43225. gammaSpace: gammaSpace,
  43226. };
  43227. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43228. };
  43229. /**
  43230. * Converts a cubemap to the according Spherical Polynomial data.
  43231. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43232. *
  43233. * @param cubeInfo The Cube map to extract the information from.
  43234. * @return The Spherical Polynomial data.
  43235. */
  43236. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43237. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43238. var totalSolidAngle = 0.0;
  43239. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43240. var du = 2.0 / cubeInfo.size;
  43241. var dv = du;
  43242. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43243. var minUV = du * 0.5 - 1.0;
  43244. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43245. var fileFace = this.FileFaces[faceIndex];
  43246. var dataArray = cubeInfo[fileFace.name];
  43247. var v = minUV;
  43248. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43249. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43250. // Because SP is still linear, so summation is fine in that basis.
  43251. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43252. for (var y = 0; y < cubeInfo.size; y++) {
  43253. var u = minUV;
  43254. for (var x = 0; x < cubeInfo.size; x++) {
  43255. // World direction (not normalised)
  43256. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43257. worldDirection.normalize();
  43258. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43259. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43260. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43261. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43262. // Handle Integer types.
  43263. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43264. r /= 255;
  43265. g /= 255;
  43266. b /= 255;
  43267. }
  43268. // Handle Gamma space textures.
  43269. if (cubeInfo.gammaSpace) {
  43270. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43271. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43272. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43273. }
  43274. var color = new BABYLON.Color3(r, g, b);
  43275. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43276. totalSolidAngle += deltaSolidAngle;
  43277. u += du;
  43278. }
  43279. v += dv;
  43280. }
  43281. }
  43282. // Solid angle for entire sphere is 4*pi
  43283. var sphereSolidAngle = 4.0 * Math.PI;
  43284. // Adjust the solid angle to allow for how many faces we processed.
  43285. var facesProcessed = 6.0;
  43286. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43287. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43288. // This is needed because the numerical integration over the cube uses a
  43289. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43290. // and also to compensate for accumulative error due to float precision in the summation.
  43291. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43292. sphericalHarmonics.scale(correctionFactor);
  43293. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43294. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43295. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43296. };
  43297. CubeMapToSphericalPolynomialTools.FileFaces = [
  43298. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43299. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43300. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43301. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43302. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43303. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43304. ];
  43305. return CubeMapToSphericalPolynomialTools;
  43306. }());
  43307. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43308. })(BABYLON || (BABYLON = {}));
  43309. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43310. var BABYLON;
  43311. (function (BABYLON) {
  43312. /**
  43313. * Manages the defines for the PBR Material.
  43314. * @hiddenChildren
  43315. */
  43316. var PBRMaterialDefines = /** @class */ (function (_super) {
  43317. __extends(PBRMaterialDefines, _super);
  43318. /**
  43319. * Initializes the PBR Material defines.
  43320. */
  43321. function PBRMaterialDefines() {
  43322. var _this = _super.call(this) || this;
  43323. _this.PBR = true;
  43324. _this.MAINUV1 = false;
  43325. _this.MAINUV2 = false;
  43326. _this.UV1 = false;
  43327. _this.UV2 = false;
  43328. _this.ALBEDO = false;
  43329. _this.ALBEDODIRECTUV = 0;
  43330. _this.VERTEXCOLOR = false;
  43331. _this.AMBIENT = false;
  43332. _this.AMBIENTDIRECTUV = 0;
  43333. _this.AMBIENTINGRAYSCALE = false;
  43334. _this.OPACITY = false;
  43335. _this.VERTEXALPHA = false;
  43336. _this.OPACITYDIRECTUV = 0;
  43337. _this.OPACITYRGB = false;
  43338. _this.ALPHATEST = false;
  43339. _this.DEPTHPREPASS = false;
  43340. _this.ALPHABLEND = false;
  43341. _this.ALPHAFROMALBEDO = false;
  43342. _this.ALPHATESTVALUE = "0.5";
  43343. _this.SPECULAROVERALPHA = false;
  43344. _this.RADIANCEOVERALPHA = false;
  43345. _this.ALPHAFRESNEL = false;
  43346. _this.LINEARALPHAFRESNEL = false;
  43347. _this.PREMULTIPLYALPHA = false;
  43348. _this.EMISSIVE = false;
  43349. _this.EMISSIVEDIRECTUV = 0;
  43350. _this.REFLECTIVITY = false;
  43351. _this.REFLECTIVITYDIRECTUV = 0;
  43352. _this.SPECULARTERM = false;
  43353. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43354. _this.MICROSURFACEAUTOMATIC = false;
  43355. _this.LODBASEDMICROSFURACE = false;
  43356. _this.MICROSURFACEMAP = false;
  43357. _this.MICROSURFACEMAPDIRECTUV = 0;
  43358. _this.METALLICWORKFLOW = false;
  43359. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43360. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43361. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43362. _this.AOSTOREINMETALMAPRED = false;
  43363. _this.ENVIRONMENTBRDF = false;
  43364. _this.NORMAL = false;
  43365. _this.TANGENT = false;
  43366. _this.BUMP = false;
  43367. _this.BUMPDIRECTUV = 0;
  43368. _this.OBJECTSPACE_NORMALMAP = false;
  43369. _this.PARALLAX = false;
  43370. _this.PARALLAXOCCLUSION = false;
  43371. _this.NORMALXYSCALE = true;
  43372. _this.LIGHTMAP = false;
  43373. _this.LIGHTMAPDIRECTUV = 0;
  43374. _this.USELIGHTMAPASSHADOWMAP = false;
  43375. _this.GAMMALIGHTMAP = false;
  43376. _this.REFLECTION = false;
  43377. _this.REFLECTIONMAP_3D = false;
  43378. _this.REFLECTIONMAP_SPHERICAL = false;
  43379. _this.REFLECTIONMAP_PLANAR = false;
  43380. _this.REFLECTIONMAP_CUBIC = false;
  43381. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43382. _this.REFLECTIONMAP_PROJECTION = false;
  43383. _this.REFLECTIONMAP_SKYBOX = false;
  43384. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  43385. _this.REFLECTIONMAP_EXPLICIT = false;
  43386. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43387. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43388. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43389. _this.INVERTCUBICMAP = false;
  43390. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43391. _this.USESPHERICALINVERTEX = false;
  43392. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43393. _this.LODINREFLECTIONALPHA = false;
  43394. _this.GAMMAREFLECTION = false;
  43395. _this.RGBDREFLECTION = false;
  43396. _this.RADIANCEOCCLUSION = false;
  43397. _this.HORIZONOCCLUSION = false;
  43398. _this.REFRACTION = false;
  43399. _this.REFRACTIONMAP_3D = false;
  43400. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43401. _this.LODINREFRACTIONALPHA = false;
  43402. _this.GAMMAREFRACTION = false;
  43403. _this.RGBDREFRACTION = false;
  43404. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43405. _this.INSTANCES = false;
  43406. _this.NUM_BONE_INFLUENCERS = 0;
  43407. _this.BonesPerMesh = 0;
  43408. _this.NONUNIFORMSCALING = false;
  43409. _this.MORPHTARGETS = false;
  43410. _this.MORPHTARGETS_NORMAL = false;
  43411. _this.MORPHTARGETS_TANGENT = false;
  43412. _this.NUM_MORPH_INFLUENCERS = 0;
  43413. _this.IMAGEPROCESSING = false;
  43414. _this.VIGNETTE = false;
  43415. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43416. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43417. _this.TONEMAPPING = false;
  43418. _this.TONEMAPPING_ACES = false;
  43419. _this.CONTRAST = false;
  43420. _this.COLORCURVES = false;
  43421. _this.COLORGRADING = false;
  43422. _this.COLORGRADING3D = false;
  43423. _this.SAMPLER3DGREENDEPTH = false;
  43424. _this.SAMPLER3DBGRMAP = false;
  43425. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43426. _this.EXPOSURE = false;
  43427. _this.USEPHYSICALLIGHTFALLOFF = false;
  43428. _this.USEGLTFLIGHTFALLOFF = false;
  43429. _this.TWOSIDEDLIGHTING = false;
  43430. _this.SHADOWFLOAT = false;
  43431. _this.CLIPPLANE = false;
  43432. _this.CLIPPLANE2 = false;
  43433. _this.CLIPPLANE3 = false;
  43434. _this.CLIPPLANE4 = false;
  43435. _this.POINTSIZE = false;
  43436. _this.FOG = false;
  43437. _this.LOGARITHMICDEPTH = false;
  43438. _this.FORCENORMALFORWARD = false;
  43439. _this.SPECULARAA = false;
  43440. _this.UNLIT = false;
  43441. _this.rebuild();
  43442. return _this;
  43443. }
  43444. /**
  43445. * Resets the PBR Material defines.
  43446. */
  43447. PBRMaterialDefines.prototype.reset = function () {
  43448. _super.prototype.reset.call(this);
  43449. this.ALPHATESTVALUE = "0.5";
  43450. this.PBR = true;
  43451. };
  43452. return PBRMaterialDefines;
  43453. }(BABYLON.MaterialDefines));
  43454. /**
  43455. * The Physically based material base class of BJS.
  43456. *
  43457. * This offers the main features of a standard PBR material.
  43458. * For more information, please refer to the documentation :
  43459. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43460. */
  43461. var PBRBaseMaterial = /** @class */ (function (_super) {
  43462. __extends(PBRBaseMaterial, _super);
  43463. /**
  43464. * Instantiates a new PBRMaterial instance.
  43465. *
  43466. * @param name The material name
  43467. * @param scene The scene the material will be use in.
  43468. */
  43469. function PBRBaseMaterial(name, scene) {
  43470. var _this = _super.call(this, name, scene) || this;
  43471. /**
  43472. * Intensity of the direct lights e.g. the four lights available in your scene.
  43473. * This impacts both the direct diffuse and specular highlights.
  43474. */
  43475. _this._directIntensity = 1.0;
  43476. /**
  43477. * Intensity of the emissive part of the material.
  43478. * This helps controlling the emissive effect without modifying the emissive color.
  43479. */
  43480. _this._emissiveIntensity = 1.0;
  43481. /**
  43482. * Intensity of the environment e.g. how much the environment will light the object
  43483. * either through harmonics for rough material or through the refelction for shiny ones.
  43484. */
  43485. _this._environmentIntensity = 1.0;
  43486. /**
  43487. * This is a special control allowing the reduction of the specular highlights coming from the
  43488. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43489. */
  43490. _this._specularIntensity = 1.0;
  43491. /**
  43492. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43493. */
  43494. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43495. /**
  43496. * Debug Control allowing disabling the bump map on this material.
  43497. */
  43498. _this._disableBumpMap = false;
  43499. /**
  43500. * AKA Occlusion Texture Intensity in other nomenclature.
  43501. */
  43502. _this._ambientTextureStrength = 1.0;
  43503. /**
  43504. * Defines how much the AO map is occluding the analytical lights (point spot...).
  43505. * 1 means it completely occludes it
  43506. * 0 mean it has no impact
  43507. */
  43508. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  43509. /**
  43510. * The color of a material in ambient lighting.
  43511. */
  43512. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43513. /**
  43514. * AKA Diffuse Color in other nomenclature.
  43515. */
  43516. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43517. /**
  43518. * AKA Specular Color in other nomenclature.
  43519. */
  43520. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43521. /**
  43522. * The color applied when light is reflected from a material.
  43523. */
  43524. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43525. /**
  43526. * The color applied when light is emitted from a material.
  43527. */
  43528. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43529. /**
  43530. * AKA Glossiness in other nomenclature.
  43531. */
  43532. _this._microSurface = 0.9;
  43533. /**
  43534. * source material index of refraction (IOR)' / 'destination material IOR.
  43535. */
  43536. _this._indexOfRefraction = 0.66;
  43537. /**
  43538. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43539. */
  43540. _this._invertRefractionY = false;
  43541. /**
  43542. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43543. * Materials half opaque for instance using refraction could benefit from this control.
  43544. */
  43545. _this._linkRefractionWithTransparency = false;
  43546. /**
  43547. * Specifies that the material will use the light map as a show map.
  43548. */
  43549. _this._useLightmapAsShadowmap = false;
  43550. /**
  43551. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43552. * makes the reflect vector face the model (under horizon).
  43553. */
  43554. _this._useHorizonOcclusion = true;
  43555. /**
  43556. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43557. * too much the area relying on ambient texture to define their ambient occlusion.
  43558. */
  43559. _this._useRadianceOcclusion = true;
  43560. /**
  43561. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43562. */
  43563. _this._useAlphaFromAlbedoTexture = false;
  43564. /**
  43565. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43566. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43567. */
  43568. _this._useSpecularOverAlpha = true;
  43569. /**
  43570. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43571. */
  43572. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43573. /**
  43574. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43575. */
  43576. _this._useRoughnessFromMetallicTextureAlpha = true;
  43577. /**
  43578. * Specifies if the metallic texture contains the roughness information in its green channel.
  43579. */
  43580. _this._useRoughnessFromMetallicTextureGreen = false;
  43581. /**
  43582. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43583. */
  43584. _this._useMetallnessFromMetallicTextureBlue = false;
  43585. /**
  43586. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43587. */
  43588. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43589. /**
  43590. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43591. */
  43592. _this._useAmbientInGrayScale = false;
  43593. /**
  43594. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43595. * The material will try to infer what glossiness each pixel should be.
  43596. */
  43597. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43598. /**
  43599. * Defines the falloff type used in this material.
  43600. * It by default is Physical.
  43601. */
  43602. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43603. /**
  43604. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43605. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43606. */
  43607. _this._useRadianceOverAlpha = true;
  43608. /**
  43609. * Allows using an object space normal map (instead of tangent space).
  43610. */
  43611. _this._useObjectSpaceNormalMap = false;
  43612. /**
  43613. * Allows using the bump map in parallax mode.
  43614. */
  43615. _this._useParallax = false;
  43616. /**
  43617. * Allows using the bump map in parallax occlusion mode.
  43618. */
  43619. _this._useParallaxOcclusion = false;
  43620. /**
  43621. * Controls the scale bias of the parallax mode.
  43622. */
  43623. _this._parallaxScaleBias = 0.05;
  43624. /**
  43625. * If sets to true, disables all the lights affecting the material.
  43626. */
  43627. _this._disableLighting = false;
  43628. /**
  43629. * Number of Simultaneous lights allowed on the material.
  43630. */
  43631. _this._maxSimultaneousLights = 4;
  43632. /**
  43633. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43634. */
  43635. _this._invertNormalMapX = false;
  43636. /**
  43637. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43638. */
  43639. _this._invertNormalMapY = false;
  43640. /**
  43641. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43642. */
  43643. _this._twoSidedLighting = false;
  43644. /**
  43645. * Defines the alpha limits in alpha test mode.
  43646. */
  43647. _this._alphaCutOff = 0.4;
  43648. /**
  43649. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43650. */
  43651. _this._forceAlphaTest = false;
  43652. /**
  43653. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43654. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43655. */
  43656. _this._useAlphaFresnel = false;
  43657. /**
  43658. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43659. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43660. */
  43661. _this._useLinearAlphaFresnel = false;
  43662. /**
  43663. * The transparency mode of the material.
  43664. */
  43665. _this._transparencyMode = null;
  43666. /**
  43667. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43668. * from cos thetav and roughness:
  43669. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43670. */
  43671. _this._environmentBRDFTexture = null;
  43672. /**
  43673. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43674. */
  43675. _this._forceIrradianceInFragment = false;
  43676. /**
  43677. * Force normal to face away from face.
  43678. */
  43679. _this._forceNormalForward = false;
  43680. /**
  43681. * Enables specular anti aliasing in the PBR shader.
  43682. * It will both interacts on the Geometry for analytical and IBL lighting.
  43683. * It also prefilter the roughness map based on the bump values.
  43684. */
  43685. _this._enableSpecularAntiAliasing = false;
  43686. /**
  43687. * Stores the available render targets.
  43688. */
  43689. _this._renderTargets = new BABYLON.SmartArray(16);
  43690. /**
  43691. * Sets the global ambient color for the material used in lighting calculations.
  43692. */
  43693. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43694. /**
  43695. * If set to true, no lighting calculations will be applied.
  43696. */
  43697. _this._unlit = false;
  43698. // Setup the default processing configuration to the scene.
  43699. _this._attachImageProcessingConfiguration(null);
  43700. _this.getRenderTargetTextures = function () {
  43701. _this._renderTargets.reset();
  43702. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43703. _this._renderTargets.push(_this._reflectionTexture);
  43704. }
  43705. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43706. _this._renderTargets.push(_this._refractionTexture);
  43707. }
  43708. return _this._renderTargets;
  43709. };
  43710. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43711. return _this;
  43712. }
  43713. /**
  43714. * Attaches a new image processing configuration to the PBR Material.
  43715. * @param configuration
  43716. */
  43717. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43718. var _this = this;
  43719. if (configuration === this._imageProcessingConfiguration) {
  43720. return;
  43721. }
  43722. // Detaches observer.
  43723. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43724. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43725. }
  43726. // Pick the scene configuration if needed.
  43727. if (!configuration) {
  43728. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43729. }
  43730. else {
  43731. this._imageProcessingConfiguration = configuration;
  43732. }
  43733. // Attaches observer.
  43734. if (this._imageProcessingConfiguration) {
  43735. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43736. _this._markAllSubMeshesAsImageProcessingDirty();
  43737. });
  43738. }
  43739. };
  43740. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  43741. /**
  43742. * Gets a boolean indicating that current material needs to register RTT
  43743. */
  43744. get: function () {
  43745. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43746. return true;
  43747. }
  43748. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43749. return true;
  43750. }
  43751. return false;
  43752. },
  43753. enumerable: true,
  43754. configurable: true
  43755. });
  43756. /**
  43757. * Gets the name of the material class.
  43758. */
  43759. PBRBaseMaterial.prototype.getClassName = function () {
  43760. return "PBRBaseMaterial";
  43761. };
  43762. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43763. /**
  43764. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43765. */
  43766. get: function () {
  43767. return this._useLogarithmicDepth;
  43768. },
  43769. /**
  43770. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43771. */
  43772. set: function (value) {
  43773. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43774. },
  43775. enumerable: true,
  43776. configurable: true
  43777. });
  43778. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43779. /**
  43780. * Gets the current transparency mode.
  43781. */
  43782. get: function () {
  43783. return this._transparencyMode;
  43784. },
  43785. /**
  43786. * Sets the transparency mode of the material.
  43787. *
  43788. * | Value | Type | Description |
  43789. * | ----- | ----------------------------------- | ----------- |
  43790. * | 0 | OPAQUE | |
  43791. * | 1 | ALPHATEST | |
  43792. * | 2 | ALPHABLEND | |
  43793. * | 3 | ALPHATESTANDBLEND | |
  43794. *
  43795. */
  43796. set: function (value) {
  43797. if (this._transparencyMode === value) {
  43798. return;
  43799. }
  43800. this._transparencyMode = value;
  43801. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43802. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43803. },
  43804. enumerable: true,
  43805. configurable: true
  43806. });
  43807. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43808. /**
  43809. * Returns true if alpha blending should be disabled.
  43810. */
  43811. get: function () {
  43812. return (this._linkRefractionWithTransparency ||
  43813. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43814. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43815. },
  43816. enumerable: true,
  43817. configurable: true
  43818. });
  43819. /**
  43820. * Specifies whether or not this material should be rendered in alpha blend mode.
  43821. */
  43822. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43823. if (this._disableAlphaBlending) {
  43824. return false;
  43825. }
  43826. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43827. };
  43828. /**
  43829. * Specifies if the mesh will require alpha blending.
  43830. * @param mesh - BJS mesh.
  43831. */
  43832. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43833. if (this._disableAlphaBlending) {
  43834. return false;
  43835. }
  43836. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43837. };
  43838. /**
  43839. * Specifies whether or not this material should be rendered in alpha test mode.
  43840. */
  43841. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43842. if (this._forceAlphaTest) {
  43843. return true;
  43844. }
  43845. if (this._linkRefractionWithTransparency) {
  43846. return false;
  43847. }
  43848. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43849. };
  43850. /**
  43851. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43852. */
  43853. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43854. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43855. };
  43856. /**
  43857. * Gets the texture used for the alpha test.
  43858. */
  43859. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43860. return this._albedoTexture;
  43861. };
  43862. /**
  43863. * Specifies that the submesh is ready to be used.
  43864. * @param mesh - BJS mesh.
  43865. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43866. * @param useInstances - Specifies that instances should be used.
  43867. * @returns - boolean indicating that the submesh is ready or not.
  43868. */
  43869. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43870. if (subMesh.effect && this.isFrozen) {
  43871. if (this._wasPreviouslyReady) {
  43872. return true;
  43873. }
  43874. }
  43875. if (!subMesh._materialDefines) {
  43876. subMesh._materialDefines = new PBRMaterialDefines();
  43877. }
  43878. var defines = subMesh._materialDefines;
  43879. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43880. if (defines._renderId === this.getScene().getRenderId()) {
  43881. return true;
  43882. }
  43883. }
  43884. var scene = this.getScene();
  43885. var engine = scene.getEngine();
  43886. if (defines._areTexturesDirty) {
  43887. if (scene.texturesEnabled) {
  43888. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43889. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43890. return false;
  43891. }
  43892. }
  43893. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43894. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43895. return false;
  43896. }
  43897. }
  43898. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43899. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43900. return false;
  43901. }
  43902. }
  43903. var reflectionTexture = this._getReflectionTexture();
  43904. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43905. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43906. return false;
  43907. }
  43908. }
  43909. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43910. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43911. return false;
  43912. }
  43913. }
  43914. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43915. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43916. return false;
  43917. }
  43918. }
  43919. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43920. if (this._metallicTexture) {
  43921. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43922. return false;
  43923. }
  43924. }
  43925. else if (this._reflectivityTexture) {
  43926. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43927. return false;
  43928. }
  43929. }
  43930. if (this._microSurfaceTexture) {
  43931. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43932. return false;
  43933. }
  43934. }
  43935. }
  43936. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43937. // Bump texture cannot be not blocking.
  43938. if (!this._bumpTexture.isReady()) {
  43939. return false;
  43940. }
  43941. }
  43942. var refractionTexture = this._getRefractionTexture();
  43943. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43944. if (!refractionTexture.isReadyOrNotBlocking()) {
  43945. return false;
  43946. }
  43947. }
  43948. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43949. // This is blocking.
  43950. if (!this._environmentBRDFTexture.isReady()) {
  43951. return false;
  43952. }
  43953. }
  43954. }
  43955. }
  43956. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43957. if (!this._imageProcessingConfiguration.isReady()) {
  43958. return false;
  43959. }
  43960. }
  43961. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43962. mesh.createNormals(true);
  43963. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43964. }
  43965. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43966. if (effect) {
  43967. scene.resetCachedMaterial();
  43968. subMesh.setEffect(effect, defines);
  43969. this.buildUniformLayout();
  43970. }
  43971. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43972. return false;
  43973. }
  43974. defines._renderId = scene.getRenderId();
  43975. this._wasPreviouslyReady = true;
  43976. return true;
  43977. };
  43978. /**
  43979. * Specifies if the material uses metallic roughness workflow.
  43980. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43981. */
  43982. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43983. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43984. return true;
  43985. }
  43986. return false;
  43987. };
  43988. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43989. if (onCompiled === void 0) { onCompiled = null; }
  43990. if (onError === void 0) { onError = null; }
  43991. if (useInstances === void 0) { useInstances = null; }
  43992. if (useClipPlane === void 0) { useClipPlane = null; }
  43993. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43994. if (!defines.isDirty) {
  43995. return null;
  43996. }
  43997. defines.markAsProcessed();
  43998. var scene = this.getScene();
  43999. var engine = scene.getEngine();
  44000. // Fallbacks
  44001. var fallbacks = new BABYLON.EffectFallbacks();
  44002. var fallbackRank = 0;
  44003. if (defines.USESPHERICALINVERTEX) {
  44004. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44005. }
  44006. if (defines.FOG) {
  44007. fallbacks.addFallback(fallbackRank, "FOG");
  44008. }
  44009. if (defines.SPECULARAA) {
  44010. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44011. }
  44012. if (defines.POINTSIZE) {
  44013. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44014. }
  44015. if (defines.LOGARITHMICDEPTH) {
  44016. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44017. }
  44018. if (defines.PARALLAX) {
  44019. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44020. }
  44021. if (defines.PARALLAXOCCLUSION) {
  44022. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44023. }
  44024. if (defines.ENVIRONMENTBRDF) {
  44025. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44026. }
  44027. if (defines.TANGENT) {
  44028. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44029. }
  44030. if (defines.BUMP) {
  44031. fallbacks.addFallback(fallbackRank++, "BUMP");
  44032. }
  44033. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44034. if (defines.SPECULARTERM) {
  44035. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44036. }
  44037. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44038. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44039. }
  44040. if (defines.LIGHTMAP) {
  44041. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44042. }
  44043. if (defines.NORMAL) {
  44044. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44045. }
  44046. if (defines.AMBIENT) {
  44047. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44048. }
  44049. if (defines.EMISSIVE) {
  44050. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44051. }
  44052. if (defines.VERTEXCOLOR) {
  44053. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44054. }
  44055. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44056. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44057. }
  44058. if (defines.MORPHTARGETS) {
  44059. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44060. }
  44061. //Attributes
  44062. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44063. if (defines.NORMAL) {
  44064. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44065. }
  44066. if (defines.TANGENT) {
  44067. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44068. }
  44069. if (defines.UV1) {
  44070. attribs.push(BABYLON.VertexBuffer.UVKind);
  44071. }
  44072. if (defines.UV2) {
  44073. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44074. }
  44075. if (defines.VERTEXCOLOR) {
  44076. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44077. }
  44078. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44079. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44080. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44081. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44082. "vFogInfos", "vFogColor", "pointSize",
  44083. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44084. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44085. "mBones",
  44086. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44087. "vLightingIntensity",
  44088. "logarithmicDepthConstant",
  44089. "vSphericalX", "vSphericalY", "vSphericalZ",
  44090. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44091. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44092. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44093. "vTangentSpaceParams"
  44094. ];
  44095. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44096. "bumpSampler", "lightmapSampler", "opacitySampler",
  44097. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44098. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44099. "microSurfaceSampler", "environmentBrdfSampler"];
  44100. var uniformBuffers = ["Material", "Scene"];
  44101. if (BABYLON.ImageProcessingConfiguration) {
  44102. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44103. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44104. }
  44105. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44106. uniformsNames: uniforms,
  44107. uniformBuffersNames: uniformBuffers,
  44108. samplers: samplers,
  44109. defines: defines,
  44110. maxSimultaneousLights: this._maxSimultaneousLights
  44111. });
  44112. var join = defines.toString();
  44113. return engine.createEffect("pbr", {
  44114. attributes: attribs,
  44115. uniformsNames: uniforms,
  44116. uniformBuffersNames: uniformBuffers,
  44117. samplers: samplers,
  44118. defines: join,
  44119. fallbacks: fallbacks,
  44120. onCompiled: onCompiled,
  44121. onError: onError,
  44122. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44123. }, engine);
  44124. };
  44125. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44126. if (useInstances === void 0) { useInstances = null; }
  44127. if (useClipPlane === void 0) { useClipPlane = null; }
  44128. var scene = this.getScene();
  44129. var engine = scene.getEngine();
  44130. // Lights
  44131. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44132. defines._needNormals = true;
  44133. // Textures
  44134. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44135. if (defines._areTexturesDirty) {
  44136. defines._needUVs = false;
  44137. if (scene.texturesEnabled) {
  44138. if (scene.getEngine().getCaps().textureLOD) {
  44139. defines.LODBASEDMICROSFURACE = true;
  44140. }
  44141. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44142. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44143. }
  44144. else {
  44145. defines.ALBEDO = false;
  44146. }
  44147. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44148. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44149. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44150. }
  44151. else {
  44152. defines.AMBIENT = false;
  44153. }
  44154. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44155. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44156. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44157. }
  44158. else {
  44159. defines.OPACITY = false;
  44160. }
  44161. var reflectionTexture = this._getReflectionTexture();
  44162. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44163. defines.REFLECTION = true;
  44164. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44165. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44166. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44167. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44168. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44169. defines.INVERTCUBICMAP = true;
  44170. }
  44171. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44172. switch (reflectionTexture.coordinatesMode) {
  44173. case BABYLON.Texture.EXPLICIT_MODE:
  44174. defines.REFLECTIONMAP_EXPLICIT = true;
  44175. break;
  44176. case BABYLON.Texture.PLANAR_MODE:
  44177. defines.REFLECTIONMAP_PLANAR = true;
  44178. break;
  44179. case BABYLON.Texture.PROJECTION_MODE:
  44180. defines.REFLECTIONMAP_PROJECTION = true;
  44181. break;
  44182. case BABYLON.Texture.SKYBOX_MODE:
  44183. defines.REFLECTIONMAP_SKYBOX = true;
  44184. break;
  44185. case BABYLON.Texture.SPHERICAL_MODE:
  44186. defines.REFLECTIONMAP_SPHERICAL = true;
  44187. break;
  44188. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44189. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44190. break;
  44191. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44192. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44193. break;
  44194. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44195. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44196. break;
  44197. case BABYLON.Texture.CUBIC_MODE:
  44198. case BABYLON.Texture.INVCUBIC_MODE:
  44199. default:
  44200. defines.REFLECTIONMAP_CUBIC = true;
  44201. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44202. break;
  44203. }
  44204. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44205. if (reflectionTexture.sphericalPolynomial) {
  44206. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44207. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44208. defines.USESPHERICALINVERTEX = false;
  44209. }
  44210. else {
  44211. defines.USESPHERICALINVERTEX = true;
  44212. }
  44213. }
  44214. }
  44215. else {
  44216. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  44217. }
  44218. }
  44219. else {
  44220. defines.REFLECTION = false;
  44221. defines.REFLECTIONMAP_3D = false;
  44222. defines.REFLECTIONMAP_SPHERICAL = false;
  44223. defines.REFLECTIONMAP_PLANAR = false;
  44224. defines.REFLECTIONMAP_CUBIC = false;
  44225. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44226. defines.REFLECTIONMAP_PROJECTION = false;
  44227. defines.REFLECTIONMAP_SKYBOX = false;
  44228. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44229. defines.REFLECTIONMAP_EXPLICIT = false;
  44230. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44231. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44232. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44233. defines.INVERTCUBICMAP = false;
  44234. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44235. defines.USESPHERICALINVERTEX = false;
  44236. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44237. defines.LODINREFLECTIONALPHA = false;
  44238. defines.GAMMAREFLECTION = false;
  44239. defines.RGBDREFLECTION = false;
  44240. }
  44241. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44242. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44243. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44244. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44245. }
  44246. else {
  44247. defines.LIGHTMAP = false;
  44248. }
  44249. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44250. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44251. }
  44252. else {
  44253. defines.EMISSIVE = false;
  44254. }
  44255. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44256. if (this._metallicTexture) {
  44257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44258. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44259. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44260. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44261. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44262. }
  44263. else if (this._reflectivityTexture) {
  44264. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44265. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44266. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44267. }
  44268. else {
  44269. defines.REFLECTIVITY = false;
  44270. }
  44271. if (this._microSurfaceTexture) {
  44272. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44273. }
  44274. else {
  44275. defines.MICROSURFACEMAP = false;
  44276. }
  44277. }
  44278. else {
  44279. defines.REFLECTIVITY = false;
  44280. defines.MICROSURFACEMAP = false;
  44281. }
  44282. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44283. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44284. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44285. defines.PARALLAX = true;
  44286. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44287. }
  44288. else {
  44289. defines.PARALLAX = false;
  44290. }
  44291. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44292. }
  44293. else {
  44294. defines.BUMP = false;
  44295. }
  44296. var refractionTexture = this._getRefractionTexture();
  44297. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44298. defines.REFRACTION = true;
  44299. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44300. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44301. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44302. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44303. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44304. if (this._linkRefractionWithTransparency) {
  44305. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44306. }
  44307. }
  44308. else {
  44309. defines.REFRACTION = false;
  44310. }
  44311. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44312. defines.ENVIRONMENTBRDF = true;
  44313. }
  44314. else {
  44315. defines.ENVIRONMENTBRDF = false;
  44316. }
  44317. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44318. defines.ALPHAFROMALBEDO = true;
  44319. }
  44320. else {
  44321. defines.ALPHAFROMALBEDO = false;
  44322. }
  44323. }
  44324. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44325. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44326. defines.USEPHYSICALLIGHTFALLOFF = false;
  44327. defines.USEGLTFLIGHTFALLOFF = false;
  44328. }
  44329. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44330. defines.USEPHYSICALLIGHTFALLOFF = false;
  44331. defines.USEGLTFLIGHTFALLOFF = true;
  44332. }
  44333. else {
  44334. defines.USEPHYSICALLIGHTFALLOFF = true;
  44335. defines.USEGLTFLIGHTFALLOFF = false;
  44336. }
  44337. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44338. if (!this.backFaceCulling && this._twoSidedLighting) {
  44339. defines.TWOSIDEDLIGHTING = true;
  44340. }
  44341. else {
  44342. defines.TWOSIDEDLIGHTING = false;
  44343. }
  44344. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44345. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44346. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44347. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44348. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44349. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44350. }
  44351. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44352. this._imageProcessingConfiguration.prepareDefines(defines);
  44353. }
  44354. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44355. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44356. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44357. // Misc.
  44358. if (defines._areMiscDirty) {
  44359. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44360. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44361. }
  44362. // Values that need to be evaluated on every frame
  44363. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44364. // Attribs
  44365. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44366. };
  44367. /**
  44368. * Force shader compilation
  44369. */
  44370. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44371. var _this = this;
  44372. var localOptions = __assign({ clipPlane: false }, options);
  44373. var defines = new PBRMaterialDefines();
  44374. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44375. if (effect.isReady()) {
  44376. if (onCompiled) {
  44377. onCompiled(this);
  44378. }
  44379. }
  44380. else {
  44381. effect.onCompileObservable.add(function () {
  44382. if (onCompiled) {
  44383. onCompiled(_this);
  44384. }
  44385. });
  44386. }
  44387. };
  44388. /**
  44389. * Initializes the uniform buffer layout for the shader.
  44390. */
  44391. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44392. // Order is important !
  44393. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44394. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  44395. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44396. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44397. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44398. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44399. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44400. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44401. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44402. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44403. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44404. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44405. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44406. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44407. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44408. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44409. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44410. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44411. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44412. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44413. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44414. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44415. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44416. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44417. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44418. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44419. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44420. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44421. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44422. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44423. this._uniformBuffer.addUniform("pointSize", 1);
  44424. this._uniformBuffer.create();
  44425. };
  44426. /**
  44427. * Unbinds the textures.
  44428. */
  44429. PBRBaseMaterial.prototype.unbind = function () {
  44430. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44431. this._uniformBuffer.setTexture("reflectionSampler", null);
  44432. }
  44433. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44434. this._uniformBuffer.setTexture("refractionSampler", null);
  44435. }
  44436. _super.prototype.unbind.call(this);
  44437. };
  44438. /**
  44439. * Binds the submesh data.
  44440. * @param world - The world matrix.
  44441. * @param mesh - The BJS mesh.
  44442. * @param subMesh - A submesh of the BJS mesh.
  44443. */
  44444. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44445. var scene = this.getScene();
  44446. var defines = subMesh._materialDefines;
  44447. if (!defines) {
  44448. return;
  44449. }
  44450. var effect = subMesh.effect;
  44451. if (!effect) {
  44452. return;
  44453. }
  44454. this._activeEffect = effect;
  44455. // Matrices
  44456. this.bindOnlyWorldMatrix(world);
  44457. // Normal Matrix
  44458. if (defines.OBJECTSPACE_NORMALMAP) {
  44459. world.toNormalMatrix(this._normalMatrix);
  44460. this.bindOnlyNormalMatrix(this._normalMatrix);
  44461. }
  44462. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44463. // Bones
  44464. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44465. var reflectionTexture = null;
  44466. if (mustRebind) {
  44467. this._uniformBuffer.bindToEffect(effect, "Material");
  44468. this.bindViewProjection(effect);
  44469. reflectionTexture = this._getReflectionTexture();
  44470. var refractionTexture = this._getRefractionTexture();
  44471. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44472. // Texture uniforms
  44473. if (scene.texturesEnabled) {
  44474. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44475. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44476. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44477. }
  44478. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44479. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  44480. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44481. }
  44482. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44483. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44484. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44485. }
  44486. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44487. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44488. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44489. if (reflectionTexture.boundingBoxSize) {
  44490. var cubeTexture = reflectionTexture;
  44491. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44492. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44493. }
  44494. var polynomials = reflectionTexture.sphericalPolynomial;
  44495. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44496. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44497. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44498. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44499. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44500. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44501. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44502. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44503. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44504. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44505. }
  44506. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44507. }
  44508. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44509. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44510. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44511. }
  44512. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44513. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44514. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44515. }
  44516. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44517. if (this._metallicTexture) {
  44518. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44519. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44520. }
  44521. else if (this._reflectivityTexture) {
  44522. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44523. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44524. }
  44525. if (this._microSurfaceTexture) {
  44526. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44527. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44528. }
  44529. }
  44530. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44531. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44532. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44533. if (scene._mirroredCameraPosition) {
  44534. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44535. }
  44536. else {
  44537. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44538. }
  44539. }
  44540. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44541. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44542. var depth = 1.0;
  44543. if (!refractionTexture.isCube) {
  44544. if (refractionTexture.depth) {
  44545. depth = refractionTexture.depth;
  44546. }
  44547. }
  44548. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44549. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44550. }
  44551. }
  44552. // Point size
  44553. if (this.pointsCloud) {
  44554. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44555. }
  44556. // Colors
  44557. if (defines.METALLICWORKFLOW) {
  44558. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44559. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44560. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44561. }
  44562. else {
  44563. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44564. }
  44565. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44566. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44567. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44568. // Misc
  44569. this._lightingInfos.x = this._directIntensity;
  44570. this._lightingInfos.y = this._emissiveIntensity;
  44571. this._lightingInfos.z = this._environmentIntensity;
  44572. this._lightingInfos.w = this._specularIntensity;
  44573. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44574. }
  44575. // Textures
  44576. if (scene.texturesEnabled) {
  44577. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44578. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44579. }
  44580. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44581. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44582. }
  44583. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44584. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44585. }
  44586. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44587. if (defines.LODBASEDMICROSFURACE) {
  44588. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44589. }
  44590. else {
  44591. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44592. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44593. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44594. }
  44595. }
  44596. if (defines.ENVIRONMENTBRDF) {
  44597. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44598. }
  44599. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44600. if (defines.LODBASEDMICROSFURACE) {
  44601. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44602. }
  44603. else {
  44604. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44605. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44606. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44607. }
  44608. }
  44609. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44610. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44611. }
  44612. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44613. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44614. }
  44615. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44616. if (this._metallicTexture) {
  44617. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44618. }
  44619. else if (this._reflectivityTexture) {
  44620. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44621. }
  44622. if (this._microSurfaceTexture) {
  44623. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44624. }
  44625. }
  44626. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44627. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44628. }
  44629. }
  44630. // Clip plane
  44631. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44632. // Colors
  44633. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44634. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44635. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44636. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44637. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44638. }
  44639. if (mustRebind || !this.isFrozen) {
  44640. // Lights
  44641. if (scene.lightsEnabled && !this._disableLighting) {
  44642. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44643. }
  44644. // View
  44645. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44646. this.bindView(effect);
  44647. }
  44648. // Fog
  44649. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44650. // Morph targets
  44651. if (defines.NUM_MORPH_INFLUENCERS) {
  44652. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44653. }
  44654. // image processing
  44655. this._imageProcessingConfiguration.bind(this._activeEffect);
  44656. // Log. depth
  44657. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44658. }
  44659. this._uniformBuffer.update();
  44660. this._afterBind(mesh, this._activeEffect);
  44661. };
  44662. /**
  44663. * Returns the animatable textures.
  44664. * @returns - Array of animatable textures.
  44665. */
  44666. PBRBaseMaterial.prototype.getAnimatables = function () {
  44667. var results = [];
  44668. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44669. results.push(this._albedoTexture);
  44670. }
  44671. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44672. results.push(this._ambientTexture);
  44673. }
  44674. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44675. results.push(this._opacityTexture);
  44676. }
  44677. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44678. results.push(this._reflectionTexture);
  44679. }
  44680. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44681. results.push(this._emissiveTexture);
  44682. }
  44683. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44684. results.push(this._metallicTexture);
  44685. }
  44686. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44687. results.push(this._reflectivityTexture);
  44688. }
  44689. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44690. results.push(this._bumpTexture);
  44691. }
  44692. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44693. results.push(this._lightmapTexture);
  44694. }
  44695. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44696. results.push(this._refractionTexture);
  44697. }
  44698. return results;
  44699. };
  44700. /**
  44701. * Returns the texture used for reflections.
  44702. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44703. */
  44704. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44705. if (this._reflectionTexture) {
  44706. return this._reflectionTexture;
  44707. }
  44708. return this.getScene().environmentTexture;
  44709. };
  44710. /**
  44711. * Returns the texture used for refraction or null if none is used.
  44712. * @returns - Refection texture if present. If no refraction texture and refraction
  44713. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44714. */
  44715. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44716. if (this._refractionTexture) {
  44717. return this._refractionTexture;
  44718. }
  44719. if (this._linkRefractionWithTransparency) {
  44720. return this.getScene().environmentTexture;
  44721. }
  44722. return null;
  44723. };
  44724. /**
  44725. * Disposes the resources of the material.
  44726. * @param forceDisposeEffect - Forces the disposal of effects.
  44727. * @param forceDisposeTextures - Forces the disposal of all textures.
  44728. */
  44729. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44730. if (forceDisposeTextures) {
  44731. if (this._albedoTexture) {
  44732. this._albedoTexture.dispose();
  44733. }
  44734. if (this._ambientTexture) {
  44735. this._ambientTexture.dispose();
  44736. }
  44737. if (this._opacityTexture) {
  44738. this._opacityTexture.dispose();
  44739. }
  44740. if (this._reflectionTexture) {
  44741. this._reflectionTexture.dispose();
  44742. }
  44743. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44744. this._environmentBRDFTexture.dispose();
  44745. }
  44746. if (this._emissiveTexture) {
  44747. this._emissiveTexture.dispose();
  44748. }
  44749. if (this._metallicTexture) {
  44750. this._metallicTexture.dispose();
  44751. }
  44752. if (this._reflectivityTexture) {
  44753. this._reflectivityTexture.dispose();
  44754. }
  44755. if (this._bumpTexture) {
  44756. this._bumpTexture.dispose();
  44757. }
  44758. if (this._lightmapTexture) {
  44759. this._lightmapTexture.dispose();
  44760. }
  44761. if (this._refractionTexture) {
  44762. this._refractionTexture.dispose();
  44763. }
  44764. }
  44765. this._renderTargets.dispose();
  44766. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44767. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44768. }
  44769. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44770. };
  44771. /**
  44772. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  44773. */
  44774. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  44775. /**
  44776. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  44777. * to enhance interoperability with other engines.
  44778. */
  44779. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  44780. /**
  44781. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  44782. * to enhance interoperability with other materials.
  44783. */
  44784. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  44785. /**
  44786. * Stores the reflectivity values based on metallic roughness workflow.
  44787. */
  44788. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44789. __decorate([
  44790. BABYLON.serializeAsImageProcessingConfiguration()
  44791. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44792. __decorate([
  44793. BABYLON.serialize()
  44794. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44795. __decorate([
  44796. BABYLON.serialize()
  44797. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44798. return PBRBaseMaterial;
  44799. }(BABYLON.PushMaterial));
  44800. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44801. })(BABYLON || (BABYLON = {}));
  44802. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44803. var BABYLON;
  44804. (function (BABYLON) {
  44805. /**
  44806. * The Physically based simple base material of BJS.
  44807. *
  44808. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44809. * It is used as the base class for both the specGloss and metalRough conventions.
  44810. */
  44811. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44812. __extends(PBRBaseSimpleMaterial, _super);
  44813. /**
  44814. * Instantiates a new PBRMaterial instance.
  44815. *
  44816. * @param name The material name
  44817. * @param scene The scene the material will be use in.
  44818. */
  44819. function PBRBaseSimpleMaterial(name, scene) {
  44820. var _this = _super.call(this, name, scene) || this;
  44821. /**
  44822. * Number of Simultaneous lights allowed on the material.
  44823. */
  44824. _this.maxSimultaneousLights = 4;
  44825. /**
  44826. * If sets to true, disables all the lights affecting the material.
  44827. */
  44828. _this.disableLighting = false;
  44829. /**
  44830. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44831. */
  44832. _this.invertNormalMapX = false;
  44833. /**
  44834. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44835. */
  44836. _this.invertNormalMapY = false;
  44837. /**
  44838. * Emissivie color used to self-illuminate the model.
  44839. */
  44840. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44841. /**
  44842. * Occlusion Channel Strenght.
  44843. */
  44844. _this.occlusionStrength = 1.0;
  44845. _this.useLightmapAsShadowmap = false;
  44846. _this._useAlphaFromAlbedoTexture = true;
  44847. _this._useAmbientInGrayScale = true;
  44848. return _this;
  44849. }
  44850. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44851. /**
  44852. * Gets the current double sided mode.
  44853. */
  44854. get: function () {
  44855. return this._twoSidedLighting;
  44856. },
  44857. /**
  44858. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44859. */
  44860. set: function (value) {
  44861. if (this._twoSidedLighting === value) {
  44862. return;
  44863. }
  44864. this._twoSidedLighting = value;
  44865. this.backFaceCulling = !value;
  44866. this._markAllSubMeshesAsTexturesDirty();
  44867. },
  44868. enumerable: true,
  44869. configurable: true
  44870. });
  44871. /**
  44872. * Return the active textures of the material.
  44873. */
  44874. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44875. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44876. if (this.environmentTexture) {
  44877. activeTextures.push(this.environmentTexture);
  44878. }
  44879. if (this.normalTexture) {
  44880. activeTextures.push(this.normalTexture);
  44881. }
  44882. if (this.emissiveTexture) {
  44883. activeTextures.push(this.emissiveTexture);
  44884. }
  44885. if (this.occlusionTexture) {
  44886. activeTextures.push(this.occlusionTexture);
  44887. }
  44888. if (this.lightmapTexture) {
  44889. activeTextures.push(this.lightmapTexture);
  44890. }
  44891. return activeTextures;
  44892. };
  44893. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44894. if (_super.prototype.hasTexture.call(this, texture)) {
  44895. return true;
  44896. }
  44897. if (this.lightmapTexture === texture) {
  44898. return true;
  44899. }
  44900. return false;
  44901. };
  44902. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44903. return "PBRBaseSimpleMaterial";
  44904. };
  44905. __decorate([
  44906. BABYLON.serialize(),
  44907. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44908. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44909. __decorate([
  44910. BABYLON.serialize(),
  44911. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44912. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44913. __decorate([
  44914. BABYLON.serializeAsTexture(),
  44915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44916. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44917. __decorate([
  44918. BABYLON.serialize(),
  44919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44920. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44921. __decorate([
  44922. BABYLON.serialize(),
  44923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44924. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44925. __decorate([
  44926. BABYLON.serializeAsTexture(),
  44927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44928. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44929. __decorate([
  44930. BABYLON.serializeAsColor3("emissive"),
  44931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44932. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44933. __decorate([
  44934. BABYLON.serializeAsTexture(),
  44935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44936. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44937. __decorate([
  44938. BABYLON.serialize(),
  44939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44940. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44941. __decorate([
  44942. BABYLON.serializeAsTexture(),
  44943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44944. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44945. __decorate([
  44946. BABYLON.serialize(),
  44947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44948. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44949. __decorate([
  44950. BABYLON.serialize()
  44951. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44952. __decorate([
  44953. BABYLON.serializeAsTexture(),
  44954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44955. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44956. __decorate([
  44957. BABYLON.serialize(),
  44958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44959. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44960. return PBRBaseSimpleMaterial;
  44961. }(BABYLON.PBRBaseMaterial));
  44962. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44963. })(BABYLON || (BABYLON = {}));
  44964. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44965. var BABYLON;
  44966. (function (BABYLON) {
  44967. /**
  44968. * The Physically based material of BJS.
  44969. *
  44970. * This offers the main features of a standard PBR material.
  44971. * For more information, please refer to the documentation :
  44972. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44973. */
  44974. var PBRMaterial = /** @class */ (function (_super) {
  44975. __extends(PBRMaterial, _super);
  44976. /**
  44977. * Instantiates a new PBRMaterial instance.
  44978. *
  44979. * @param name The material name
  44980. * @param scene The scene the material will be use in.
  44981. */
  44982. function PBRMaterial(name, scene) {
  44983. var _this = _super.call(this, name, scene) || this;
  44984. /**
  44985. * Intensity of the direct lights e.g. the four lights available in your scene.
  44986. * This impacts both the direct diffuse and specular highlights.
  44987. */
  44988. _this.directIntensity = 1.0;
  44989. /**
  44990. * Intensity of the emissive part of the material.
  44991. * This helps controlling the emissive effect without modifying the emissive color.
  44992. */
  44993. _this.emissiveIntensity = 1.0;
  44994. /**
  44995. * Intensity of the environment e.g. how much the environment will light the object
  44996. * either through harmonics for rough material or through the refelction for shiny ones.
  44997. */
  44998. _this.environmentIntensity = 1.0;
  44999. /**
  45000. * This is a special control allowing the reduction of the specular highlights coming from the
  45001. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45002. */
  45003. _this.specularIntensity = 1.0;
  45004. /**
  45005. * Debug Control allowing disabling the bump map on this material.
  45006. */
  45007. _this.disableBumpMap = false;
  45008. /**
  45009. * AKA Occlusion Texture Intensity in other nomenclature.
  45010. */
  45011. _this.ambientTextureStrength = 1.0;
  45012. /**
  45013. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45014. * 1 means it completely occludes it
  45015. * 0 mean it has no impact
  45016. */
  45017. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45018. /**
  45019. * The color of a material in ambient lighting.
  45020. */
  45021. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45022. /**
  45023. * AKA Diffuse Color in other nomenclature.
  45024. */
  45025. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45026. /**
  45027. * AKA Specular Color in other nomenclature.
  45028. */
  45029. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45030. /**
  45031. * The color reflected from the material.
  45032. */
  45033. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45034. /**
  45035. * The color emitted from the material.
  45036. */
  45037. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45038. /**
  45039. * AKA Glossiness in other nomenclature.
  45040. */
  45041. _this.microSurface = 1.0;
  45042. /**
  45043. * source material index of refraction (IOR)' / 'destination material IOR.
  45044. */
  45045. _this.indexOfRefraction = 0.66;
  45046. /**
  45047. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45048. */
  45049. _this.invertRefractionY = false;
  45050. /**
  45051. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45052. * Materials half opaque for instance using refraction could benefit from this control.
  45053. */
  45054. _this.linkRefractionWithTransparency = false;
  45055. _this.useLightmapAsShadowmap = false;
  45056. /**
  45057. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45058. */
  45059. _this.useAlphaFromAlbedoTexture = false;
  45060. /**
  45061. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45062. */
  45063. _this.forceAlphaTest = false;
  45064. /**
  45065. * Defines the alpha limits in alpha test mode.
  45066. */
  45067. _this.alphaCutOff = 0.4;
  45068. /**
  45069. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45070. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45071. */
  45072. _this.useSpecularOverAlpha = true;
  45073. /**
  45074. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45075. */
  45076. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45077. /**
  45078. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45079. */
  45080. _this.useRoughnessFromMetallicTextureAlpha = true;
  45081. /**
  45082. * Specifies if the metallic texture contains the roughness information in its green channel.
  45083. */
  45084. _this.useRoughnessFromMetallicTextureGreen = false;
  45085. /**
  45086. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45087. */
  45088. _this.useMetallnessFromMetallicTextureBlue = false;
  45089. /**
  45090. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45091. */
  45092. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45093. /**
  45094. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45095. */
  45096. _this.useAmbientInGrayScale = false;
  45097. /**
  45098. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45099. * The material will try to infer what glossiness each pixel should be.
  45100. */
  45101. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45102. /**
  45103. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45104. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45105. */
  45106. _this.useRadianceOverAlpha = true;
  45107. /**
  45108. * Allows using an object space normal map (instead of tangent space).
  45109. */
  45110. _this.useObjectSpaceNormalMap = false;
  45111. /**
  45112. * Allows using the bump map in parallax mode.
  45113. */
  45114. _this.useParallax = false;
  45115. /**
  45116. * Allows using the bump map in parallax occlusion mode.
  45117. */
  45118. _this.useParallaxOcclusion = false;
  45119. /**
  45120. * Controls the scale bias of the parallax mode.
  45121. */
  45122. _this.parallaxScaleBias = 0.05;
  45123. /**
  45124. * If sets to true, disables all the lights affecting the material.
  45125. */
  45126. _this.disableLighting = false;
  45127. /**
  45128. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45129. */
  45130. _this.forceIrradianceInFragment = false;
  45131. /**
  45132. * Number of Simultaneous lights allowed on the material.
  45133. */
  45134. _this.maxSimultaneousLights = 4;
  45135. /**
  45136. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45137. */
  45138. _this.invertNormalMapX = false;
  45139. /**
  45140. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45141. */
  45142. _this.invertNormalMapY = false;
  45143. /**
  45144. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45145. */
  45146. _this.twoSidedLighting = false;
  45147. /**
  45148. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45149. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45150. */
  45151. _this.useAlphaFresnel = false;
  45152. /**
  45153. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45154. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45155. */
  45156. _this.useLinearAlphaFresnel = false;
  45157. /**
  45158. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45159. * And/Or occlude the blended part.
  45160. */
  45161. _this.environmentBRDFTexture = null;
  45162. /**
  45163. * Force normal to face away from face.
  45164. */
  45165. _this.forceNormalForward = false;
  45166. /**
  45167. * Enables specular anti aliasing in the PBR shader.
  45168. * It will both interacts on the Geometry for analytical and IBL lighting.
  45169. * It also prefilter the roughness map based on the bump values.
  45170. */
  45171. _this.enableSpecularAntiAliasing = false;
  45172. /**
  45173. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45174. * makes the reflect vector face the model (under horizon).
  45175. */
  45176. _this.useHorizonOcclusion = true;
  45177. /**
  45178. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45179. * too much the area relying on ambient texture to define their ambient occlusion.
  45180. */
  45181. _this.useRadianceOcclusion = true;
  45182. /**
  45183. * If set to true, no lighting calculations will be applied.
  45184. */
  45185. _this.unlit = false;
  45186. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45187. return _this;
  45188. }
  45189. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45190. /**
  45191. * BJS is using an harcoded light falloff based on a manually sets up range.
  45192. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45193. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45194. */
  45195. get: function () {
  45196. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45197. },
  45198. /**
  45199. * BJS is using an harcoded light falloff based on a manually sets up range.
  45200. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45201. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45202. */
  45203. set: function (value) {
  45204. if (value !== this.usePhysicalLightFalloff) {
  45205. // Ensure the effect will be rebuilt.
  45206. this._markAllSubMeshesAsTexturesDirty();
  45207. if (value) {
  45208. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45209. }
  45210. else {
  45211. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45212. }
  45213. }
  45214. },
  45215. enumerable: true,
  45216. configurable: true
  45217. });
  45218. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45219. /**
  45220. * In order to support the falloff compatibility with gltf, a special mode has been added
  45221. * to reproduce the gltf light falloff.
  45222. */
  45223. get: function () {
  45224. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45225. },
  45226. /**
  45227. * In order to support the falloff compatibility with gltf, a special mode has been added
  45228. * to reproduce the gltf light falloff.
  45229. */
  45230. set: function (value) {
  45231. if (value !== this.useGLTFLightFalloff) {
  45232. // Ensure the effect will be rebuilt.
  45233. this._markAllSubMeshesAsTexturesDirty();
  45234. if (value) {
  45235. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45236. }
  45237. else {
  45238. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45239. }
  45240. }
  45241. },
  45242. enumerable: true,
  45243. configurable: true
  45244. });
  45245. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45246. /**
  45247. * Gets the image processing configuration used either in this material.
  45248. */
  45249. get: function () {
  45250. return this._imageProcessingConfiguration;
  45251. },
  45252. /**
  45253. * Sets the Default image processing configuration used either in the this material.
  45254. *
  45255. * If sets to null, the scene one is in use.
  45256. */
  45257. set: function (value) {
  45258. this._attachImageProcessingConfiguration(value);
  45259. // Ensure the effect will be rebuilt.
  45260. this._markAllSubMeshesAsTexturesDirty();
  45261. },
  45262. enumerable: true,
  45263. configurable: true
  45264. });
  45265. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45266. /**
  45267. * Gets wether the color curves effect is enabled.
  45268. */
  45269. get: function () {
  45270. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45271. },
  45272. /**
  45273. * Sets wether the color curves effect is enabled.
  45274. */
  45275. set: function (value) {
  45276. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45277. },
  45278. enumerable: true,
  45279. configurable: true
  45280. });
  45281. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45282. /**
  45283. * Gets wether the color grading effect is enabled.
  45284. */
  45285. get: function () {
  45286. return this.imageProcessingConfiguration.colorGradingEnabled;
  45287. },
  45288. /**
  45289. * Gets wether the color grading effect is enabled.
  45290. */
  45291. set: function (value) {
  45292. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45298. /**
  45299. * Gets wether tonemapping is enabled or not.
  45300. */
  45301. get: function () {
  45302. return this._imageProcessingConfiguration.toneMappingEnabled;
  45303. },
  45304. /**
  45305. * Sets wether tonemapping is enabled or not
  45306. */
  45307. set: function (value) {
  45308. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45309. },
  45310. enumerable: true,
  45311. configurable: true
  45312. });
  45313. ;
  45314. ;
  45315. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45316. /**
  45317. * The camera exposure used on this material.
  45318. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45319. * This corresponds to a photographic exposure.
  45320. */
  45321. get: function () {
  45322. return this._imageProcessingConfiguration.exposure;
  45323. },
  45324. /**
  45325. * The camera exposure used on this material.
  45326. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45327. * This corresponds to a photographic exposure.
  45328. */
  45329. set: function (value) {
  45330. this._imageProcessingConfiguration.exposure = value;
  45331. },
  45332. enumerable: true,
  45333. configurable: true
  45334. });
  45335. ;
  45336. ;
  45337. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45338. /**
  45339. * Gets The camera contrast used on this material.
  45340. */
  45341. get: function () {
  45342. return this._imageProcessingConfiguration.contrast;
  45343. },
  45344. /**
  45345. * Sets The camera contrast used on this material.
  45346. */
  45347. set: function (value) {
  45348. this._imageProcessingConfiguration.contrast = value;
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45354. /**
  45355. * Gets the Color Grading 2D Lookup Texture.
  45356. */
  45357. get: function () {
  45358. return this._imageProcessingConfiguration.colorGradingTexture;
  45359. },
  45360. /**
  45361. * Sets the Color Grading 2D Lookup Texture.
  45362. */
  45363. set: function (value) {
  45364. this._imageProcessingConfiguration.colorGradingTexture = value;
  45365. },
  45366. enumerable: true,
  45367. configurable: true
  45368. });
  45369. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45370. /**
  45371. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45372. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45373. * 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;
  45374. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45375. */
  45376. get: function () {
  45377. return this._imageProcessingConfiguration.colorCurves;
  45378. },
  45379. /**
  45380. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45381. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45382. * 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;
  45383. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45384. */
  45385. set: function (value) {
  45386. this._imageProcessingConfiguration.colorCurves = value;
  45387. },
  45388. enumerable: true,
  45389. configurable: true
  45390. });
  45391. /**
  45392. * Returns the name of this material class.
  45393. */
  45394. PBRMaterial.prototype.getClassName = function () {
  45395. return "PBRMaterial";
  45396. };
  45397. /**
  45398. * Returns an array of the actively used textures.
  45399. * @returns - Array of BaseTextures
  45400. */
  45401. PBRMaterial.prototype.getActiveTextures = function () {
  45402. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45403. if (this._albedoTexture) {
  45404. activeTextures.push(this._albedoTexture);
  45405. }
  45406. if (this._ambientTexture) {
  45407. activeTextures.push(this._ambientTexture);
  45408. }
  45409. if (this._opacityTexture) {
  45410. activeTextures.push(this._opacityTexture);
  45411. }
  45412. if (this._reflectionTexture) {
  45413. activeTextures.push(this._reflectionTexture);
  45414. }
  45415. if (this._emissiveTexture) {
  45416. activeTextures.push(this._emissiveTexture);
  45417. }
  45418. if (this._reflectivityTexture) {
  45419. activeTextures.push(this._reflectivityTexture);
  45420. }
  45421. if (this._metallicTexture) {
  45422. activeTextures.push(this._metallicTexture);
  45423. }
  45424. if (this._microSurfaceTexture) {
  45425. activeTextures.push(this._microSurfaceTexture);
  45426. }
  45427. if (this._bumpTexture) {
  45428. activeTextures.push(this._bumpTexture);
  45429. }
  45430. if (this._lightmapTexture) {
  45431. activeTextures.push(this._lightmapTexture);
  45432. }
  45433. if (this._refractionTexture) {
  45434. activeTextures.push(this._refractionTexture);
  45435. }
  45436. return activeTextures;
  45437. };
  45438. /**
  45439. * Checks to see if a texture is used in the material.
  45440. * @param texture - Base texture to use.
  45441. * @returns - Boolean specifying if a texture is used in the material.
  45442. */
  45443. PBRMaterial.prototype.hasTexture = function (texture) {
  45444. if (_super.prototype.hasTexture.call(this, texture)) {
  45445. return true;
  45446. }
  45447. if (this._albedoTexture === texture) {
  45448. return true;
  45449. }
  45450. if (this._ambientTexture === texture) {
  45451. return true;
  45452. }
  45453. if (this._opacityTexture === texture) {
  45454. return true;
  45455. }
  45456. if (this._reflectionTexture === texture) {
  45457. return true;
  45458. }
  45459. if (this._reflectivityTexture === texture) {
  45460. return true;
  45461. }
  45462. if (this._metallicTexture === texture) {
  45463. return true;
  45464. }
  45465. if (this._microSurfaceTexture === texture) {
  45466. return true;
  45467. }
  45468. if (this._bumpTexture === texture) {
  45469. return true;
  45470. }
  45471. if (this._lightmapTexture === texture) {
  45472. return true;
  45473. }
  45474. if (this._refractionTexture === texture) {
  45475. return true;
  45476. }
  45477. return false;
  45478. };
  45479. /**
  45480. * Makes a duplicate of the current material.
  45481. * @param name - name to use for the new material.
  45482. */
  45483. PBRMaterial.prototype.clone = function (name) {
  45484. var _this = this;
  45485. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45486. clone.id = name;
  45487. clone.name = name;
  45488. return clone;
  45489. };
  45490. /**
  45491. * Serializes this PBR Material.
  45492. * @returns - An object with the serialized material.
  45493. */
  45494. PBRMaterial.prototype.serialize = function () {
  45495. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45496. serializationObject.customType = "BABYLON.PBRMaterial";
  45497. return serializationObject;
  45498. };
  45499. // Statics
  45500. /**
  45501. * Parses a PBR Material from a serialized object.
  45502. * @param source - Serialized object.
  45503. * @param scene - BJS scene instance.
  45504. * @param rootUrl - url for the scene object
  45505. * @returns - PBRMaterial
  45506. */
  45507. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45508. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45509. };
  45510. /**
  45511. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45512. */
  45513. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45514. /**
  45515. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45516. */
  45517. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45518. /**
  45519. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45520. */
  45521. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45522. /**
  45523. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45524. * They are also discarded below the alpha cutoff threshold to improve performances.
  45525. */
  45526. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45527. /**
  45528. * Defines the default value of how much AO map is occluding the analytical lights
  45529. * (point spot...).
  45530. */
  45531. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  45532. __decorate([
  45533. BABYLON.serialize(),
  45534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45535. ], PBRMaterial.prototype, "directIntensity", void 0);
  45536. __decorate([
  45537. BABYLON.serialize(),
  45538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45539. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45540. __decorate([
  45541. BABYLON.serialize(),
  45542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45543. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45544. __decorate([
  45545. BABYLON.serialize(),
  45546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45547. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45548. __decorate([
  45549. BABYLON.serialize(),
  45550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45551. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45552. __decorate([
  45553. BABYLON.serializeAsTexture(),
  45554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45555. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45556. __decorate([
  45557. BABYLON.serializeAsTexture(),
  45558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45559. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45560. __decorate([
  45561. BABYLON.serialize(),
  45562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45563. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45564. __decorate([
  45565. BABYLON.serialize(),
  45566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45567. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  45568. __decorate([
  45569. BABYLON.serializeAsTexture(),
  45570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45571. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45572. __decorate([
  45573. BABYLON.serializeAsTexture(),
  45574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45575. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45576. __decorate([
  45577. BABYLON.serializeAsTexture(),
  45578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45579. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45580. __decorate([
  45581. BABYLON.serializeAsTexture(),
  45582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45583. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45584. __decorate([
  45585. BABYLON.serializeAsTexture(),
  45586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45587. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45588. __decorate([
  45589. BABYLON.serialize(),
  45590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45591. ], PBRMaterial.prototype, "metallic", void 0);
  45592. __decorate([
  45593. BABYLON.serialize(),
  45594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45595. ], PBRMaterial.prototype, "roughness", void 0);
  45596. __decorate([
  45597. BABYLON.serializeAsTexture(),
  45598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45599. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45600. __decorate([
  45601. BABYLON.serializeAsTexture(),
  45602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45603. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45604. __decorate([
  45605. BABYLON.serializeAsTexture(),
  45606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45607. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45608. __decorate([
  45609. BABYLON.serializeAsTexture(),
  45610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45611. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45612. __decorate([
  45613. BABYLON.serializeAsColor3("ambient"),
  45614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45615. ], PBRMaterial.prototype, "ambientColor", void 0);
  45616. __decorate([
  45617. BABYLON.serializeAsColor3("albedo"),
  45618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45619. ], PBRMaterial.prototype, "albedoColor", void 0);
  45620. __decorate([
  45621. BABYLON.serializeAsColor3("reflectivity"),
  45622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45623. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45624. __decorate([
  45625. BABYLON.serializeAsColor3("reflection"),
  45626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45627. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45628. __decorate([
  45629. BABYLON.serializeAsColor3("emissive"),
  45630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45631. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45632. __decorate([
  45633. BABYLON.serialize(),
  45634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45635. ], PBRMaterial.prototype, "microSurface", void 0);
  45636. __decorate([
  45637. BABYLON.serialize(),
  45638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45639. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45640. __decorate([
  45641. BABYLON.serialize(),
  45642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45643. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45644. __decorate([
  45645. BABYLON.serialize(),
  45646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45647. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45648. __decorate([
  45649. BABYLON.serialize(),
  45650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45651. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45652. __decorate([
  45653. BABYLON.serialize(),
  45654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45655. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45656. __decorate([
  45657. BABYLON.serialize(),
  45658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45659. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45660. __decorate([
  45661. BABYLON.serialize(),
  45662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45663. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45664. __decorate([
  45665. BABYLON.serialize(),
  45666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45667. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45668. __decorate([
  45669. BABYLON.serialize(),
  45670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45671. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45672. __decorate([
  45673. BABYLON.serialize(),
  45674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45675. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45676. __decorate([
  45677. BABYLON.serialize(),
  45678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45679. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45680. __decorate([
  45681. BABYLON.serialize(),
  45682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45683. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45684. __decorate([
  45685. BABYLON.serialize(),
  45686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45687. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45688. __decorate([
  45689. BABYLON.serialize(),
  45690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45691. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45692. __decorate([
  45693. BABYLON.serialize(),
  45694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45695. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45696. __decorate([
  45697. BABYLON.serialize()
  45698. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  45699. __decorate([
  45700. BABYLON.serialize()
  45701. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  45702. __decorate([
  45703. BABYLON.serialize(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45705. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45710. __decorate([
  45711. BABYLON.serialize(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "useParallax", void 0);
  45714. __decorate([
  45715. BABYLON.serialize(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45718. __decorate([
  45719. BABYLON.serialize(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45721. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45722. __decorate([
  45723. BABYLON.serialize(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45725. ], PBRMaterial.prototype, "disableLighting", void 0);
  45726. __decorate([
  45727. BABYLON.serialize(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45733. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45737. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45738. __decorate([
  45739. BABYLON.serialize(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45741. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45742. __decorate([
  45743. BABYLON.serialize(),
  45744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45745. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45746. __decorate([
  45747. BABYLON.serialize(),
  45748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45749. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45750. __decorate([
  45751. BABYLON.serialize(),
  45752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45753. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45754. __decorate([
  45755. BABYLON.serializeAsTexture(),
  45756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45757. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45758. __decorate([
  45759. BABYLON.serialize(),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45761. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45762. __decorate([
  45763. BABYLON.serialize(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45765. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45770. __decorate([
  45771. BABYLON.serialize(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45773. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45774. __decorate([
  45775. BABYLON.serialize(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45777. ], PBRMaterial.prototype, "unlit", void 0);
  45778. return PBRMaterial;
  45779. }(BABYLON.PBRBaseMaterial));
  45780. BABYLON.PBRMaterial = PBRMaterial;
  45781. })(BABYLON || (BABYLON = {}));
  45782. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45783. var BABYLON;
  45784. (function (BABYLON) {
  45785. /**
  45786. * The PBR material of BJS following the metal roughness convention.
  45787. *
  45788. * This fits to the PBR convention in the GLTF definition:
  45789. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45790. */
  45791. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45792. __extends(PBRMetallicRoughnessMaterial, _super);
  45793. /**
  45794. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45795. *
  45796. * @param name The material name
  45797. * @param scene The scene the material will be use in.
  45798. */
  45799. function PBRMetallicRoughnessMaterial(name, scene) {
  45800. var _this = _super.call(this, name, scene) || this;
  45801. _this._useRoughnessFromMetallicTextureAlpha = false;
  45802. _this._useRoughnessFromMetallicTextureGreen = true;
  45803. _this._useMetallnessFromMetallicTextureBlue = true;
  45804. _this.metallic = 1.0;
  45805. _this.roughness = 1.0;
  45806. return _this;
  45807. }
  45808. /**
  45809. * Return the currrent class name of the material.
  45810. */
  45811. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45812. return "PBRMetallicRoughnessMaterial";
  45813. };
  45814. /**
  45815. * Return the active textures of the material.
  45816. */
  45817. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45818. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45819. if (this.baseTexture) {
  45820. activeTextures.push(this.baseTexture);
  45821. }
  45822. if (this.metallicRoughnessTexture) {
  45823. activeTextures.push(this.metallicRoughnessTexture);
  45824. }
  45825. return activeTextures;
  45826. };
  45827. /**
  45828. * Checks to see if a texture is used in the material.
  45829. * @param texture - Base texture to use.
  45830. * @returns - Boolean specifying if a texture is used in the material.
  45831. */
  45832. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45833. if (_super.prototype.hasTexture.call(this, texture)) {
  45834. return true;
  45835. }
  45836. if (this.baseTexture === texture) {
  45837. return true;
  45838. }
  45839. if (this.metallicRoughnessTexture === texture) {
  45840. return true;
  45841. }
  45842. return false;
  45843. };
  45844. /**
  45845. * Makes a duplicate of the current material.
  45846. * @param name - name to use for the new material.
  45847. */
  45848. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45849. var _this = this;
  45850. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45851. clone.id = name;
  45852. clone.name = name;
  45853. return clone;
  45854. };
  45855. /**
  45856. * Serialize the material to a parsable JSON object.
  45857. */
  45858. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45859. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45860. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45861. return serializationObject;
  45862. };
  45863. /**
  45864. * Parses a JSON object correponding to the serialize function.
  45865. */
  45866. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45867. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45868. };
  45869. __decorate([
  45870. BABYLON.serializeAsColor3(),
  45871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45872. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45873. __decorate([
  45874. BABYLON.serializeAsTexture(),
  45875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45876. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45877. __decorate([
  45878. BABYLON.serialize(),
  45879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45880. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45881. __decorate([
  45882. BABYLON.serialize(),
  45883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45884. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45885. __decorate([
  45886. BABYLON.serializeAsTexture(),
  45887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45888. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45889. return PBRMetallicRoughnessMaterial;
  45890. }(BABYLON.PBRBaseSimpleMaterial));
  45891. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45892. })(BABYLON || (BABYLON = {}));
  45893. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45894. var BABYLON;
  45895. (function (BABYLON) {
  45896. /**
  45897. * The PBR material of BJS following the specular glossiness convention.
  45898. *
  45899. * This fits to the PBR convention in the GLTF definition:
  45900. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45901. */
  45902. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45903. __extends(PBRSpecularGlossinessMaterial, _super);
  45904. /**
  45905. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45906. *
  45907. * @param name The material name
  45908. * @param scene The scene the material will be use in.
  45909. */
  45910. function PBRSpecularGlossinessMaterial(name, scene) {
  45911. var _this = _super.call(this, name, scene) || this;
  45912. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45913. return _this;
  45914. }
  45915. /**
  45916. * Return the currrent class name of the material.
  45917. */
  45918. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45919. return "PBRSpecularGlossinessMaterial";
  45920. };
  45921. /**
  45922. * Return the active textures of the material.
  45923. */
  45924. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45925. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45926. if (this.diffuseTexture) {
  45927. activeTextures.push(this.diffuseTexture);
  45928. }
  45929. if (this.specularGlossinessTexture) {
  45930. activeTextures.push(this.specularGlossinessTexture);
  45931. }
  45932. return activeTextures;
  45933. };
  45934. /**
  45935. * Checks to see if a texture is used in the material.
  45936. * @param texture - Base texture to use.
  45937. * @returns - Boolean specifying if a texture is used in the material.
  45938. */
  45939. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45940. if (_super.prototype.hasTexture.call(this, texture)) {
  45941. return true;
  45942. }
  45943. if (this.diffuseTexture === texture) {
  45944. return true;
  45945. }
  45946. if (this.specularGlossinessTexture === texture) {
  45947. return true;
  45948. }
  45949. return false;
  45950. };
  45951. /**
  45952. * Makes a duplicate of the current material.
  45953. * @param name - name to use for the new material.
  45954. */
  45955. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45956. var _this = this;
  45957. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45958. clone.id = name;
  45959. clone.name = name;
  45960. return clone;
  45961. };
  45962. /**
  45963. * Serialize the material to a parsable JSON object.
  45964. */
  45965. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45966. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45967. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45968. return serializationObject;
  45969. };
  45970. /**
  45971. * Parses a JSON object correponding to the serialize function.
  45972. */
  45973. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45974. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45975. };
  45976. __decorate([
  45977. BABYLON.serializeAsColor3("diffuse"),
  45978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45979. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45980. __decorate([
  45981. BABYLON.serializeAsTexture(),
  45982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45983. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45984. __decorate([
  45985. BABYLON.serializeAsColor3("specular"),
  45986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45987. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45988. __decorate([
  45989. BABYLON.serialize(),
  45990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45991. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45992. __decorate([
  45993. BABYLON.serializeAsTexture(),
  45994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45995. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45996. return PBRSpecularGlossinessMaterial;
  45997. }(BABYLON.PBRBaseSimpleMaterial));
  45998. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45999. })(BABYLON || (BABYLON = {}));
  46000. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46001. var BABYLON;
  46002. (function (BABYLON) {
  46003. /**
  46004. * This is a list of all the different input types that are available in the application.
  46005. * Fo instance: ArcRotateCameraGamepadInput...
  46006. */
  46007. BABYLON.CameraInputTypes = {};
  46008. /**
  46009. * This represents the input manager used within a camera.
  46010. * It helps dealing with all the different kind of input attached to a camera.
  46011. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46012. */
  46013. var CameraInputsManager = /** @class */ (function () {
  46014. /**
  46015. * Instantiate a new Camera Input Manager.
  46016. * @param camera Defines the camera the input manager blongs to
  46017. */
  46018. function CameraInputsManager(camera) {
  46019. this.attached = {};
  46020. this.camera = camera;
  46021. this.checkInputs = function () { };
  46022. }
  46023. /**
  46024. * Add an input method to a camera
  46025. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46026. * @param input camera input method
  46027. */
  46028. CameraInputsManager.prototype.add = function (input) {
  46029. var type = input.getSimpleName();
  46030. if (this.attached[type]) {
  46031. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46032. return;
  46033. }
  46034. this.attached[type] = input;
  46035. input.camera = this.camera;
  46036. //for checkInputs, we are dynamically creating a function
  46037. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46038. if (input.checkInputs) {
  46039. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46040. }
  46041. if (this.attachedElement) {
  46042. input.attachControl(this.attachedElement);
  46043. }
  46044. };
  46045. /**
  46046. * Remove a specific input method from a camera
  46047. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46048. * @param inputToRemove camera input method
  46049. */
  46050. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46051. for (var cam in this.attached) {
  46052. var input = this.attached[cam];
  46053. if (input === inputToRemove) {
  46054. input.detachControl(this.attachedElement);
  46055. input.camera = null;
  46056. delete this.attached[cam];
  46057. this.rebuildInputCheck();
  46058. }
  46059. }
  46060. };
  46061. /**
  46062. * Remove a specific input type from a camera
  46063. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  46064. * @param inputType the type of the input to remove
  46065. */
  46066. CameraInputsManager.prototype.removeByType = function (inputType) {
  46067. for (var cam in this.attached) {
  46068. var input = this.attached[cam];
  46069. if (input.getClassName() === inputType) {
  46070. input.detachControl(this.attachedElement);
  46071. input.camera = null;
  46072. delete this.attached[cam];
  46073. this.rebuildInputCheck();
  46074. }
  46075. }
  46076. };
  46077. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46078. var current = this.checkInputs;
  46079. return function () {
  46080. current();
  46081. fn();
  46082. };
  46083. };
  46084. /**
  46085. * Attach the input controls to the currently attached dom element to listen the events from.
  46086. * @param input Defines the input to attach
  46087. */
  46088. CameraInputsManager.prototype.attachInput = function (input) {
  46089. if (this.attachedElement) {
  46090. input.attachControl(this.attachedElement, this.noPreventDefault);
  46091. }
  46092. };
  46093. /**
  46094. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  46095. * @param element Defines the dom element to collect the events from
  46096. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46097. */
  46098. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46099. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46100. if (this.attachedElement) {
  46101. return;
  46102. }
  46103. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46104. this.attachedElement = element;
  46105. this.noPreventDefault = noPreventDefault;
  46106. for (var cam in this.attached) {
  46107. this.attached[cam].attachControl(element, noPreventDefault);
  46108. }
  46109. };
  46110. /**
  46111. * Detach the current manager inputs controls from a specific dom element.
  46112. * @param element Defines the dom element to collect the events from
  46113. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  46114. */
  46115. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46116. if (disconnect === void 0) { disconnect = false; }
  46117. if (this.attachedElement !== element) {
  46118. return;
  46119. }
  46120. for (var cam in this.attached) {
  46121. this.attached[cam].detachControl(element);
  46122. if (disconnect) {
  46123. this.attached[cam].camera = null;
  46124. }
  46125. }
  46126. this.attachedElement = null;
  46127. };
  46128. /**
  46129. * Rebuild the dynamic inputCheck function from the current list of
  46130. * defined inputs in the manager.
  46131. */
  46132. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46133. this.checkInputs = function () { };
  46134. for (var cam in this.attached) {
  46135. var input = this.attached[cam];
  46136. if (input.checkInputs) {
  46137. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46138. }
  46139. }
  46140. };
  46141. /**
  46142. * Remove all attached input methods from a camera
  46143. */
  46144. CameraInputsManager.prototype.clear = function () {
  46145. if (this.attachedElement) {
  46146. this.detachElement(this.attachedElement, true);
  46147. }
  46148. this.attached = {};
  46149. this.attachedElement = null;
  46150. this.checkInputs = function () { };
  46151. };
  46152. /**
  46153. * Serialize the current input manager attached to a camera.
  46154. * This ensures than once parsed,
  46155. * the input associated to the camera will be identical to the current ones
  46156. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  46157. */
  46158. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46159. var inputs = {};
  46160. for (var cam in this.attached) {
  46161. var input = this.attached[cam];
  46162. var res = BABYLON.SerializationHelper.Serialize(input);
  46163. inputs[input.getClassName()] = res;
  46164. }
  46165. serializedCamera.inputsmgr = inputs;
  46166. };
  46167. /**
  46168. * Parses an input manager serialized JSON to restore the previous list of inputs
  46169. * and states associated to a camera.
  46170. * @param parsedCamera Defines the JSON to parse
  46171. */
  46172. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46173. var parsedInputs = parsedCamera.inputsmgr;
  46174. if (parsedInputs) {
  46175. this.clear();
  46176. for (var n in parsedInputs) {
  46177. var construct = BABYLON.CameraInputTypes[n];
  46178. if (construct) {
  46179. var parsedinput = parsedInputs[n];
  46180. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46181. this.add(input);
  46182. }
  46183. }
  46184. }
  46185. else {
  46186. //2016-03-08 this part is for managing backward compatibility
  46187. for (var n in this.attached) {
  46188. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46189. if (construct) {
  46190. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46191. this.remove(this.attached[n]);
  46192. this.add(input);
  46193. }
  46194. }
  46195. }
  46196. };
  46197. return CameraInputsManager;
  46198. }());
  46199. BABYLON.CameraInputsManager = CameraInputsManager;
  46200. })(BABYLON || (BABYLON = {}));
  46201. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46202. var BABYLON;
  46203. (function (BABYLON) {
  46204. /**
  46205. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  46206. * This is the base of the follow, arc rotate cameras and Free camera
  46207. * @see http://doc.babylonjs.com/features/cameras
  46208. */
  46209. var TargetCamera = /** @class */ (function (_super) {
  46210. __extends(TargetCamera, _super);
  46211. /**
  46212. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  46213. * This is the base of the follow, arc rotate cameras and Free camera
  46214. * @see http://doc.babylonjs.com/features/cameras
  46215. * @param name Defines the name of the camera in the scene
  46216. * @param position Defines the start position of the camera in the scene
  46217. * @param scene Defines the scene the camera belongs to
  46218. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  46219. */
  46220. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46221. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46222. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46223. /**
  46224. * Define the current direction the camera is moving to
  46225. */
  46226. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46227. /**
  46228. * Define the current rotation the camera is rotating to
  46229. */
  46230. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46231. /**
  46232. * Define the current rotation of the camera
  46233. */
  46234. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46235. /**
  46236. * Define the current speed of the camera
  46237. */
  46238. _this.speed = 2.0;
  46239. /**
  46240. * Add cconstraint to the camera to prevent it to move freely in all directions and
  46241. * around all axis.
  46242. */
  46243. _this.noRotationConstraint = false;
  46244. /**
  46245. * Define the current target of the camera as an object or a position.
  46246. */
  46247. _this.lockedTarget = null;
  46248. /** @hidden */
  46249. _this._currentTarget = BABYLON.Vector3.Zero();
  46250. /** @hidden */
  46251. _this._viewMatrix = BABYLON.Matrix.Zero();
  46252. /** @hidden */
  46253. _this._camMatrix = BABYLON.Matrix.Zero();
  46254. /** @hidden */
  46255. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46256. /** @hidden */
  46257. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46258. /** @hidden */
  46259. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46260. /** @hidden */
  46261. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46262. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46263. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46264. _this._defaultUp = BABYLON.Vector3.Up();
  46265. _this._cachedRotationZ = 0;
  46266. return _this;
  46267. }
  46268. /**
  46269. * Gets the position in front of the camera at a given distance.
  46270. * @param distance The distance from the camera we want the position to be
  46271. * @returns the position
  46272. */
  46273. TargetCamera.prototype.getFrontPosition = function (distance) {
  46274. this.getWorldMatrix();
  46275. var direction = this.getTarget().subtract(this.position);
  46276. direction.normalize();
  46277. direction.scaleInPlace(distance);
  46278. return this.globalPosition.add(direction);
  46279. };
  46280. /** @hidden */
  46281. TargetCamera.prototype._getLockedTargetPosition = function () {
  46282. if (!this.lockedTarget) {
  46283. return null;
  46284. }
  46285. if (this.lockedTarget.absolutePosition) {
  46286. this.lockedTarget.computeWorldMatrix();
  46287. }
  46288. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46289. };
  46290. /**
  46291. * Store current camera state of the camera (fov, position, rotation, etc..)
  46292. * @returns the camera
  46293. */
  46294. TargetCamera.prototype.storeState = function () {
  46295. this._storedPosition = this.position.clone();
  46296. this._storedRotation = this.rotation.clone();
  46297. if (this.rotationQuaternion) {
  46298. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46299. }
  46300. return _super.prototype.storeState.call(this);
  46301. };
  46302. /**
  46303. * Restored camera state. You must call storeState() first
  46304. * @returns whether it was successful or not
  46305. * @hidden
  46306. */
  46307. TargetCamera.prototype._restoreStateValues = function () {
  46308. if (!_super.prototype._restoreStateValues.call(this)) {
  46309. return false;
  46310. }
  46311. this.position = this._storedPosition.clone();
  46312. this.rotation = this._storedRotation.clone();
  46313. if (this.rotationQuaternion) {
  46314. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46315. }
  46316. this.cameraDirection.copyFromFloats(0, 0, 0);
  46317. this.cameraRotation.copyFromFloats(0, 0);
  46318. return true;
  46319. };
  46320. /** @hidden */
  46321. TargetCamera.prototype._initCache = function () {
  46322. _super.prototype._initCache.call(this);
  46323. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46324. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46325. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46326. };
  46327. /** @hidden */
  46328. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46329. if (!ignoreParentClass) {
  46330. _super.prototype._updateCache.call(this);
  46331. }
  46332. var lockedTargetPosition = this._getLockedTargetPosition();
  46333. if (!lockedTargetPosition) {
  46334. this._cache.lockedTarget = null;
  46335. }
  46336. else {
  46337. if (!this._cache.lockedTarget) {
  46338. this._cache.lockedTarget = lockedTargetPosition.clone();
  46339. }
  46340. else {
  46341. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46342. }
  46343. }
  46344. this._cache.rotation.copyFrom(this.rotation);
  46345. if (this.rotationQuaternion)
  46346. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46347. };
  46348. // Synchronized
  46349. /** @hidden */
  46350. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46351. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46352. return false;
  46353. }
  46354. var lockedTargetPosition = this._getLockedTargetPosition();
  46355. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46356. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46357. };
  46358. // Methods
  46359. /** @hidden */
  46360. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46361. var engine = this.getEngine();
  46362. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46363. };
  46364. // Target
  46365. /** @hidden */
  46366. TargetCamera.prototype.setTarget = function (target) {
  46367. this.upVector.normalize();
  46368. if (this.position.z === target.z) {
  46369. this.position.z += BABYLON.Epsilon;
  46370. }
  46371. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  46372. this._camMatrix.invert();
  46373. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46374. var vDir = target.subtract(this.position);
  46375. if (vDir.x >= 0.0) {
  46376. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46377. }
  46378. else {
  46379. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46380. }
  46381. this.rotation.z = 0;
  46382. if (isNaN(this.rotation.x)) {
  46383. this.rotation.x = 0;
  46384. }
  46385. if (isNaN(this.rotation.y)) {
  46386. this.rotation.y = 0;
  46387. }
  46388. if (isNaN(this.rotation.z)) {
  46389. this.rotation.z = 0;
  46390. }
  46391. if (this.rotationQuaternion) {
  46392. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46393. }
  46394. };
  46395. /**
  46396. * Return the current target position of the camera. This value is expressed in local space.
  46397. * @returns the target position
  46398. */
  46399. TargetCamera.prototype.getTarget = function () {
  46400. return this._currentTarget;
  46401. };
  46402. /** @hidden */
  46403. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46404. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46405. };
  46406. /** @hidden */
  46407. TargetCamera.prototype._updatePosition = function () {
  46408. if (this.parent) {
  46409. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46410. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46411. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46412. return;
  46413. }
  46414. this.position.addInPlace(this.cameraDirection);
  46415. };
  46416. /** @hidden */
  46417. TargetCamera.prototype._checkInputs = function () {
  46418. var needToMove = this._decideIfNeedsToMove();
  46419. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46420. // Move
  46421. if (needToMove) {
  46422. this._updatePosition();
  46423. }
  46424. // Rotate
  46425. if (needToRotate) {
  46426. this.rotation.x += this.cameraRotation.x;
  46427. this.rotation.y += this.cameraRotation.y;
  46428. //rotate, if quaternion is set and rotation was used
  46429. if (this.rotationQuaternion) {
  46430. var len = this.rotation.lengthSquared();
  46431. if (len) {
  46432. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46433. }
  46434. }
  46435. if (!this.noRotationConstraint) {
  46436. var limit = (Math.PI / 2) * 0.95;
  46437. if (this.rotation.x > limit)
  46438. this.rotation.x = limit;
  46439. if (this.rotation.x < -limit)
  46440. this.rotation.x = -limit;
  46441. }
  46442. }
  46443. // Inertia
  46444. if (needToMove) {
  46445. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46446. this.cameraDirection.x = 0;
  46447. }
  46448. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46449. this.cameraDirection.y = 0;
  46450. }
  46451. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46452. this.cameraDirection.z = 0;
  46453. }
  46454. this.cameraDirection.scaleInPlace(this.inertia);
  46455. }
  46456. if (needToRotate) {
  46457. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46458. this.cameraRotation.x = 0;
  46459. }
  46460. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46461. this.cameraRotation.y = 0;
  46462. }
  46463. this.cameraRotation.scaleInPlace(this.inertia);
  46464. }
  46465. _super.prototype._checkInputs.call(this);
  46466. };
  46467. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46468. if (this.rotationQuaternion) {
  46469. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46470. }
  46471. else {
  46472. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46473. }
  46474. };
  46475. /**
  46476. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46477. * @returns the current camera
  46478. */
  46479. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  46480. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  46481. return this;
  46482. };
  46483. /** @hidden */
  46484. TargetCamera.prototype._getViewMatrix = function () {
  46485. if (this.lockedTarget) {
  46486. this.setTarget(this._getLockedTargetPosition());
  46487. }
  46488. // Compute
  46489. this._updateCameraRotationMatrix();
  46490. // Apply the changed rotation to the upVector.
  46491. if (this._cachedRotationZ != this.rotation.z) {
  46492. this._rotateUpVectorWithCameraRotationMatrix();
  46493. this._cachedRotationZ = this.rotation.z;
  46494. }
  46495. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46496. // Computing target and final matrix
  46497. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46498. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46499. return this._viewMatrix;
  46500. };
  46501. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46502. if (this.parent) {
  46503. var parentWorldMatrix = this.parent.getWorldMatrix();
  46504. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46505. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46506. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46507. this._markSyncedWithParent();
  46508. }
  46509. else {
  46510. this._globalPosition.copyFrom(position);
  46511. this._globalCurrentTarget.copyFrom(target);
  46512. this._globalCurrentUpVector.copyFrom(up);
  46513. }
  46514. if (this.getScene().useRightHandedSystem) {
  46515. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46516. }
  46517. else {
  46518. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46519. }
  46520. };
  46521. /**
  46522. * @hidden
  46523. */
  46524. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46525. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46526. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46527. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46528. if (!this.rotationQuaternion) {
  46529. this.rotationQuaternion = new BABYLON.Quaternion();
  46530. }
  46531. rigCamera._cameraRigParams = {};
  46532. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46533. }
  46534. return rigCamera;
  46535. }
  46536. return null;
  46537. };
  46538. /**
  46539. * @hidden
  46540. */
  46541. TargetCamera.prototype._updateRigCameras = function () {
  46542. var camLeft = this._rigCameras[0];
  46543. var camRight = this._rigCameras[1];
  46544. switch (this.cameraRigMode) {
  46545. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46546. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46547. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46548. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46549. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46550. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46551. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46552. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46553. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46554. camLeft.setTarget(this.getTarget());
  46555. camRight.setTarget(this.getTarget());
  46556. break;
  46557. case BABYLON.Camera.RIG_MODE_VR:
  46558. if (camLeft.rotationQuaternion) {
  46559. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46560. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46561. }
  46562. else {
  46563. camLeft.rotation.copyFrom(this.rotation);
  46564. camRight.rotation.copyFrom(this.rotation);
  46565. }
  46566. camLeft.position.copyFrom(this.position);
  46567. camRight.position.copyFrom(this.position);
  46568. break;
  46569. }
  46570. _super.prototype._updateRigCameras.call(this);
  46571. };
  46572. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46573. if (!this._rigCamTransformMatrix) {
  46574. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46575. }
  46576. var target = this.getTarget();
  46577. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46578. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46579. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46580. };
  46581. /**
  46582. * Gets the current object class name.
  46583. * @return the class name
  46584. */
  46585. TargetCamera.prototype.getClassName = function () {
  46586. return "TargetCamera";
  46587. };
  46588. __decorate([
  46589. BABYLON.serializeAsVector3()
  46590. ], TargetCamera.prototype, "rotation", void 0);
  46591. __decorate([
  46592. BABYLON.serialize()
  46593. ], TargetCamera.prototype, "speed", void 0);
  46594. __decorate([
  46595. BABYLON.serializeAsMeshReference("lockedTargetId")
  46596. ], TargetCamera.prototype, "lockedTarget", void 0);
  46597. return TargetCamera;
  46598. }(BABYLON.Camera));
  46599. BABYLON.TargetCamera = TargetCamera;
  46600. })(BABYLON || (BABYLON = {}));
  46601. //# sourceMappingURL=babylon.targetCamera.js.map
  46602. var BABYLON;
  46603. (function (BABYLON) {
  46604. /**
  46605. * Manage the mouse inputs to control the movement of a free camera.
  46606. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46607. */
  46608. var FreeCameraMouseInput = /** @class */ (function () {
  46609. /**
  46610. * Manage the mouse inputs to control the movement of a free camera.
  46611. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46612. * @param touchEnabled Defines if touch is enabled or not
  46613. */
  46614. function FreeCameraMouseInput(
  46615. /**
  46616. * Define if touch is enabled in the mouse input
  46617. */
  46618. touchEnabled) {
  46619. if (touchEnabled === void 0) { touchEnabled = true; }
  46620. this.touchEnabled = touchEnabled;
  46621. /**
  46622. * Defines the buttons associated with the input to handle camera move.
  46623. */
  46624. this.buttons = [0, 1, 2];
  46625. /**
  46626. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  46627. */
  46628. this.angularSensibility = 2000.0;
  46629. this.previousPosition = null;
  46630. }
  46631. /**
  46632. * Attach the input controls to a specific dom element to get the input from.
  46633. * @param element Defines the element the controls should be listened from
  46634. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46635. */
  46636. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46637. var _this = this;
  46638. var engine = this.camera.getEngine();
  46639. if (!this._pointerInput) {
  46640. this._pointerInput = function (p, s) {
  46641. var evt = p.event;
  46642. if (engine.isInVRExclusivePointerMode) {
  46643. return;
  46644. }
  46645. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46646. return;
  46647. }
  46648. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46649. return;
  46650. }
  46651. var srcElement = (evt.srcElement || evt.target);
  46652. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46653. try {
  46654. srcElement.setPointerCapture(evt.pointerId);
  46655. }
  46656. catch (e) {
  46657. //Nothing to do with the error. Execution will continue.
  46658. }
  46659. _this.previousPosition = {
  46660. x: evt.clientX,
  46661. y: evt.clientY
  46662. };
  46663. if (!noPreventDefault) {
  46664. evt.preventDefault();
  46665. element.focus();
  46666. }
  46667. }
  46668. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46669. try {
  46670. srcElement.releasePointerCapture(evt.pointerId);
  46671. }
  46672. catch (e) {
  46673. //Nothing to do with the error.
  46674. }
  46675. _this.previousPosition = null;
  46676. if (!noPreventDefault) {
  46677. evt.preventDefault();
  46678. }
  46679. }
  46680. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46681. if (!_this.previousPosition || engine.isPointerLock) {
  46682. return;
  46683. }
  46684. var offsetX = evt.clientX - _this.previousPosition.x;
  46685. if (_this.camera.getScene().useRightHandedSystem)
  46686. offsetX *= -1;
  46687. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46688. offsetX *= -1;
  46689. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46690. var offsetY = evt.clientY - _this.previousPosition.y;
  46691. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46692. _this.previousPosition = {
  46693. x: evt.clientX,
  46694. y: evt.clientY
  46695. };
  46696. if (!noPreventDefault) {
  46697. evt.preventDefault();
  46698. }
  46699. }
  46700. };
  46701. }
  46702. this._onMouseMove = function (evt) {
  46703. if (!engine.isPointerLock) {
  46704. return;
  46705. }
  46706. if (engine.isInVRExclusivePointerMode) {
  46707. return;
  46708. }
  46709. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46710. if (_this.camera.getScene().useRightHandedSystem)
  46711. offsetX *= -1;
  46712. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46713. offsetX *= -1;
  46714. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46715. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46716. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46717. _this.previousPosition = null;
  46718. if (!noPreventDefault) {
  46719. evt.preventDefault();
  46720. }
  46721. };
  46722. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46723. element.addEventListener("mousemove", this._onMouseMove, false);
  46724. };
  46725. /**
  46726. * Detach the current controls from the specified dom element.
  46727. * @param element Defines the element to stop listening the inputs from
  46728. */
  46729. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46730. if (this._observer && element) {
  46731. this.camera.getScene().onPointerObservable.remove(this._observer);
  46732. if (this._onMouseMove) {
  46733. element.removeEventListener("mousemove", this._onMouseMove);
  46734. }
  46735. this._observer = null;
  46736. this._onMouseMove = null;
  46737. this.previousPosition = null;
  46738. }
  46739. };
  46740. /**
  46741. * Gets the class name of the current intput.
  46742. * @returns the class name
  46743. */
  46744. FreeCameraMouseInput.prototype.getClassName = function () {
  46745. return "FreeCameraMouseInput";
  46746. };
  46747. /**
  46748. * Get the friendly name associated with the input class.
  46749. * @returns the input friendly name
  46750. */
  46751. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46752. return "mouse";
  46753. };
  46754. __decorate([
  46755. BABYLON.serialize()
  46756. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46757. __decorate([
  46758. BABYLON.serialize()
  46759. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46760. return FreeCameraMouseInput;
  46761. }());
  46762. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46763. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46764. })(BABYLON || (BABYLON = {}));
  46765. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46766. var BABYLON;
  46767. (function (BABYLON) {
  46768. /**
  46769. * Manage the keyboard inputs to control the movement of a free camera.
  46770. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46771. */
  46772. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46773. function FreeCameraKeyboardMoveInput() {
  46774. /**
  46775. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  46776. */
  46777. this.keysUp = [38];
  46778. /**
  46779. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  46780. */
  46781. this.keysDown = [40];
  46782. /**
  46783. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  46784. */
  46785. this.keysLeft = [37];
  46786. /**
  46787. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  46788. */
  46789. this.keysRight = [39];
  46790. this._keys = new Array();
  46791. }
  46792. /**
  46793. * Attach the input controls to a specific dom element to get the input from.
  46794. * @param element Defines the element the controls should be listened from
  46795. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  46796. */
  46797. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46798. var _this = this;
  46799. if (this._onCanvasBlurObserver) {
  46800. return;
  46801. }
  46802. this._scene = this.camera.getScene();
  46803. this._engine = this._scene.getEngine();
  46804. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46805. _this._keys = [];
  46806. });
  46807. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46808. var evt = info.event;
  46809. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46810. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46811. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46812. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46813. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46814. var index = _this._keys.indexOf(evt.keyCode);
  46815. if (index === -1) {
  46816. _this._keys.push(evt.keyCode);
  46817. }
  46818. if (!noPreventDefault) {
  46819. evt.preventDefault();
  46820. }
  46821. }
  46822. }
  46823. else {
  46824. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46825. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46826. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46827. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46828. var index = _this._keys.indexOf(evt.keyCode);
  46829. if (index >= 0) {
  46830. _this._keys.splice(index, 1);
  46831. }
  46832. if (!noPreventDefault) {
  46833. evt.preventDefault();
  46834. }
  46835. }
  46836. }
  46837. });
  46838. };
  46839. /**
  46840. * Detach the current controls from the specified dom element.
  46841. * @param element Defines the element to stop listening the inputs from
  46842. */
  46843. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46844. if (this._scene) {
  46845. if (this._onKeyboardObserver) {
  46846. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46847. }
  46848. if (this._onCanvasBlurObserver) {
  46849. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46850. }
  46851. this._onKeyboardObserver = null;
  46852. this._onCanvasBlurObserver = null;
  46853. }
  46854. this._keys = [];
  46855. };
  46856. /**
  46857. * Update the current camera state depending on the inputs that have been used this frame.
  46858. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  46859. */
  46860. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46861. if (this._onKeyboardObserver) {
  46862. var camera = this.camera;
  46863. // Keyboard
  46864. for (var index = 0; index < this._keys.length; index++) {
  46865. var keyCode = this._keys[index];
  46866. var speed = camera._computeLocalCameraSpeed();
  46867. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46868. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46869. }
  46870. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46871. camera._localDirection.copyFromFloats(0, 0, speed);
  46872. }
  46873. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46874. camera._localDirection.copyFromFloats(speed, 0, 0);
  46875. }
  46876. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46877. camera._localDirection.copyFromFloats(0, 0, -speed);
  46878. }
  46879. if (camera.getScene().useRightHandedSystem) {
  46880. camera._localDirection.z *= -1;
  46881. }
  46882. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46883. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46884. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46885. }
  46886. }
  46887. };
  46888. /**
  46889. * Gets the class name of the current intput.
  46890. * @returns the class name
  46891. */
  46892. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46893. return "FreeCameraKeyboardMoveInput";
  46894. };
  46895. /** @hidden */
  46896. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46897. this._keys = [];
  46898. };
  46899. /**
  46900. * Get the friendly name associated with the input class.
  46901. * @returns the input friendly name
  46902. */
  46903. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46904. return "keyboard";
  46905. };
  46906. __decorate([
  46907. BABYLON.serialize()
  46908. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46909. __decorate([
  46910. BABYLON.serialize()
  46911. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46912. __decorate([
  46913. BABYLON.serialize()
  46914. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46915. __decorate([
  46916. BABYLON.serialize()
  46917. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46918. return FreeCameraKeyboardMoveInput;
  46919. }());
  46920. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46921. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46922. })(BABYLON || (BABYLON = {}));
  46923. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46924. var BABYLON;
  46925. (function (BABYLON) {
  46926. /**
  46927. * Default Inputs manager for the FreeCamera.
  46928. * It groups all the default supported inputs for ease of use.
  46929. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46930. */
  46931. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46932. __extends(FreeCameraInputsManager, _super);
  46933. /**
  46934. * Instantiates a new FreeCameraInputsManager.
  46935. * @param camera Defines the camera the inputs belong to
  46936. */
  46937. function FreeCameraInputsManager(camera) {
  46938. return _super.call(this, camera) || this;
  46939. }
  46940. /**
  46941. * Add keyboard input support to the input manager.
  46942. * @returns the current input manager
  46943. */
  46944. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46945. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46946. return this;
  46947. };
  46948. /**
  46949. * Add mouse input support to the input manager.
  46950. * @returns the current input manager
  46951. */
  46952. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46953. if (touchEnabled === void 0) { touchEnabled = true; }
  46954. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46955. return this;
  46956. };
  46957. /**
  46958. * Add orientation input support to the input manager.
  46959. * @returns the current input manager
  46960. */
  46961. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46962. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46963. return this;
  46964. };
  46965. /**
  46966. * Add touch input support to the input manager.
  46967. * @returns the current input manager
  46968. */
  46969. FreeCameraInputsManager.prototype.addTouch = function () {
  46970. this.add(new BABYLON.FreeCameraTouchInput());
  46971. return this;
  46972. };
  46973. /**
  46974. * Add virtual joystick input support to the input manager.
  46975. * @returns the current input manager
  46976. */
  46977. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46978. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46979. return this;
  46980. };
  46981. return FreeCameraInputsManager;
  46982. }(BABYLON.CameraInputsManager));
  46983. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46984. })(BABYLON || (BABYLON = {}));
  46985. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46986. var BABYLON;
  46987. (function (BABYLON) {
  46988. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  46989. // Forcing to use the Universal camera
  46990. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  46991. });
  46992. /**
  46993. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  46994. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  46995. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  46996. */
  46997. var FreeCamera = /** @class */ (function (_super) {
  46998. __extends(FreeCamera, _super);
  46999. /**
  47000. * Instantiates a Free Camera.
  47001. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  47002. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  47003. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  47004. * @param name Define the name of the camera in the scene
  47005. * @param position Define the start position of the camera in the scene
  47006. * @param scene Define the scene the camera belongs to
  47007. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47008. */
  47009. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47010. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47011. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47012. /**
  47013. * Define the collision ellipsoid of the camera.
  47014. * This is helpful to simulate a camera body like the player body around the camera
  47015. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  47016. */
  47017. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47018. /**
  47019. * Define an offset for the position of the ellipsoid around the camera.
  47020. * This can be helpful to determine the center of the body near the gravity center of the body
  47021. * instead of its head.
  47022. */
  47023. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47024. /**
  47025. * Enable or disable collisions of the camera with the rest of the scene objects.
  47026. */
  47027. _this.checkCollisions = false;
  47028. /**
  47029. * Enable or disable gravity on the camera.
  47030. */
  47031. _this.applyGravity = false;
  47032. _this._needMoveForGravity = false;
  47033. _this._oldPosition = BABYLON.Vector3.Zero();
  47034. _this._diffPosition = BABYLON.Vector3.Zero();
  47035. _this._newPosition = BABYLON.Vector3.Zero();
  47036. // Collisions
  47037. _this._collisionMask = -1;
  47038. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47039. if (collidedMesh === void 0) { collidedMesh = null; }
  47040. //TODO move this to the collision coordinator!
  47041. if (_this.getScene().workerCollisions)
  47042. newPosition.multiplyInPlace(_this._collider._radius);
  47043. var updatePosition = function (newPos) {
  47044. _this._newPosition.copyFrom(newPos);
  47045. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47046. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47047. _this.position.addInPlace(_this._diffPosition);
  47048. if (_this.onCollide && collidedMesh) {
  47049. _this.onCollide(collidedMesh);
  47050. }
  47051. }
  47052. };
  47053. updatePosition(newPosition);
  47054. };
  47055. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47056. _this.inputs.addKeyboard().addMouse();
  47057. return _this;
  47058. }
  47059. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47060. /**
  47061. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47062. * Higher values reduce sensitivity.
  47063. */
  47064. get: function () {
  47065. var mouse = this.inputs.attached["mouse"];
  47066. if (mouse)
  47067. return mouse.angularSensibility;
  47068. return 0;
  47069. },
  47070. /**
  47071. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47072. * Higher values reduce sensitivity.
  47073. */
  47074. set: function (value) {
  47075. var mouse = this.inputs.attached["mouse"];
  47076. if (mouse)
  47077. mouse.angularSensibility = value;
  47078. },
  47079. enumerable: true,
  47080. configurable: true
  47081. });
  47082. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47083. /**
  47084. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  47085. */
  47086. get: function () {
  47087. var keyboard = this.inputs.attached["keyboard"];
  47088. if (keyboard)
  47089. return keyboard.keysUp;
  47090. return [];
  47091. },
  47092. set: function (value) {
  47093. var keyboard = this.inputs.attached["keyboard"];
  47094. if (keyboard)
  47095. keyboard.keysUp = value;
  47096. },
  47097. enumerable: true,
  47098. configurable: true
  47099. });
  47100. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47101. /**
  47102. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  47103. */
  47104. get: function () {
  47105. var keyboard = this.inputs.attached["keyboard"];
  47106. if (keyboard)
  47107. return keyboard.keysDown;
  47108. return [];
  47109. },
  47110. set: function (value) {
  47111. var keyboard = this.inputs.attached["keyboard"];
  47112. if (keyboard)
  47113. keyboard.keysDown = value;
  47114. },
  47115. enumerable: true,
  47116. configurable: true
  47117. });
  47118. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47119. /**
  47120. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  47121. */
  47122. get: function () {
  47123. var keyboard = this.inputs.attached["keyboard"];
  47124. if (keyboard)
  47125. return keyboard.keysLeft;
  47126. return [];
  47127. },
  47128. set: function (value) {
  47129. var keyboard = this.inputs.attached["keyboard"];
  47130. if (keyboard)
  47131. keyboard.keysLeft = value;
  47132. },
  47133. enumerable: true,
  47134. configurable: true
  47135. });
  47136. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47137. /**
  47138. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  47139. */
  47140. get: function () {
  47141. var keyboard = this.inputs.attached["keyboard"];
  47142. if (keyboard)
  47143. return keyboard.keysRight;
  47144. return [];
  47145. },
  47146. set: function (value) {
  47147. var keyboard = this.inputs.attached["keyboard"];
  47148. if (keyboard)
  47149. keyboard.keysRight = value;
  47150. },
  47151. enumerable: true,
  47152. configurable: true
  47153. });
  47154. /**
  47155. * Attached controls to the current camera.
  47156. * @param element Defines the element the controls should be listened from
  47157. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47158. */
  47159. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47160. this.inputs.attachElement(element, noPreventDefault);
  47161. };
  47162. /**
  47163. * Detach the current controls from the camera.
  47164. * The camera will stop reacting to inputs.
  47165. * @param element Defines the element to stop listening the inputs from
  47166. */
  47167. FreeCamera.prototype.detachControl = function (element) {
  47168. this.inputs.detachElement(element);
  47169. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47170. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47171. };
  47172. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47173. /**
  47174. * Define a collision mask to limit the list of object the camera can collide with
  47175. */
  47176. get: function () {
  47177. return this._collisionMask;
  47178. },
  47179. set: function (mask) {
  47180. this._collisionMask = !isNaN(mask) ? mask : -1;
  47181. },
  47182. enumerable: true,
  47183. configurable: true
  47184. });
  47185. /** @hidden */
  47186. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47187. var globalPosition;
  47188. if (this.parent) {
  47189. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47190. }
  47191. else {
  47192. globalPosition = this.position;
  47193. }
  47194. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47195. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47196. if (!this._collider) {
  47197. this._collider = new BABYLON.Collider();
  47198. }
  47199. this._collider._radius = this.ellipsoid;
  47200. this._collider.collisionMask = this._collisionMask;
  47201. //no need for clone, as long as gravity is not on.
  47202. var actualDisplacement = displacement;
  47203. //add gravity to the direction to prevent the dual-collision checking
  47204. if (this.applyGravity) {
  47205. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47206. actualDisplacement = displacement.add(this.getScene().gravity);
  47207. }
  47208. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47209. };
  47210. /** @hidden */
  47211. FreeCamera.prototype._checkInputs = function () {
  47212. if (!this._localDirection) {
  47213. this._localDirection = BABYLON.Vector3.Zero();
  47214. this._transformedDirection = BABYLON.Vector3.Zero();
  47215. }
  47216. this.inputs.checkInputs();
  47217. _super.prototype._checkInputs.call(this);
  47218. };
  47219. /** @hidden */
  47220. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47221. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47222. };
  47223. /** @hidden */
  47224. FreeCamera.prototype._updatePosition = function () {
  47225. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47226. this._collideWithWorld(this.cameraDirection);
  47227. }
  47228. else {
  47229. _super.prototype._updatePosition.call(this);
  47230. }
  47231. };
  47232. /**
  47233. * Destroy the camera and release the current resources hold by it.
  47234. */
  47235. FreeCamera.prototype.dispose = function () {
  47236. this.inputs.clear();
  47237. _super.prototype.dispose.call(this);
  47238. };
  47239. /**
  47240. * Gets the current object class name.
  47241. * @return the class name
  47242. */
  47243. FreeCamera.prototype.getClassName = function () {
  47244. return "FreeCamera";
  47245. };
  47246. __decorate([
  47247. BABYLON.serializeAsVector3()
  47248. ], FreeCamera.prototype, "ellipsoid", void 0);
  47249. __decorate([
  47250. BABYLON.serializeAsVector3()
  47251. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47252. __decorate([
  47253. BABYLON.serialize()
  47254. ], FreeCamera.prototype, "checkCollisions", void 0);
  47255. __decorate([
  47256. BABYLON.serialize()
  47257. ], FreeCamera.prototype, "applyGravity", void 0);
  47258. return FreeCamera;
  47259. }(BABYLON.TargetCamera));
  47260. BABYLON.FreeCamera = FreeCamera;
  47261. })(BABYLON || (BABYLON = {}));
  47262. //# sourceMappingURL=babylon.freeCamera.js.map
  47263. var BABYLON;
  47264. (function (BABYLON) {
  47265. /**
  47266. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  47267. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47268. */
  47269. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47270. function ArcRotateCameraKeyboardMoveInput() {
  47271. /**
  47272. * Defines the list of key codes associated with the up action (increase alpha)
  47273. */
  47274. this.keysUp = [38];
  47275. /**
  47276. * Defines the list of key codes associated with the down action (decrease alpha)
  47277. */
  47278. this.keysDown = [40];
  47279. /**
  47280. * Defines the list of key codes associated with the left action (increase beta)
  47281. */
  47282. this.keysLeft = [37];
  47283. /**
  47284. * Defines the list of key codes associated with the right action (decrease beta)
  47285. */
  47286. this.keysRight = [39];
  47287. /**
  47288. * Defines the list of key codes associated with the reset action.
  47289. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  47290. */
  47291. this.keysReset = [220];
  47292. /**
  47293. * Defines the panning sensibility of the inputs.
  47294. * (How fast is the camera paning)
  47295. */
  47296. this.panningSensibility = 50.0;
  47297. /**
  47298. * Defines the zooming sensibility of the inputs.
  47299. * (How fast is the camera zooming)
  47300. */
  47301. this.zoomingSensibility = 25.0;
  47302. /**
  47303. * Defines wether maintaining the alt key down switch the movement mode from
  47304. * orientation to zoom.
  47305. */
  47306. this.useAltToZoom = true;
  47307. this._keys = new Array();
  47308. }
  47309. /**
  47310. * Attach the input controls to a specific dom element to get the input from.
  47311. * @param element Defines the element the controls should be listened from
  47312. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47313. */
  47314. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47315. var _this = this;
  47316. if (this._onCanvasBlurObserver) {
  47317. return;
  47318. }
  47319. this._scene = this.camera.getScene();
  47320. this._engine = this._scene.getEngine();
  47321. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47322. _this._keys = [];
  47323. });
  47324. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47325. var evt = info.event;
  47326. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47327. _this._ctrlPressed = evt.ctrlKey;
  47328. _this._altPressed = evt.altKey;
  47329. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47330. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47331. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47332. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47333. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47334. var index = _this._keys.indexOf(evt.keyCode);
  47335. if (index === -1) {
  47336. _this._keys.push(evt.keyCode);
  47337. }
  47338. if (evt.preventDefault) {
  47339. if (!noPreventDefault) {
  47340. evt.preventDefault();
  47341. }
  47342. }
  47343. }
  47344. }
  47345. else {
  47346. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47347. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47348. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47349. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47350. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47351. var index = _this._keys.indexOf(evt.keyCode);
  47352. if (index >= 0) {
  47353. _this._keys.splice(index, 1);
  47354. }
  47355. if (evt.preventDefault) {
  47356. if (!noPreventDefault) {
  47357. evt.preventDefault();
  47358. }
  47359. }
  47360. }
  47361. }
  47362. });
  47363. };
  47364. /**
  47365. * Detach the current controls from the specified dom element.
  47366. * @param element Defines the element to stop listening the inputs from
  47367. */
  47368. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47369. if (this._scene) {
  47370. if (this._onKeyboardObserver) {
  47371. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47372. }
  47373. if (this._onCanvasBlurObserver) {
  47374. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47375. }
  47376. this._onKeyboardObserver = null;
  47377. this._onCanvasBlurObserver = null;
  47378. }
  47379. this._keys = [];
  47380. };
  47381. /**
  47382. * Update the current camera state depending on the inputs that have been used this frame.
  47383. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  47384. */
  47385. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47386. if (this._onKeyboardObserver) {
  47387. var camera = this.camera;
  47388. for (var index = 0; index < this._keys.length; index++) {
  47389. var keyCode = this._keys[index];
  47390. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47391. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47392. camera.inertialPanningX -= 1 / this.panningSensibility;
  47393. }
  47394. else {
  47395. camera.inertialAlphaOffset -= 0.01;
  47396. }
  47397. }
  47398. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47399. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47400. camera.inertialPanningY += 1 / this.panningSensibility;
  47401. }
  47402. else if (this._altPressed && this.useAltToZoom) {
  47403. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47404. }
  47405. else {
  47406. camera.inertialBetaOffset -= 0.01;
  47407. }
  47408. }
  47409. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47410. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47411. camera.inertialPanningX += 1 / this.panningSensibility;
  47412. }
  47413. else {
  47414. camera.inertialAlphaOffset += 0.01;
  47415. }
  47416. }
  47417. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47418. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47419. camera.inertialPanningY -= 1 / this.panningSensibility;
  47420. }
  47421. else if (this._altPressed && this.useAltToZoom) {
  47422. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47423. }
  47424. else {
  47425. camera.inertialBetaOffset += 0.01;
  47426. }
  47427. }
  47428. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47429. camera.restoreState();
  47430. }
  47431. }
  47432. }
  47433. };
  47434. /**
  47435. * Gets the class name of the current intput.
  47436. * @returns the class name
  47437. */
  47438. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47439. return "ArcRotateCameraKeyboardMoveInput";
  47440. };
  47441. /**
  47442. * Get the friendly name associated with the input class.
  47443. * @returns the input friendly name
  47444. */
  47445. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47446. return "keyboard";
  47447. };
  47448. __decorate([
  47449. BABYLON.serialize()
  47450. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47451. __decorate([
  47452. BABYLON.serialize()
  47453. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47454. __decorate([
  47455. BABYLON.serialize()
  47456. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47457. __decorate([
  47458. BABYLON.serialize()
  47459. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47460. __decorate([
  47461. BABYLON.serialize()
  47462. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47463. __decorate([
  47464. BABYLON.serialize()
  47465. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47466. __decorate([
  47467. BABYLON.serialize()
  47468. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47469. __decorate([
  47470. BABYLON.serialize()
  47471. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47472. return ArcRotateCameraKeyboardMoveInput;
  47473. }());
  47474. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47475. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47476. })(BABYLON || (BABYLON = {}));
  47477. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47478. var BABYLON;
  47479. (function (BABYLON) {
  47480. /**
  47481. * Manage the mouse wheel inputs to control an arc rotate camera.
  47482. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47483. */
  47484. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47485. function ArcRotateCameraMouseWheelInput() {
  47486. /**
  47487. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  47488. */
  47489. this.wheelPrecision = 3.0;
  47490. /**
  47491. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47492. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47493. */
  47494. this.wheelDeltaPercentage = 0;
  47495. }
  47496. /**
  47497. * Attach the input controls to a specific dom element to get the input from.
  47498. * @param element Defines the element the controls should be listened from
  47499. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47500. */
  47501. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47502. var _this = this;
  47503. this._wheel = function (p, s) {
  47504. //sanity check - this should be a PointerWheel event.
  47505. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47506. return;
  47507. var event = p.event;
  47508. var delta = 0;
  47509. if (event.wheelDelta) {
  47510. if (_this.wheelDeltaPercentage) {
  47511. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47512. if (event.wheelDelta > 0) {
  47513. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47514. }
  47515. else {
  47516. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47517. }
  47518. }
  47519. else {
  47520. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47521. }
  47522. }
  47523. else if (event.detail) {
  47524. delta = -event.detail / _this.wheelPrecision;
  47525. }
  47526. if (delta)
  47527. _this.camera.inertialRadiusOffset += delta;
  47528. if (event.preventDefault) {
  47529. if (!noPreventDefault) {
  47530. event.preventDefault();
  47531. }
  47532. }
  47533. };
  47534. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47535. };
  47536. /**
  47537. * Detach the current controls from the specified dom element.
  47538. * @param element Defines the element to stop listening the inputs from
  47539. */
  47540. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47541. if (this._observer && element) {
  47542. this.camera.getScene().onPointerObservable.remove(this._observer);
  47543. this._observer = null;
  47544. this._wheel = null;
  47545. }
  47546. };
  47547. /**
  47548. * Gets the class name of the current intput.
  47549. * @returns the class name
  47550. */
  47551. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47552. return "ArcRotateCameraMouseWheelInput";
  47553. };
  47554. /**
  47555. * Get the friendly name associated with the input class.
  47556. * @returns the input friendly name
  47557. */
  47558. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47559. return "mousewheel";
  47560. };
  47561. __decorate([
  47562. BABYLON.serialize()
  47563. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47564. __decorate([
  47565. BABYLON.serialize()
  47566. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47567. return ArcRotateCameraMouseWheelInput;
  47568. }());
  47569. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47570. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47571. })(BABYLON || (BABYLON = {}));
  47572. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47573. var BABYLON;
  47574. (function (BABYLON) {
  47575. /**
  47576. * Manage the pointers inputs to control an arc rotate camera.
  47577. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47578. */
  47579. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47580. function ArcRotateCameraPointersInput() {
  47581. /**
  47582. * Defines the buttons associated with the input to handle camera move.
  47583. */
  47584. this.buttons = [0, 1, 2];
  47585. /**
  47586. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  47587. */
  47588. this.angularSensibilityX = 1000.0;
  47589. /**
  47590. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  47591. */
  47592. this.angularSensibilityY = 1000.0;
  47593. /**
  47594. * Defines the pointer pinch precision or how fast is the camera zooming.
  47595. */
  47596. this.pinchPrecision = 12.0;
  47597. /**
  47598. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47599. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47600. */
  47601. this.pinchDeltaPercentage = 0;
  47602. /**
  47603. * Defines the pointer panning sensibility or how fast is the camera moving.
  47604. */
  47605. this.panningSensibility = 1000.0;
  47606. /**
  47607. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  47608. */
  47609. this.multiTouchPanning = true;
  47610. /**
  47611. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  47612. */
  47613. this.multiTouchPanAndZoom = true;
  47614. /**
  47615. * Revers pinch action direction.
  47616. */
  47617. this.pinchInwards = true;
  47618. this._isPanClick = false;
  47619. }
  47620. /**
  47621. * Attach the input controls to a specific dom element to get the input from.
  47622. * @param element Defines the element the controls should be listened from
  47623. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47624. */
  47625. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47626. var _this = this;
  47627. var engine = this.camera.getEngine();
  47628. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47629. var pointA = null;
  47630. var pointB = null;
  47631. var previousPinchSquaredDistance = 0;
  47632. var initialDistance = 0;
  47633. var twoFingerActivityCount = 0;
  47634. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47635. this._pointerInput = function (p, s) {
  47636. var evt = p.event;
  47637. var isTouch = p.event.pointerType === "touch";
  47638. if (engine.isInVRExclusivePointerMode) {
  47639. return;
  47640. }
  47641. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47642. return;
  47643. }
  47644. var srcElement = (evt.srcElement || evt.target);
  47645. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47646. try {
  47647. srcElement.setPointerCapture(evt.pointerId);
  47648. }
  47649. catch (e) {
  47650. //Nothing to do with the error. Execution will continue.
  47651. }
  47652. // Manage panning with pan button click
  47653. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47654. // manage pointers
  47655. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47656. if (pointA === null) {
  47657. pointA = cacheSoloPointer;
  47658. }
  47659. else if (pointB === null) {
  47660. pointB = cacheSoloPointer;
  47661. }
  47662. if (!noPreventDefault) {
  47663. evt.preventDefault();
  47664. element.focus();
  47665. }
  47666. }
  47667. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47668. _this.camera.restoreState();
  47669. }
  47670. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47671. try {
  47672. srcElement.releasePointerCapture(evt.pointerId);
  47673. }
  47674. catch (e) {
  47675. //Nothing to do with the error.
  47676. }
  47677. cacheSoloPointer = null;
  47678. previousPinchSquaredDistance = 0;
  47679. previousMultiTouchPanPosition.isPaning = false;
  47680. previousMultiTouchPanPosition.isPinching = false;
  47681. twoFingerActivityCount = 0;
  47682. initialDistance = 0;
  47683. if (!isTouch) {
  47684. pointB = null; // Mouse and pen are mono pointer
  47685. }
  47686. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47687. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47688. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47689. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47690. if (engine._badOS) {
  47691. pointA = pointB = null;
  47692. }
  47693. else {
  47694. //only remove the impacted pointer in case of multitouch allowing on most
  47695. //platforms switching from rotate to zoom and pan seamlessly.
  47696. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47697. pointA = pointB;
  47698. pointB = null;
  47699. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47700. }
  47701. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47702. pointB = null;
  47703. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47704. }
  47705. else {
  47706. pointA = pointB = null;
  47707. }
  47708. }
  47709. if (!noPreventDefault) {
  47710. evt.preventDefault();
  47711. }
  47712. }
  47713. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47714. if (!noPreventDefault) {
  47715. evt.preventDefault();
  47716. }
  47717. // One button down
  47718. if (pointA && pointB === null && cacheSoloPointer) {
  47719. if (_this.panningSensibility !== 0 &&
  47720. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47721. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47722. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47723. }
  47724. else {
  47725. var offsetX = evt.clientX - cacheSoloPointer.x;
  47726. var offsetY = evt.clientY - cacheSoloPointer.y;
  47727. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47728. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47729. }
  47730. cacheSoloPointer.x = evt.clientX;
  47731. cacheSoloPointer.y = evt.clientY;
  47732. }
  47733. // Two buttons down: pinch/pan
  47734. else if (pointA && pointB) {
  47735. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47736. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47737. ed.x = evt.clientX;
  47738. ed.y = evt.clientY;
  47739. var direction = _this.pinchInwards ? 1 : -1;
  47740. var distX = pointA.x - pointB.x;
  47741. var distY = pointA.y - pointB.y;
  47742. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47743. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47744. if (previousPinchSquaredDistance === 0) {
  47745. initialDistance = pinchDistance;
  47746. previousPinchSquaredDistance = pinchSquaredDistance;
  47747. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47748. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47749. return;
  47750. }
  47751. if (_this.multiTouchPanAndZoom) {
  47752. if (_this.pinchDeltaPercentage) {
  47753. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47754. }
  47755. else {
  47756. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47757. (_this.pinchPrecision *
  47758. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47759. direction);
  47760. }
  47761. if (_this.panningSensibility !== 0) {
  47762. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47763. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47764. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47765. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47766. previousMultiTouchPanPosition.x = pointersCenterX;
  47767. previousMultiTouchPanPosition.y = pointersCenterY;
  47768. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47769. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47770. }
  47771. }
  47772. else {
  47773. twoFingerActivityCount++;
  47774. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47775. if (_this.pinchDeltaPercentage) {
  47776. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47777. }
  47778. else {
  47779. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47780. (_this.pinchPrecision *
  47781. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47782. direction);
  47783. }
  47784. previousMultiTouchPanPosition.isPaning = false;
  47785. previousMultiTouchPanPosition.isPinching = true;
  47786. }
  47787. else {
  47788. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47789. if (!previousMultiTouchPanPosition.isPaning) {
  47790. previousMultiTouchPanPosition.isPaning = true;
  47791. previousMultiTouchPanPosition.isPinching = false;
  47792. previousMultiTouchPanPosition.x = ed.x;
  47793. previousMultiTouchPanPosition.y = ed.y;
  47794. return;
  47795. }
  47796. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47797. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47798. }
  47799. }
  47800. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47801. previousMultiTouchPanPosition.x = ed.x;
  47802. previousMultiTouchPanPosition.y = ed.y;
  47803. }
  47804. }
  47805. previousPinchSquaredDistance = pinchSquaredDistance;
  47806. }
  47807. }
  47808. };
  47809. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47810. this._onContextMenu = function (evt) {
  47811. evt.preventDefault();
  47812. };
  47813. if (!this.camera._useCtrlForPanning) {
  47814. element.addEventListener("contextmenu", this._onContextMenu, false);
  47815. }
  47816. this._onLostFocus = function () {
  47817. //this._keys = [];
  47818. pointA = pointB = null;
  47819. previousPinchSquaredDistance = 0;
  47820. previousMultiTouchPanPosition.isPaning = false;
  47821. previousMultiTouchPanPosition.isPinching = false;
  47822. twoFingerActivityCount = 0;
  47823. cacheSoloPointer = null;
  47824. initialDistance = 0;
  47825. };
  47826. this._onMouseMove = function (evt) {
  47827. if (!engine.isPointerLock) {
  47828. return;
  47829. }
  47830. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47831. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47832. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47833. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47834. if (!noPreventDefault) {
  47835. evt.preventDefault();
  47836. }
  47837. };
  47838. this._onGestureStart = function (e) {
  47839. if (window.MSGesture === undefined) {
  47840. return;
  47841. }
  47842. if (!_this._MSGestureHandler) {
  47843. _this._MSGestureHandler = new MSGesture();
  47844. _this._MSGestureHandler.target = element;
  47845. }
  47846. _this._MSGestureHandler.addPointer(e.pointerId);
  47847. };
  47848. this._onGesture = function (e) {
  47849. _this.camera.radius *= e.scale;
  47850. if (e.preventDefault) {
  47851. if (!noPreventDefault) {
  47852. e.stopPropagation();
  47853. e.preventDefault();
  47854. }
  47855. }
  47856. };
  47857. element.addEventListener("mousemove", this._onMouseMove, false);
  47858. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47859. element.addEventListener("MSGestureChange", this._onGesture, false);
  47860. BABYLON.Tools.RegisterTopRootEvents([
  47861. { name: "blur", handler: this._onLostFocus }
  47862. ]);
  47863. };
  47864. /**
  47865. * Detach the current controls from the specified dom element.
  47866. * @param element Defines the element to stop listening the inputs from
  47867. */
  47868. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47869. if (this._onLostFocus) {
  47870. BABYLON.Tools.UnregisterTopRootEvents([
  47871. { name: "blur", handler: this._onLostFocus }
  47872. ]);
  47873. }
  47874. if (element && this._observer) {
  47875. this.camera.getScene().onPointerObservable.remove(this._observer);
  47876. this._observer = null;
  47877. if (this._onContextMenu) {
  47878. element.removeEventListener("contextmenu", this._onContextMenu);
  47879. }
  47880. if (this._onMouseMove) {
  47881. element.removeEventListener("mousemove", this._onMouseMove);
  47882. }
  47883. if (this._onGestureStart) {
  47884. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47885. }
  47886. if (this._onGesture) {
  47887. element.removeEventListener("MSGestureChange", this._onGesture);
  47888. }
  47889. this._isPanClick = false;
  47890. this.pinchInwards = true;
  47891. this._onMouseMove = null;
  47892. this._onGestureStart = null;
  47893. this._onGesture = null;
  47894. this._MSGestureHandler = null;
  47895. this._onLostFocus = null;
  47896. this._onContextMenu = null;
  47897. }
  47898. };
  47899. /**
  47900. * Gets the class name of the current intput.
  47901. * @returns the class name
  47902. */
  47903. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47904. return "ArcRotateCameraPointersInput";
  47905. };
  47906. /**
  47907. * Get the friendly name associated with the input class.
  47908. * @returns the input friendly name
  47909. */
  47910. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47911. return "pointers";
  47912. };
  47913. __decorate([
  47914. BABYLON.serialize()
  47915. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47916. __decorate([
  47917. BABYLON.serialize()
  47918. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47919. __decorate([
  47920. BABYLON.serialize()
  47921. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47922. __decorate([
  47923. BABYLON.serialize()
  47924. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47925. __decorate([
  47926. BABYLON.serialize()
  47927. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47928. __decorate([
  47929. BABYLON.serialize()
  47930. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47931. __decorate([
  47932. BABYLON.serialize()
  47933. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47934. __decorate([
  47935. BABYLON.serialize()
  47936. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47937. return ArcRotateCameraPointersInput;
  47938. }());
  47939. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47940. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47941. })(BABYLON || (BABYLON = {}));
  47942. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47943. var BABYLON;
  47944. (function (BABYLON) {
  47945. /**
  47946. * Default Inputs manager for the ArcRotateCamera.
  47947. * It groups all the default supported inputs for ease of use.
  47948. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47949. */
  47950. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47951. __extends(ArcRotateCameraInputsManager, _super);
  47952. /**
  47953. * Instantiates a new ArcRotateCameraInputsManager.
  47954. * @param camera Defines the camera the inputs belong to
  47955. */
  47956. function ArcRotateCameraInputsManager(camera) {
  47957. return _super.call(this, camera) || this;
  47958. }
  47959. /**
  47960. * Add mouse wheel input support to the input manager.
  47961. * @returns the current input manager
  47962. */
  47963. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47964. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47965. return this;
  47966. };
  47967. /**
  47968. * Add pointers input support to the input manager.
  47969. * @returns the current input manager
  47970. */
  47971. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47972. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47973. return this;
  47974. };
  47975. /**
  47976. * Add keyboard input support to the input manager.
  47977. * @returns the current input manager
  47978. */
  47979. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47980. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47981. return this;
  47982. };
  47983. /**
  47984. * Add orientation input support to the input manager.
  47985. * @returns the current input manager
  47986. */
  47987. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47988. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47989. return this;
  47990. };
  47991. return ArcRotateCameraInputsManager;
  47992. }(BABYLON.CameraInputsManager));
  47993. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47994. })(BABYLON || (BABYLON = {}));
  47995. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47996. var BABYLON;
  47997. (function (BABYLON) {
  47998. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47999. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  48000. });
  48001. /**
  48002. * This represents an orbital type of camera.
  48003. *
  48004. * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
  48005. * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
  48006. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  48007. */
  48008. var ArcRotateCamera = /** @class */ (function (_super) {
  48009. __extends(ArcRotateCamera, _super);
  48010. /**
  48011. * Instantiates a new ArcRotateCamera in a given scene
  48012. * @param name Defines the name of the camera
  48013. * @param alpha Defines the camera rotation along the logitudinal axis
  48014. * @param beta Defines the camera rotation along the latitudinal axis
  48015. * @param radius Defines the camera distance from its target
  48016. * @param target Defines the camera target
  48017. * @param scene Defines the scene the camera belongs to
  48018. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48019. */
  48020. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48021. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48022. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48023. /**
  48024. * Current inertia value on the longitudinal axis.
  48025. * The bigger this number the longer it will take for the camera to stop.
  48026. */
  48027. _this.inertialAlphaOffset = 0;
  48028. /**
  48029. * Current inertia value on the latitudinal axis.
  48030. * The bigger this number the longer it will take for the camera to stop.
  48031. */
  48032. _this.inertialBetaOffset = 0;
  48033. /**
  48034. * Current inertia value on the radius axis.
  48035. * The bigger this number the longer it will take for the camera to stop.
  48036. */
  48037. _this.inertialRadiusOffset = 0;
  48038. /**
  48039. * Minimum allowed angle on the longitudinal axis.
  48040. * This can help limiting how the Camera is able to move in the scene.
  48041. */
  48042. _this.lowerAlphaLimit = null;
  48043. /**
  48044. * Maximum allowed angle on the longitudinal axis.
  48045. * This can help limiting how the Camera is able to move in the scene.
  48046. */
  48047. _this.upperAlphaLimit = null;
  48048. /**
  48049. * Minimum allowed angle on the latitudinal axis.
  48050. * This can help limiting how the Camera is able to move in the scene.
  48051. */
  48052. _this.lowerBetaLimit = 0.01;
  48053. /**
  48054. * Maximum allowed angle on the latitudinal axis.
  48055. * This can help limiting how the Camera is able to move in the scene.
  48056. */
  48057. _this.upperBetaLimit = Math.PI;
  48058. /**
  48059. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  48060. * This can help limiting how the Camera is able to move in the scene.
  48061. */
  48062. _this.lowerRadiusLimit = null;
  48063. /**
  48064. * Maximum allowed distance of the camera to the target (The camera can not get further).
  48065. * This can help limiting how the Camera is able to move in the scene.
  48066. */
  48067. _this.upperRadiusLimit = null;
  48068. /**
  48069. * Defines the current inertia value used during panning of the camera along the X axis.
  48070. */
  48071. _this.inertialPanningX = 0;
  48072. /**
  48073. * Defines the current inertia value used during panning of the camera along the Y axis.
  48074. */
  48075. _this.inertialPanningY = 0;
  48076. /**
  48077. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  48078. * Basically if your fingers moves away from more than this distance you will be considered
  48079. * in pinch mode.
  48080. */
  48081. _this.pinchToPanMaxDistance = 20;
  48082. /**
  48083. * Defines the maximum distance the camera can pan.
  48084. * This could help keeping the cammera always in your scene.
  48085. */
  48086. _this.panningDistanceLimit = null;
  48087. /**
  48088. * Defines the target of the camera before paning.
  48089. */
  48090. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48091. /**
  48092. * Defines the value of the inertia used during panning.
  48093. * 0 would mean stop inertia and one would mean no decelleration at all.
  48094. */
  48095. _this.panningInertia = 0.9;
  48096. //-- end properties for backward compatibility for inputs
  48097. /**
  48098. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  48099. */
  48100. _this.zoomOnFactor = 1;
  48101. /**
  48102. * Defines a screen offset for the camera position.
  48103. */
  48104. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48105. /**
  48106. * Allows the camera to be completely reversed.
  48107. * If false the camera can not arrive upside down.
  48108. */
  48109. _this.allowUpsideDown = true;
  48110. /** @hidden */
  48111. _this._viewMatrix = new BABYLON.Matrix();
  48112. /**
  48113. * Defines the allowed panning axis.
  48114. */
  48115. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48116. /**
  48117. * Observable triggered when the mesh target has been changed on the camera.
  48118. */
  48119. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48120. /**
  48121. * Defines whether the camera should check collision with the objects oh the scene.
  48122. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  48123. */
  48124. _this.checkCollisions = false;
  48125. /**
  48126. * Defines the collision radius of the camera.
  48127. * This simulates a sphere around the camera.
  48128. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48129. */
  48130. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48131. _this._previousPosition = BABYLON.Vector3.Zero();
  48132. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48133. _this._newPosition = BABYLON.Vector3.Zero();
  48134. _this._computationVector = BABYLON.Vector3.Zero();
  48135. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48136. if (collidedMesh === void 0) { collidedMesh = null; }
  48137. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48138. newPosition.multiplyInPlace(_this._collider._radius);
  48139. }
  48140. if (!collidedMesh) {
  48141. _this._previousPosition.copyFrom(_this.position);
  48142. }
  48143. else {
  48144. _this.setPosition(newPosition);
  48145. if (_this.onCollide) {
  48146. _this.onCollide(collidedMesh);
  48147. }
  48148. }
  48149. // Recompute because of constraints
  48150. var cosa = Math.cos(_this.alpha);
  48151. var sina = Math.sin(_this.alpha);
  48152. var cosb = Math.cos(_this.beta);
  48153. var sinb = Math.sin(_this.beta);
  48154. if (sinb === 0) {
  48155. sinb = 0.0001;
  48156. }
  48157. var target = _this._getTargetPosition();
  48158. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48159. target.addToRef(_this._computationVector, _this._newPosition);
  48160. _this.position.copyFrom(_this._newPosition);
  48161. var up = _this.upVector;
  48162. if (_this.allowUpsideDown && _this.beta < 0) {
  48163. up = up.clone();
  48164. up = up.negate();
  48165. }
  48166. _this._computeViewMatrix(_this.position, target, up);
  48167. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48168. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48169. _this._collisionTriggered = false;
  48170. };
  48171. _this._target = BABYLON.Vector3.Zero();
  48172. if (target) {
  48173. _this.setTarget(target);
  48174. }
  48175. _this.alpha = alpha;
  48176. _this.beta = beta;
  48177. _this.radius = radius;
  48178. _this.getViewMatrix();
  48179. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48180. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48181. return _this;
  48182. }
  48183. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48184. /**
  48185. * Defines the target point of the camera.
  48186. * The camera looks towards it form the radius distance.
  48187. */
  48188. get: function () {
  48189. return this._target;
  48190. },
  48191. set: function (value) {
  48192. this.setTarget(value);
  48193. },
  48194. enumerable: true,
  48195. configurable: true
  48196. });
  48197. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48198. //-- begin properties for backward compatibility for inputs
  48199. /**
  48200. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  48201. */
  48202. get: function () {
  48203. var pointers = this.inputs.attached["pointers"];
  48204. if (pointers)
  48205. return pointers.angularSensibilityX;
  48206. return 0;
  48207. },
  48208. set: function (value) {
  48209. var pointers = this.inputs.attached["pointers"];
  48210. if (pointers) {
  48211. pointers.angularSensibilityX = value;
  48212. }
  48213. },
  48214. enumerable: true,
  48215. configurable: true
  48216. });
  48217. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48218. /**
  48219. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  48220. */
  48221. get: function () {
  48222. var pointers = this.inputs.attached["pointers"];
  48223. if (pointers)
  48224. return pointers.angularSensibilityY;
  48225. return 0;
  48226. },
  48227. set: function (value) {
  48228. var pointers = this.inputs.attached["pointers"];
  48229. if (pointers) {
  48230. pointers.angularSensibilityY = value;
  48231. }
  48232. },
  48233. enumerable: true,
  48234. configurable: true
  48235. });
  48236. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48237. /**
  48238. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  48239. */
  48240. get: function () {
  48241. var pointers = this.inputs.attached["pointers"];
  48242. if (pointers)
  48243. return pointers.pinchPrecision;
  48244. return 0;
  48245. },
  48246. set: function (value) {
  48247. var pointers = this.inputs.attached["pointers"];
  48248. if (pointers) {
  48249. pointers.pinchPrecision = value;
  48250. }
  48251. },
  48252. enumerable: true,
  48253. configurable: true
  48254. });
  48255. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48256. /**
  48257. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  48258. * It will be used instead of pinchDeltaPrecision if different from 0.
  48259. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48260. */
  48261. get: function () {
  48262. var pointers = this.inputs.attached["pointers"];
  48263. if (pointers)
  48264. return pointers.pinchDeltaPercentage;
  48265. return 0;
  48266. },
  48267. set: function (value) {
  48268. var pointers = this.inputs.attached["pointers"];
  48269. if (pointers) {
  48270. pointers.pinchDeltaPercentage = value;
  48271. }
  48272. },
  48273. enumerable: true,
  48274. configurable: true
  48275. });
  48276. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48277. /**
  48278. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  48279. */
  48280. get: function () {
  48281. var pointers = this.inputs.attached["pointers"];
  48282. if (pointers)
  48283. return pointers.panningSensibility;
  48284. return 0;
  48285. },
  48286. set: function (value) {
  48287. var pointers = this.inputs.attached["pointers"];
  48288. if (pointers) {
  48289. pointers.panningSensibility = value;
  48290. }
  48291. },
  48292. enumerable: true,
  48293. configurable: true
  48294. });
  48295. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48296. /**
  48297. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  48298. */
  48299. get: function () {
  48300. var keyboard = this.inputs.attached["keyboard"];
  48301. if (keyboard)
  48302. return keyboard.keysUp;
  48303. return [];
  48304. },
  48305. set: function (value) {
  48306. var keyboard = this.inputs.attached["keyboard"];
  48307. if (keyboard)
  48308. keyboard.keysUp = value;
  48309. },
  48310. enumerable: true,
  48311. configurable: true
  48312. });
  48313. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48314. /**
  48315. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  48316. */
  48317. get: function () {
  48318. var keyboard = this.inputs.attached["keyboard"];
  48319. if (keyboard)
  48320. return keyboard.keysDown;
  48321. return [];
  48322. },
  48323. set: function (value) {
  48324. var keyboard = this.inputs.attached["keyboard"];
  48325. if (keyboard)
  48326. keyboard.keysDown = value;
  48327. },
  48328. enumerable: true,
  48329. configurable: true
  48330. });
  48331. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48332. /**
  48333. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  48334. */
  48335. get: function () {
  48336. var keyboard = this.inputs.attached["keyboard"];
  48337. if (keyboard)
  48338. return keyboard.keysLeft;
  48339. return [];
  48340. },
  48341. set: function (value) {
  48342. var keyboard = this.inputs.attached["keyboard"];
  48343. if (keyboard)
  48344. keyboard.keysLeft = value;
  48345. },
  48346. enumerable: true,
  48347. configurable: true
  48348. });
  48349. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48350. /**
  48351. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  48352. */
  48353. get: function () {
  48354. var keyboard = this.inputs.attached["keyboard"];
  48355. if (keyboard)
  48356. return keyboard.keysRight;
  48357. return [];
  48358. },
  48359. set: function (value) {
  48360. var keyboard = this.inputs.attached["keyboard"];
  48361. if (keyboard)
  48362. keyboard.keysRight = value;
  48363. },
  48364. enumerable: true,
  48365. configurable: true
  48366. });
  48367. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48368. /**
  48369. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  48370. */
  48371. get: function () {
  48372. var mousewheel = this.inputs.attached["mousewheel"];
  48373. if (mousewheel)
  48374. return mousewheel.wheelPrecision;
  48375. return 0;
  48376. },
  48377. set: function (value) {
  48378. var mousewheel = this.inputs.attached["mousewheel"];
  48379. if (mousewheel)
  48380. mousewheel.wheelPrecision = value;
  48381. },
  48382. enumerable: true,
  48383. configurable: true
  48384. });
  48385. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48386. /**
  48387. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  48388. * It will be used instead of pinchDeltaPrecision if different from 0.
  48389. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48390. */
  48391. get: function () {
  48392. var mousewheel = this.inputs.attached["mousewheel"];
  48393. if (mousewheel)
  48394. return mousewheel.wheelDeltaPercentage;
  48395. return 0;
  48396. },
  48397. set: function (value) {
  48398. var mousewheel = this.inputs.attached["mousewheel"];
  48399. if (mousewheel)
  48400. mousewheel.wheelDeltaPercentage = value;
  48401. },
  48402. enumerable: true,
  48403. configurable: true
  48404. });
  48405. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48406. /**
  48407. * Gets the bouncing behavior of the camera if it has been enabled.
  48408. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48409. */
  48410. get: function () {
  48411. return this._bouncingBehavior;
  48412. },
  48413. enumerable: true,
  48414. configurable: true
  48415. });
  48416. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48417. /**
  48418. * Defines if the bouncing behavior of the camera is enabled on the camera.
  48419. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  48420. */
  48421. get: function () {
  48422. return this._bouncingBehavior != null;
  48423. },
  48424. set: function (value) {
  48425. if (value === this.useBouncingBehavior) {
  48426. return;
  48427. }
  48428. if (value) {
  48429. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48430. this.addBehavior(this._bouncingBehavior);
  48431. }
  48432. else if (this._bouncingBehavior) {
  48433. this.removeBehavior(this._bouncingBehavior);
  48434. this._bouncingBehavior = null;
  48435. }
  48436. },
  48437. enumerable: true,
  48438. configurable: true
  48439. });
  48440. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48441. /**
  48442. * Gets the framing behavior of the camera if it has been enabled.
  48443. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48444. */
  48445. get: function () {
  48446. return this._framingBehavior;
  48447. },
  48448. enumerable: true,
  48449. configurable: true
  48450. });
  48451. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48452. /**
  48453. * Defines if the framing behavior of the camera is enabled on the camera.
  48454. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  48455. */
  48456. get: function () {
  48457. return this._framingBehavior != null;
  48458. },
  48459. set: function (value) {
  48460. if (value === this.useFramingBehavior) {
  48461. return;
  48462. }
  48463. if (value) {
  48464. this._framingBehavior = new BABYLON.FramingBehavior();
  48465. this.addBehavior(this._framingBehavior);
  48466. }
  48467. else if (this._framingBehavior) {
  48468. this.removeBehavior(this._framingBehavior);
  48469. this._framingBehavior = null;
  48470. }
  48471. },
  48472. enumerable: true,
  48473. configurable: true
  48474. });
  48475. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48476. /**
  48477. * Gets the auto rotation behavior of the camera if it has been enabled.
  48478. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48479. */
  48480. get: function () {
  48481. return this._autoRotationBehavior;
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48487. /**
  48488. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  48489. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  48490. */
  48491. get: function () {
  48492. return this._autoRotationBehavior != null;
  48493. },
  48494. set: function (value) {
  48495. if (value === this.useAutoRotationBehavior) {
  48496. return;
  48497. }
  48498. if (value) {
  48499. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48500. this.addBehavior(this._autoRotationBehavior);
  48501. }
  48502. else if (this._autoRotationBehavior) {
  48503. this.removeBehavior(this._autoRotationBehavior);
  48504. this._autoRotationBehavior = null;
  48505. }
  48506. },
  48507. enumerable: true,
  48508. configurable: true
  48509. });
  48510. // Cache
  48511. /** @hidden */
  48512. ArcRotateCamera.prototype._initCache = function () {
  48513. _super.prototype._initCache.call(this);
  48514. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48515. this._cache.alpha = undefined;
  48516. this._cache.beta = undefined;
  48517. this._cache.radius = undefined;
  48518. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48519. };
  48520. /** @hidden */
  48521. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48522. if (!ignoreParentClass) {
  48523. _super.prototype._updateCache.call(this);
  48524. }
  48525. this._cache._target.copyFrom(this._getTargetPosition());
  48526. this._cache.alpha = this.alpha;
  48527. this._cache.beta = this.beta;
  48528. this._cache.radius = this.radius;
  48529. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48530. };
  48531. ArcRotateCamera.prototype._getTargetPosition = function () {
  48532. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48533. var pos = this._targetHost.getAbsolutePosition();
  48534. if (this._targetBoundingCenter) {
  48535. pos.addToRef(this._targetBoundingCenter, this._target);
  48536. }
  48537. else {
  48538. this._target.copyFrom(pos);
  48539. }
  48540. }
  48541. var lockedTargetPosition = this._getLockedTargetPosition();
  48542. if (lockedTargetPosition) {
  48543. return lockedTargetPosition;
  48544. }
  48545. return this._target;
  48546. };
  48547. /**
  48548. * Stores the current state of the camera (alpha, beta, radius and target)
  48549. * @returns the camera itself
  48550. */
  48551. ArcRotateCamera.prototype.storeState = function () {
  48552. this._storedAlpha = this.alpha;
  48553. this._storedBeta = this.beta;
  48554. this._storedRadius = this.radius;
  48555. this._storedTarget = this._getTargetPosition().clone();
  48556. return _super.prototype.storeState.call(this);
  48557. };
  48558. /**
  48559. * @hidden
  48560. * Restored camera state. You must call storeState() first
  48561. */
  48562. ArcRotateCamera.prototype._restoreStateValues = function () {
  48563. if (!_super.prototype._restoreStateValues.call(this)) {
  48564. return false;
  48565. }
  48566. this.alpha = this._storedAlpha;
  48567. this.beta = this._storedBeta;
  48568. this.radius = this._storedRadius;
  48569. this.setTarget(this._storedTarget.clone());
  48570. this.inertialAlphaOffset = 0;
  48571. this.inertialBetaOffset = 0;
  48572. this.inertialRadiusOffset = 0;
  48573. this.inertialPanningX = 0;
  48574. this.inertialPanningY = 0;
  48575. return true;
  48576. };
  48577. // Synchronized
  48578. /** @hidden */
  48579. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48580. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48581. return false;
  48582. return this._cache._target.equals(this._getTargetPosition())
  48583. && this._cache.alpha === this.alpha
  48584. && this._cache.beta === this.beta
  48585. && this._cache.radius === this.radius
  48586. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48587. };
  48588. /**
  48589. * Attached controls to the current camera.
  48590. * @param element Defines the element the controls should be listened from
  48591. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48592. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  48593. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  48594. */
  48595. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48596. var _this = this;
  48597. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48598. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48599. this._useCtrlForPanning = useCtrlForPanning;
  48600. this._panningMouseButton = panningMouseButton;
  48601. this.inputs.attachElement(element, noPreventDefault);
  48602. this._reset = function () {
  48603. _this.inertialAlphaOffset = 0;
  48604. _this.inertialBetaOffset = 0;
  48605. _this.inertialRadiusOffset = 0;
  48606. _this.inertialPanningX = 0;
  48607. _this.inertialPanningY = 0;
  48608. };
  48609. };
  48610. /**
  48611. * Detach the current controls from the camera.
  48612. * The camera will stop reacting to inputs.
  48613. * @param element Defines the element to stop listening the inputs from
  48614. */
  48615. ArcRotateCamera.prototype.detachControl = function (element) {
  48616. this.inputs.detachElement(element);
  48617. if (this._reset) {
  48618. this._reset();
  48619. }
  48620. };
  48621. /** @hidden */
  48622. ArcRotateCamera.prototype._checkInputs = function () {
  48623. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48624. if (this._collisionTriggered) {
  48625. return;
  48626. }
  48627. this.inputs.checkInputs();
  48628. // Inertia
  48629. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48630. var inertialAlphaOffset = this.inertialAlphaOffset;
  48631. if (this.beta <= 0)
  48632. inertialAlphaOffset *= -1;
  48633. if (this.getScene().useRightHandedSystem)
  48634. inertialAlphaOffset *= -1;
  48635. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48636. inertialAlphaOffset *= -1;
  48637. this.alpha += inertialAlphaOffset;
  48638. this.beta += this.inertialBetaOffset;
  48639. this.radius -= this.inertialRadiusOffset;
  48640. this.inertialAlphaOffset *= this.inertia;
  48641. this.inertialBetaOffset *= this.inertia;
  48642. this.inertialRadiusOffset *= this.inertia;
  48643. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48644. this.inertialAlphaOffset = 0;
  48645. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48646. this.inertialBetaOffset = 0;
  48647. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48648. this.inertialRadiusOffset = 0;
  48649. }
  48650. // Panning inertia
  48651. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48652. if (!this._localDirection) {
  48653. this._localDirection = BABYLON.Vector3.Zero();
  48654. this._transformedDirection = BABYLON.Vector3.Zero();
  48655. }
  48656. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48657. this._localDirection.multiplyInPlace(this.panningAxis);
  48658. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48659. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48660. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48661. if (!this.panningAxis.y) {
  48662. this._transformedDirection.y = 0;
  48663. }
  48664. if (!this._targetHost) {
  48665. if (this.panningDistanceLimit) {
  48666. this._transformedDirection.addInPlace(this._target);
  48667. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48668. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48669. this._target.copyFrom(this._transformedDirection);
  48670. }
  48671. }
  48672. else {
  48673. this._target.addInPlace(this._transformedDirection);
  48674. }
  48675. }
  48676. this.inertialPanningX *= this.panningInertia;
  48677. this.inertialPanningY *= this.panningInertia;
  48678. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48679. this.inertialPanningX = 0;
  48680. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48681. this.inertialPanningY = 0;
  48682. }
  48683. // Limits
  48684. this._checkLimits();
  48685. _super.prototype._checkInputs.call(this);
  48686. };
  48687. ArcRotateCamera.prototype._checkLimits = function () {
  48688. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48689. if (this.allowUpsideDown && this.beta > Math.PI) {
  48690. this.beta = this.beta - (2 * Math.PI);
  48691. }
  48692. }
  48693. else {
  48694. if (this.beta < this.lowerBetaLimit) {
  48695. this.beta = this.lowerBetaLimit;
  48696. }
  48697. }
  48698. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48699. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48700. this.beta = this.beta + (2 * Math.PI);
  48701. }
  48702. }
  48703. else {
  48704. if (this.beta > this.upperBetaLimit) {
  48705. this.beta = this.upperBetaLimit;
  48706. }
  48707. }
  48708. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48709. this.alpha = this.lowerAlphaLimit;
  48710. }
  48711. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48712. this.alpha = this.upperAlphaLimit;
  48713. }
  48714. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48715. this.radius = this.lowerRadiusLimit;
  48716. }
  48717. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48718. this.radius = this.upperRadiusLimit;
  48719. }
  48720. };
  48721. /**
  48722. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  48723. */
  48724. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48725. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48726. this.radius = this._computationVector.length();
  48727. if (this.radius === 0) {
  48728. this.radius = 0.0001; // Just to avoid division by zero
  48729. }
  48730. // Alpha
  48731. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48732. if (this._computationVector.z < 0) {
  48733. this.alpha = 2 * Math.PI - this.alpha;
  48734. }
  48735. // Beta
  48736. this.beta = Math.acos(this._computationVector.y / this.radius);
  48737. this._checkLimits();
  48738. };
  48739. /**
  48740. * Use a position to define the current camera related information like aplha, beta and radius
  48741. * @param position Defines the position to set the camera at
  48742. */
  48743. ArcRotateCamera.prototype.setPosition = function (position) {
  48744. if (this.position.equals(position)) {
  48745. return;
  48746. }
  48747. this.position.copyFrom(position);
  48748. this.rebuildAnglesAndRadius();
  48749. };
  48750. /**
  48751. * Defines the target the camera should look at.
  48752. * This will automatically adapt alpha beta and radius to fit within the new target.
  48753. * @param target Defines the new target as a Vector or a mesh
  48754. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  48755. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  48756. */
  48757. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48758. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48759. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48760. if (target.getBoundingInfo) {
  48761. if (toBoundingCenter) {
  48762. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48763. }
  48764. else {
  48765. this._targetBoundingCenter = null;
  48766. }
  48767. this._targetHost = target;
  48768. this._target = this._getTargetPosition();
  48769. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48770. }
  48771. else {
  48772. var newTarget = target;
  48773. var currentTarget = this._getTargetPosition();
  48774. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48775. return;
  48776. }
  48777. this._targetHost = null;
  48778. this._target = newTarget;
  48779. this._targetBoundingCenter = null;
  48780. this.onMeshTargetChangedObservable.notifyObservers(null);
  48781. }
  48782. this.rebuildAnglesAndRadius();
  48783. };
  48784. /** @hidden */
  48785. ArcRotateCamera.prototype._getViewMatrix = function () {
  48786. // Compute
  48787. var cosa = Math.cos(this.alpha);
  48788. var sina = Math.sin(this.alpha);
  48789. var cosb = Math.cos(this.beta);
  48790. var sinb = Math.sin(this.beta);
  48791. if (sinb === 0) {
  48792. sinb = 0.0001;
  48793. }
  48794. var target = this._getTargetPosition();
  48795. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48796. target.addToRef(this._computationVector, this._newPosition);
  48797. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48798. if (!this._collider) {
  48799. this._collider = new BABYLON.Collider();
  48800. }
  48801. this._collider._radius = this.collisionRadius;
  48802. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48803. this._collisionTriggered = true;
  48804. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48805. }
  48806. else {
  48807. this.position.copyFrom(this._newPosition);
  48808. var up = this.upVector;
  48809. if (this.allowUpsideDown && sinb < 0) {
  48810. up = up.clone();
  48811. up = up.negate();
  48812. }
  48813. this._computeViewMatrix(this.position, target, up);
  48814. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48815. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48816. }
  48817. this._currentTarget = target;
  48818. return this._viewMatrix;
  48819. };
  48820. /**
  48821. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  48822. * @param meshes Defines the mesh to zoom on
  48823. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48824. */
  48825. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48826. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48827. meshes = meshes || this.getScene().meshes;
  48828. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48829. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48830. this.radius = distance * this.zoomOnFactor;
  48831. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48832. };
  48833. /**
  48834. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  48835. * The target will be changed but the radius
  48836. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  48837. * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
  48838. */
  48839. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48840. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48841. var meshesOrMinMaxVector;
  48842. var distance;
  48843. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48844. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48845. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48846. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48847. }
  48848. else { //minMaxVector and distance
  48849. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48850. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48851. distance = minMaxVectorAndDistance.distance;
  48852. }
  48853. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48854. if (!doNotUpdateMaxZ) {
  48855. this.maxZ = distance * 2;
  48856. }
  48857. };
  48858. /**
  48859. * @override
  48860. * Override Camera.createRigCamera
  48861. */
  48862. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48863. var alphaShift = 0;
  48864. switch (this.cameraRigMode) {
  48865. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48866. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48867. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48868. case BABYLON.Camera.RIG_MODE_VR:
  48869. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48870. break;
  48871. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48872. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48873. break;
  48874. }
  48875. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48876. rigCam._cameraRigParams = {};
  48877. return rigCam;
  48878. };
  48879. /**
  48880. * @hidden
  48881. * @override
  48882. * Override Camera._updateRigCameras
  48883. */
  48884. ArcRotateCamera.prototype._updateRigCameras = function () {
  48885. var camLeft = this._rigCameras[0];
  48886. var camRight = this._rigCameras[1];
  48887. camLeft.beta = camRight.beta = this.beta;
  48888. camLeft.radius = camRight.radius = this.radius;
  48889. switch (this.cameraRigMode) {
  48890. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48893. case BABYLON.Camera.RIG_MODE_VR:
  48894. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48895. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48896. break;
  48897. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48898. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48899. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48900. break;
  48901. }
  48902. _super.prototype._updateRigCameras.call(this);
  48903. };
  48904. /**
  48905. * Destroy the camera and release the current resources hold by it.
  48906. */
  48907. ArcRotateCamera.prototype.dispose = function () {
  48908. this.inputs.clear();
  48909. _super.prototype.dispose.call(this);
  48910. };
  48911. /**
  48912. * Gets the current object class name.
  48913. * @return the class name
  48914. */
  48915. ArcRotateCamera.prototype.getClassName = function () {
  48916. return "ArcRotateCamera";
  48917. };
  48918. __decorate([
  48919. BABYLON.serialize()
  48920. ], ArcRotateCamera.prototype, "alpha", void 0);
  48921. __decorate([
  48922. BABYLON.serialize()
  48923. ], ArcRotateCamera.prototype, "beta", void 0);
  48924. __decorate([
  48925. BABYLON.serialize()
  48926. ], ArcRotateCamera.prototype, "radius", void 0);
  48927. __decorate([
  48928. BABYLON.serializeAsVector3("target")
  48929. ], ArcRotateCamera.prototype, "_target", void 0);
  48930. __decorate([
  48931. BABYLON.serialize()
  48932. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48933. __decorate([
  48934. BABYLON.serialize()
  48935. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48936. __decorate([
  48937. BABYLON.serialize()
  48938. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48939. __decorate([
  48940. BABYLON.serialize()
  48941. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48942. __decorate([
  48943. BABYLON.serialize()
  48944. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48945. __decorate([
  48946. BABYLON.serialize()
  48947. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48948. __decorate([
  48949. BABYLON.serialize()
  48950. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48951. __decorate([
  48952. BABYLON.serialize()
  48953. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48954. __decorate([
  48955. BABYLON.serialize()
  48956. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48957. __decorate([
  48958. BABYLON.serialize()
  48959. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48960. __decorate([
  48961. BABYLON.serialize()
  48962. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48963. __decorate([
  48964. BABYLON.serialize()
  48965. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48966. __decorate([
  48967. BABYLON.serialize()
  48968. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48969. __decorate([
  48970. BABYLON.serializeAsVector3()
  48971. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48972. __decorate([
  48973. BABYLON.serialize()
  48974. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48975. __decorate([
  48976. BABYLON.serialize()
  48977. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48978. __decorate([
  48979. BABYLON.serialize()
  48980. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  48981. __decorate([
  48982. BABYLON.serialize()
  48983. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48984. return ArcRotateCamera;
  48985. }(BABYLON.TargetCamera));
  48986. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48987. })(BABYLON || (BABYLON = {}));
  48988. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48989. var BABYLON;
  48990. (function (BABYLON) {
  48991. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48992. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48993. });
  48994. /**
  48995. * The HemisphericLight simulates the ambient environment light,
  48996. * so the passed direction is the light reflection direction, not the incoming direction.
  48997. */
  48998. var HemisphericLight = /** @class */ (function (_super) {
  48999. __extends(HemisphericLight, _super);
  49000. /**
  49001. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49002. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49003. * The HemisphericLight can't cast shadows.
  49004. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49005. * @param name The friendly name of the light
  49006. * @param direction The direction of the light reflection
  49007. * @param scene The scene the light belongs to
  49008. */
  49009. function HemisphericLight(name, direction, scene) {
  49010. var _this = _super.call(this, name, scene) || this;
  49011. /**
  49012. * The groundColor is the light in the opposite direction to the one specified during creation.
  49013. * 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.
  49014. */
  49015. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49016. _this.direction = direction || BABYLON.Vector3.Up();
  49017. return _this;
  49018. }
  49019. HemisphericLight.prototype._buildUniformLayout = function () {
  49020. this._uniformBuffer.addUniform("vLightData", 4);
  49021. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49022. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49023. this._uniformBuffer.addUniform("vLightGround", 3);
  49024. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49025. this._uniformBuffer.addUniform("depthValues", 2);
  49026. this._uniformBuffer.create();
  49027. };
  49028. /**
  49029. * Returns the string "HemisphericLight".
  49030. * @return The class name
  49031. */
  49032. HemisphericLight.prototype.getClassName = function () {
  49033. return "HemisphericLight";
  49034. };
  49035. /**
  49036. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49037. * Returns the updated direction.
  49038. * @param target The target the direction should point to
  49039. * @return The computed direction
  49040. */
  49041. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49042. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49043. return this.direction;
  49044. };
  49045. /**
  49046. * Returns the shadow generator associated to the light.
  49047. * @returns Always null for hemispheric lights because it does not support shadows.
  49048. */
  49049. HemisphericLight.prototype.getShadowGenerator = function () {
  49050. return null;
  49051. };
  49052. /**
  49053. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49054. * @param effect The effect to update
  49055. * @param lightIndex The index of the light in the effect to update
  49056. * @returns The hemispheric light
  49057. */
  49058. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49059. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49060. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49061. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49062. return this;
  49063. };
  49064. /**
  49065. * Computes the world matrix of the node
  49066. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49067. * @param useWasUpdatedFlag defines a reserved property
  49068. * @returns the world matrix
  49069. */
  49070. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  49071. if (!this._worldMatrix) {
  49072. this._worldMatrix = BABYLON.Matrix.Identity();
  49073. }
  49074. return this._worldMatrix;
  49075. };
  49076. /**
  49077. * Returns the integer 3.
  49078. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49079. */
  49080. HemisphericLight.prototype.getTypeID = function () {
  49081. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49082. };
  49083. /**
  49084. * Prepares the list of defines specific to the light type.
  49085. * @param defines the list of defines
  49086. * @param lightIndex defines the index of the light for the effect
  49087. */
  49088. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49089. defines["HEMILIGHT" + lightIndex] = true;
  49090. };
  49091. __decorate([
  49092. BABYLON.serializeAsColor3()
  49093. ], HemisphericLight.prototype, "groundColor", void 0);
  49094. __decorate([
  49095. BABYLON.serializeAsVector3()
  49096. ], HemisphericLight.prototype, "direction", void 0);
  49097. return HemisphericLight;
  49098. }(BABYLON.Light));
  49099. BABYLON.HemisphericLight = HemisphericLight;
  49100. })(BABYLON || (BABYLON = {}));
  49101. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49102. var BABYLON;
  49103. (function (BABYLON) {
  49104. /**
  49105. * Base implementation IShadowLight
  49106. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49107. */
  49108. var ShadowLight = /** @class */ (function (_super) {
  49109. __extends(ShadowLight, _super);
  49110. function ShadowLight() {
  49111. var _this = _super !== null && _super.apply(this, arguments) || this;
  49112. _this._needProjectionMatrixCompute = true;
  49113. return _this;
  49114. }
  49115. ShadowLight.prototype._setPosition = function (value) {
  49116. this._position = value;
  49117. };
  49118. Object.defineProperty(ShadowLight.prototype, "position", {
  49119. /**
  49120. * Sets the position the shadow will be casted from. Also use as the light position for both
  49121. * point and spot lights.
  49122. */
  49123. get: function () {
  49124. return this._position;
  49125. },
  49126. /**
  49127. * Sets the position the shadow will be casted from. Also use as the light position for both
  49128. * point and spot lights.
  49129. */
  49130. set: function (value) {
  49131. this._setPosition(value);
  49132. },
  49133. enumerable: true,
  49134. configurable: true
  49135. });
  49136. ShadowLight.prototype._setDirection = function (value) {
  49137. this._direction = value;
  49138. };
  49139. Object.defineProperty(ShadowLight.prototype, "direction", {
  49140. /**
  49141. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49142. * Also use as the light direction on spot and directional lights.
  49143. */
  49144. get: function () {
  49145. return this._direction;
  49146. },
  49147. /**
  49148. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49149. * Also use as the light direction on spot and directional lights.
  49150. */
  49151. set: function (value) {
  49152. this._setDirection(value);
  49153. },
  49154. enumerable: true,
  49155. configurable: true
  49156. });
  49157. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49158. /**
  49159. * Gets the shadow projection clipping minimum z value.
  49160. */
  49161. get: function () {
  49162. return this._shadowMinZ;
  49163. },
  49164. /**
  49165. * Sets the shadow projection clipping minimum z value.
  49166. */
  49167. set: function (value) {
  49168. this._shadowMinZ = value;
  49169. this.forceProjectionMatrixCompute();
  49170. },
  49171. enumerable: true,
  49172. configurable: true
  49173. });
  49174. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49175. /**
  49176. * Sets the shadow projection clipping maximum z value.
  49177. */
  49178. get: function () {
  49179. return this._shadowMaxZ;
  49180. },
  49181. /**
  49182. * Gets the shadow projection clipping maximum z value.
  49183. */
  49184. set: function (value) {
  49185. this._shadowMaxZ = value;
  49186. this.forceProjectionMatrixCompute();
  49187. },
  49188. enumerable: true,
  49189. configurable: true
  49190. });
  49191. /**
  49192. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49193. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49194. */
  49195. ShadowLight.prototype.computeTransformedInformation = function () {
  49196. if (this.parent && this.parent.getWorldMatrix) {
  49197. if (!this.transformedPosition) {
  49198. this.transformedPosition = BABYLON.Vector3.Zero();
  49199. }
  49200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49201. // In case the direction is present.
  49202. if (this.direction) {
  49203. if (!this.transformedDirection) {
  49204. this.transformedDirection = BABYLON.Vector3.Zero();
  49205. }
  49206. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49207. }
  49208. return true;
  49209. }
  49210. return false;
  49211. };
  49212. /**
  49213. * Return the depth scale used for the shadow map.
  49214. * @returns the depth scale.
  49215. */
  49216. ShadowLight.prototype.getDepthScale = function () {
  49217. return 50.0;
  49218. };
  49219. /**
  49220. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49221. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49222. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49223. */
  49224. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49225. return this.transformedDirection ? this.transformedDirection : this.direction;
  49226. };
  49227. /**
  49228. * Returns the ShadowLight absolute position in the World.
  49229. * @returns the position vector in world space
  49230. */
  49231. ShadowLight.prototype.getAbsolutePosition = function () {
  49232. return this.transformedPosition ? this.transformedPosition : this.position;
  49233. };
  49234. /**
  49235. * Sets the ShadowLight direction toward the passed target.
  49236. * @param target The point tot target in local space
  49237. * @returns the updated ShadowLight direction
  49238. */
  49239. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49240. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49241. return this.direction;
  49242. };
  49243. /**
  49244. * Returns the light rotation in euler definition.
  49245. * @returns the x y z rotation in local space.
  49246. */
  49247. ShadowLight.prototype.getRotation = function () {
  49248. this.direction.normalize();
  49249. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49250. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49251. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49252. };
  49253. /**
  49254. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49255. * @returns true if a cube texture needs to be use
  49256. */
  49257. ShadowLight.prototype.needCube = function () {
  49258. return false;
  49259. };
  49260. /**
  49261. * Detects if the projection matrix requires to be recomputed this frame.
  49262. * @returns true if it requires to be recomputed otherwise, false.
  49263. */
  49264. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49265. return this._needProjectionMatrixCompute;
  49266. };
  49267. /**
  49268. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49269. */
  49270. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49271. this._needProjectionMatrixCompute = true;
  49272. };
  49273. /** @hidden */
  49274. ShadowLight.prototype._initCache = function () {
  49275. _super.prototype._initCache.call(this);
  49276. this._cache.position = BABYLON.Vector3.Zero();
  49277. };
  49278. /** @hidden */
  49279. ShadowLight.prototype._isSynchronized = function () {
  49280. if (!this._cache.position.equals(this.position))
  49281. return false;
  49282. return true;
  49283. };
  49284. /**
  49285. * Computes the world matrix of the node
  49286. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  49287. * @returns the world matrix
  49288. */
  49289. ShadowLight.prototype.computeWorldMatrix = function (force) {
  49290. if (!force && this.isSynchronized()) {
  49291. this._currentRenderId = this.getScene().getRenderId();
  49292. return this._worldMatrix;
  49293. }
  49294. this._updateCache();
  49295. this._cache.position.copyFrom(this.position);
  49296. if (!this._worldMatrix) {
  49297. this._worldMatrix = BABYLON.Matrix.Identity();
  49298. }
  49299. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49300. if (this.parent && this.parent.getWorldMatrix) {
  49301. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  49302. this._markSyncedWithParent();
  49303. }
  49304. // Cache the determinant
  49305. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  49306. return this._worldMatrix;
  49307. };
  49308. /**
  49309. * Gets the minZ used for shadow according to both the scene and the light.
  49310. * @param activeCamera The camera we are returning the min for
  49311. * @returns the depth min z
  49312. */
  49313. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49314. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49315. };
  49316. /**
  49317. * Gets the maxZ used for shadow according to both the scene and the light.
  49318. * @param activeCamera The camera we are returning the max for
  49319. * @returns the depth max z
  49320. */
  49321. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49322. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49323. };
  49324. /**
  49325. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49326. * @param matrix The materix to updated with the projection information
  49327. * @param viewMatrix The transform matrix of the light
  49328. * @param renderList The list of mesh to render in the map
  49329. * @returns The current light
  49330. */
  49331. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49332. if (this.customProjectionMatrixBuilder) {
  49333. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49334. }
  49335. else {
  49336. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49337. }
  49338. return this;
  49339. };
  49340. __decorate([
  49341. BABYLON.serializeAsVector3()
  49342. ], ShadowLight.prototype, "position", null);
  49343. __decorate([
  49344. BABYLON.serializeAsVector3()
  49345. ], ShadowLight.prototype, "direction", null);
  49346. __decorate([
  49347. BABYLON.serialize()
  49348. ], ShadowLight.prototype, "shadowMinZ", null);
  49349. __decorate([
  49350. BABYLON.serialize()
  49351. ], ShadowLight.prototype, "shadowMaxZ", null);
  49352. return ShadowLight;
  49353. }(BABYLON.Light));
  49354. BABYLON.ShadowLight = ShadowLight;
  49355. })(BABYLON || (BABYLON = {}));
  49356. //# sourceMappingURL=babylon.shadowLight.js.map
  49357. var BABYLON;
  49358. (function (BABYLON) {
  49359. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49360. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49361. });
  49362. /**
  49363. * A point light is a light defined by an unique point in world space.
  49364. * The light is emitted in every direction from this point.
  49365. * A good example of a point light is a standard light bulb.
  49366. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49367. */
  49368. var PointLight = /** @class */ (function (_super) {
  49369. __extends(PointLight, _super);
  49370. /**
  49371. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49372. * A PointLight emits the light in every direction.
  49373. * It can cast shadows.
  49374. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49375. * ```javascript
  49376. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49377. * ```
  49378. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49379. * @param name The light friendly name
  49380. * @param position The position of the point light in the scene
  49381. * @param scene The scene the lights belongs to
  49382. */
  49383. function PointLight(name, position, scene) {
  49384. var _this = _super.call(this, name, scene) || this;
  49385. _this._shadowAngle = Math.PI / 2;
  49386. _this.position = position;
  49387. return _this;
  49388. }
  49389. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49390. /**
  49391. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49392. * This specifies what angle the shadow will use to be created.
  49393. *
  49394. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49395. */
  49396. get: function () {
  49397. return this._shadowAngle;
  49398. },
  49399. /**
  49400. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49401. * This specifies what angle the shadow will use to be created.
  49402. *
  49403. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49404. */
  49405. set: function (value) {
  49406. this._shadowAngle = value;
  49407. this.forceProjectionMatrixCompute();
  49408. },
  49409. enumerable: true,
  49410. configurable: true
  49411. });
  49412. Object.defineProperty(PointLight.prototype, "direction", {
  49413. /**
  49414. * Gets the direction if it has been set.
  49415. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49416. */
  49417. get: function () {
  49418. return this._direction;
  49419. },
  49420. /**
  49421. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49422. */
  49423. set: function (value) {
  49424. var previousNeedCube = this.needCube();
  49425. this._direction = value;
  49426. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49427. this._shadowGenerator.recreateShadowMap();
  49428. }
  49429. },
  49430. enumerable: true,
  49431. configurable: true
  49432. });
  49433. /**
  49434. * Returns the string "PointLight"
  49435. * @returns the class name
  49436. */
  49437. PointLight.prototype.getClassName = function () {
  49438. return "PointLight";
  49439. };
  49440. /**
  49441. * Returns the integer 0.
  49442. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49443. */
  49444. PointLight.prototype.getTypeID = function () {
  49445. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49446. };
  49447. /**
  49448. * Specifies wether or not the shadowmap should be a cube texture.
  49449. * @returns true if the shadowmap needs to be a cube texture.
  49450. */
  49451. PointLight.prototype.needCube = function () {
  49452. return !this.direction;
  49453. };
  49454. /**
  49455. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49456. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49457. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49458. */
  49459. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49460. if (this.direction) {
  49461. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49462. }
  49463. else {
  49464. switch (faceIndex) {
  49465. case 0:
  49466. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49467. case 1:
  49468. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49469. case 2:
  49470. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49471. case 3:
  49472. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49473. case 4:
  49474. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49475. case 5:
  49476. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49477. }
  49478. }
  49479. return BABYLON.Vector3.Zero();
  49480. };
  49481. /**
  49482. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49483. * - fov = PI / 2
  49484. * - aspect ratio : 1.0
  49485. * - z-near and far equal to the active camera minZ and maxZ.
  49486. * Returns the PointLight.
  49487. */
  49488. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49489. var activeCamera = this.getScene().activeCamera;
  49490. if (!activeCamera) {
  49491. return;
  49492. }
  49493. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49494. };
  49495. PointLight.prototype._buildUniformLayout = function () {
  49496. this._uniformBuffer.addUniform("vLightData", 4);
  49497. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49498. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49499. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49500. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49501. this._uniformBuffer.addUniform("depthValues", 2);
  49502. this._uniformBuffer.create();
  49503. };
  49504. /**
  49505. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49506. * @param effect The effect to update
  49507. * @param lightIndex The index of the light in the effect to update
  49508. * @returns The point light
  49509. */
  49510. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49511. if (this.computeTransformedInformation()) {
  49512. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49513. }
  49514. else {
  49515. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49516. }
  49517. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49518. return this;
  49519. };
  49520. /**
  49521. * Prepares the list of defines specific to the light type.
  49522. * @param defines the list of defines
  49523. * @param lightIndex defines the index of the light for the effect
  49524. */
  49525. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49526. defines["POINTLIGHT" + lightIndex] = true;
  49527. };
  49528. __decorate([
  49529. BABYLON.serialize()
  49530. ], PointLight.prototype, "shadowAngle", null);
  49531. return PointLight;
  49532. }(BABYLON.ShadowLight));
  49533. BABYLON.PointLight = PointLight;
  49534. })(BABYLON || (BABYLON = {}));
  49535. //# sourceMappingURL=babylon.pointLight.js.map
  49536. var BABYLON;
  49537. (function (BABYLON) {
  49538. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49539. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49540. });
  49541. /**
  49542. * A directional light is defined by a direction (what a surprise!).
  49543. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49544. * 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.
  49545. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49546. */
  49547. var DirectionalLight = /** @class */ (function (_super) {
  49548. __extends(DirectionalLight, _super);
  49549. /**
  49550. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49551. * The directional light is emitted from everywhere in the given direction.
  49552. * It can cast shawdows.
  49553. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49554. * @param name The friendly name of the light
  49555. * @param direction The direction of the light
  49556. * @param scene The scene the light belongs to
  49557. */
  49558. function DirectionalLight(name, direction, scene) {
  49559. var _this = _super.call(this, name, scene) || this;
  49560. _this._shadowFrustumSize = 0;
  49561. _this._shadowOrthoScale = 0.1;
  49562. /**
  49563. * Automatically compute the projection matrix to best fit (including all the casters)
  49564. * on each frame.
  49565. */
  49566. _this.autoUpdateExtends = true;
  49567. // Cache
  49568. _this._orthoLeft = Number.MAX_VALUE;
  49569. _this._orthoRight = Number.MIN_VALUE;
  49570. _this._orthoTop = Number.MIN_VALUE;
  49571. _this._orthoBottom = Number.MAX_VALUE;
  49572. _this.position = direction.scale(-1.0);
  49573. _this.direction = direction;
  49574. return _this;
  49575. }
  49576. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49577. /**
  49578. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49579. */
  49580. get: function () {
  49581. return this._shadowFrustumSize;
  49582. },
  49583. /**
  49584. * Specifies a fix frustum size for the shadow generation.
  49585. */
  49586. set: function (value) {
  49587. this._shadowFrustumSize = value;
  49588. this.forceProjectionMatrixCompute();
  49589. },
  49590. enumerable: true,
  49591. configurable: true
  49592. });
  49593. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49594. /**
  49595. * Gets the shadow projection scale against the optimal computed one.
  49596. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49597. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49598. */
  49599. get: function () {
  49600. return this._shadowOrthoScale;
  49601. },
  49602. /**
  49603. * Sets the shadow projection scale against the optimal computed one.
  49604. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49605. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49606. */
  49607. set: function (value) {
  49608. this._shadowOrthoScale = value;
  49609. this.forceProjectionMatrixCompute();
  49610. },
  49611. enumerable: true,
  49612. configurable: true
  49613. });
  49614. /**
  49615. * Returns the string "DirectionalLight".
  49616. * @return The class name
  49617. */
  49618. DirectionalLight.prototype.getClassName = function () {
  49619. return "DirectionalLight";
  49620. };
  49621. /**
  49622. * Returns the integer 1.
  49623. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49624. */
  49625. DirectionalLight.prototype.getTypeID = function () {
  49626. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49627. };
  49628. /**
  49629. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49630. * Returns the DirectionalLight Shadow projection matrix.
  49631. */
  49632. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49633. if (this.shadowFrustumSize > 0) {
  49634. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49635. }
  49636. else {
  49637. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49638. }
  49639. };
  49640. /**
  49641. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49642. * Returns the DirectionalLight Shadow projection matrix.
  49643. */
  49644. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49645. var activeCamera = this.getScene().activeCamera;
  49646. if (!activeCamera) {
  49647. return;
  49648. }
  49649. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49650. };
  49651. /**
  49652. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49653. * Returns the DirectionalLight Shadow projection matrix.
  49654. */
  49655. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49656. var activeCamera = this.getScene().activeCamera;
  49657. if (!activeCamera) {
  49658. return;
  49659. }
  49660. // Check extends
  49661. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49662. var tempVector3 = BABYLON.Vector3.Zero();
  49663. this._orthoLeft = Number.MAX_VALUE;
  49664. this._orthoRight = Number.MIN_VALUE;
  49665. this._orthoTop = Number.MIN_VALUE;
  49666. this._orthoBottom = Number.MAX_VALUE;
  49667. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49668. var mesh = renderList[meshIndex];
  49669. if (!mesh) {
  49670. continue;
  49671. }
  49672. var boundingInfo = mesh.getBoundingInfo();
  49673. var boundingBox = boundingInfo.boundingBox;
  49674. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49675. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49676. if (tempVector3.x < this._orthoLeft)
  49677. this._orthoLeft = tempVector3.x;
  49678. if (tempVector3.y < this._orthoBottom)
  49679. this._orthoBottom = tempVector3.y;
  49680. if (tempVector3.x > this._orthoRight)
  49681. this._orthoRight = tempVector3.x;
  49682. if (tempVector3.y > this._orthoTop)
  49683. this._orthoTop = tempVector3.y;
  49684. }
  49685. }
  49686. }
  49687. var xOffset = this._orthoRight - this._orthoLeft;
  49688. var yOffset = this._orthoTop - this._orthoBottom;
  49689. 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);
  49690. };
  49691. DirectionalLight.prototype._buildUniformLayout = function () {
  49692. this._uniformBuffer.addUniform("vLightData", 4);
  49693. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49694. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49695. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49696. this._uniformBuffer.addUniform("depthValues", 2);
  49697. this._uniformBuffer.create();
  49698. };
  49699. /**
  49700. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49701. * @param effect The effect to update
  49702. * @param lightIndex The index of the light in the effect to update
  49703. * @returns The directional light
  49704. */
  49705. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49706. if (this.computeTransformedInformation()) {
  49707. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49708. return this;
  49709. }
  49710. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49711. return this;
  49712. };
  49713. /**
  49714. * Gets the minZ used for shadow according to both the scene and the light.
  49715. *
  49716. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49717. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49718. * @param activeCamera The camera we are returning the min for
  49719. * @returns the depth min z
  49720. */
  49721. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49722. return 1;
  49723. };
  49724. /**
  49725. * Gets the maxZ used for shadow according to both the scene and the light.
  49726. *
  49727. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49728. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49729. * @param activeCamera The camera we are returning the max for
  49730. * @returns the depth max z
  49731. */
  49732. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49733. return 1;
  49734. };
  49735. /**
  49736. * Prepares the list of defines specific to the light type.
  49737. * @param defines the list of defines
  49738. * @param lightIndex defines the index of the light for the effect
  49739. */
  49740. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49741. defines["DIRLIGHT" + lightIndex] = true;
  49742. };
  49743. __decorate([
  49744. BABYLON.serialize()
  49745. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49746. __decorate([
  49747. BABYLON.serialize()
  49748. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49749. __decorate([
  49750. BABYLON.serialize()
  49751. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49752. return DirectionalLight;
  49753. }(BABYLON.ShadowLight));
  49754. BABYLON.DirectionalLight = DirectionalLight;
  49755. })(BABYLON || (BABYLON = {}));
  49756. //# sourceMappingURL=babylon.directionalLight.js.map
  49757. var BABYLON;
  49758. (function (BABYLON) {
  49759. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49760. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49761. });
  49762. /**
  49763. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49764. * These values define a cone of light starting from the position, emitting toward the direction.
  49765. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49766. * and the exponent defines the speed of the decay of the light with distance (reach).
  49767. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49768. */
  49769. var SpotLight = /** @class */ (function (_super) {
  49770. __extends(SpotLight, _super);
  49771. /**
  49772. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49773. * It can cast shadows.
  49774. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49775. * @param name The light friendly name
  49776. * @param position The position of the spot light in the scene
  49777. * @param direction The direction of the light in the scene
  49778. * @param angle The cone angle of the light in Radians
  49779. * @param exponent The light decay speed with the distance from the emission spot
  49780. * @param scene The scene the lights belongs to
  49781. */
  49782. function SpotLight(name, position, direction, angle, exponent, scene) {
  49783. var _this = _super.call(this, name, scene) || this;
  49784. _this._innerAngle = 0;
  49785. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49786. _this._projectionTextureLightNear = 1e-6;
  49787. _this._projectionTextureLightFar = 1000.0;
  49788. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49789. _this._projectionTextureViewLightDirty = true;
  49790. _this._projectionTextureProjectionLightDirty = true;
  49791. _this._projectionTextureDirty = true;
  49792. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49793. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49794. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49795. _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);
  49796. _this.position = position;
  49797. _this.direction = direction;
  49798. _this.angle = angle;
  49799. _this.exponent = exponent;
  49800. return _this;
  49801. }
  49802. Object.defineProperty(SpotLight.prototype, "angle", {
  49803. /**
  49804. * Gets the cone angle of the spot light in Radians.
  49805. */
  49806. get: function () {
  49807. return this._angle;
  49808. },
  49809. /**
  49810. * Sets the cone angle of the spot light in Radians.
  49811. */
  49812. set: function (value) {
  49813. this._angle = value;
  49814. this._cosHalfAngle = Math.cos(value * 0.5);
  49815. this._projectionTextureProjectionLightDirty = true;
  49816. this.forceProjectionMatrixCompute();
  49817. this._computeAngleValues();
  49818. },
  49819. enumerable: true,
  49820. configurable: true
  49821. });
  49822. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49823. /**
  49824. * Only used in gltf falloff mode, this defines the angle where
  49825. * the directional falloff will start before cutting at angle which could be seen
  49826. * as outer angle.
  49827. */
  49828. get: function () {
  49829. return this._innerAngle;
  49830. },
  49831. /**
  49832. * Only used in gltf falloff mode, this defines the angle where
  49833. * the directional falloff will start before cutting at angle which could be seen
  49834. * as outer angle.
  49835. */
  49836. set: function (value) {
  49837. this._innerAngle = value;
  49838. this._computeAngleValues();
  49839. },
  49840. enumerable: true,
  49841. configurable: true
  49842. });
  49843. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49844. /**
  49845. * Allows scaling the angle of the light for shadow generation only.
  49846. */
  49847. get: function () {
  49848. return this._shadowAngleScale;
  49849. },
  49850. /**
  49851. * Allows scaling the angle of the light for shadow generation only.
  49852. */
  49853. set: function (value) {
  49854. this._shadowAngleScale = value;
  49855. this.forceProjectionMatrixCompute();
  49856. },
  49857. enumerable: true,
  49858. configurable: true
  49859. });
  49860. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49861. /**
  49862. * Allows reading the projecton texture
  49863. */
  49864. get: function () {
  49865. return this._projectionTextureMatrix;
  49866. },
  49867. enumerable: true,
  49868. configurable: true
  49869. });
  49870. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49871. /**
  49872. * Gets the near clip of the Spotlight for texture projection.
  49873. */
  49874. get: function () {
  49875. return this._projectionTextureLightNear;
  49876. },
  49877. /**
  49878. * Sets the near clip of the Spotlight for texture projection.
  49879. */
  49880. set: function (value) {
  49881. this._projectionTextureLightNear = value;
  49882. this._projectionTextureProjectionLightDirty = true;
  49883. },
  49884. enumerable: true,
  49885. configurable: true
  49886. });
  49887. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49888. /**
  49889. * Gets the far clip of the Spotlight for texture projection.
  49890. */
  49891. get: function () {
  49892. return this._projectionTextureLightFar;
  49893. },
  49894. /**
  49895. * Sets the far clip of the Spotlight for texture projection.
  49896. */
  49897. set: function (value) {
  49898. this._projectionTextureLightFar = value;
  49899. this._projectionTextureProjectionLightDirty = true;
  49900. },
  49901. enumerable: true,
  49902. configurable: true
  49903. });
  49904. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49905. /**
  49906. * Gets the Up vector of the Spotlight for texture projection.
  49907. */
  49908. get: function () {
  49909. return this._projectionTextureUpDirection;
  49910. },
  49911. /**
  49912. * Sets the Up vector of the Spotlight for texture projection.
  49913. */
  49914. set: function (value) {
  49915. this._projectionTextureUpDirection = value;
  49916. this._projectionTextureProjectionLightDirty = true;
  49917. },
  49918. enumerable: true,
  49919. configurable: true
  49920. });
  49921. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49922. /**
  49923. * Gets the projection texture of the light.
  49924. */
  49925. get: function () {
  49926. return this._projectionTexture;
  49927. },
  49928. /**
  49929. * Sets the projection texture of the light.
  49930. */
  49931. set: function (value) {
  49932. this._projectionTexture = value;
  49933. this._projectionTextureDirty = true;
  49934. },
  49935. enumerable: true,
  49936. configurable: true
  49937. });
  49938. /**
  49939. * Returns the string "SpotLight".
  49940. * @returns the class name
  49941. */
  49942. SpotLight.prototype.getClassName = function () {
  49943. return "SpotLight";
  49944. };
  49945. /**
  49946. * Returns the integer 2.
  49947. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49948. */
  49949. SpotLight.prototype.getTypeID = function () {
  49950. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49951. };
  49952. /**
  49953. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49954. */
  49955. SpotLight.prototype._setDirection = function (value) {
  49956. _super.prototype._setDirection.call(this, value);
  49957. this._projectionTextureViewLightDirty = true;
  49958. };
  49959. /**
  49960. * Overrides the position setter to recompute the projection texture view light Matrix.
  49961. */
  49962. SpotLight.prototype._setPosition = function (value) {
  49963. _super.prototype._setPosition.call(this, value);
  49964. this._projectionTextureViewLightDirty = true;
  49965. };
  49966. /**
  49967. * 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.
  49968. * Returns the SpotLight.
  49969. */
  49970. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49971. var activeCamera = this.getScene().activeCamera;
  49972. if (!activeCamera) {
  49973. return;
  49974. }
  49975. this._shadowAngleScale = this._shadowAngleScale || 1;
  49976. var angle = this._shadowAngleScale * this._angle;
  49977. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49978. };
  49979. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49980. this._projectionTextureViewLightDirty = false;
  49981. this._projectionTextureDirty = true;
  49982. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49983. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49984. };
  49985. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49986. this._projectionTextureProjectionLightDirty = false;
  49987. this._projectionTextureDirty = true;
  49988. var light_far = this.projectionTextureLightFar;
  49989. var light_near = this.projectionTextureLightNear;
  49990. var P = light_far / (light_far - light_near);
  49991. var Q = -P * light_near;
  49992. var S = 1.0 / Math.tan(this._angle / 2.0);
  49993. var A = 1.0;
  49994. 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);
  49995. };
  49996. /**
  49997. * Main function for light texture projection matrix computing.
  49998. */
  49999. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50000. this._projectionTextureDirty = false;
  50001. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50002. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50003. };
  50004. SpotLight.prototype._buildUniformLayout = function () {
  50005. this._uniformBuffer.addUniform("vLightData", 4);
  50006. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50007. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50008. this._uniformBuffer.addUniform("vLightDirection", 3);
  50009. this._uniformBuffer.addUniform("vLightFalloff", 4);
  50010. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50011. this._uniformBuffer.addUniform("depthValues", 2);
  50012. this._uniformBuffer.create();
  50013. };
  50014. SpotLight.prototype._computeAngleValues = function () {
  50015. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  50016. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  50017. };
  50018. /**
  50019. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50020. * @param effect The effect to update
  50021. * @param lightIndex The index of the light in the effect to update
  50022. * @returns The spot light
  50023. */
  50024. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50025. var normalizeDirection;
  50026. if (this.computeTransformedInformation()) {
  50027. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50028. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50029. }
  50030. else {
  50031. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50032. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50033. }
  50034. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  50035. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  50036. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50037. if (this._projectionTextureViewLightDirty) {
  50038. this._computeProjectionTextureViewLightMatrix();
  50039. }
  50040. if (this._projectionTextureProjectionLightDirty) {
  50041. this._computeProjectionTextureProjectionLightMatrix();
  50042. }
  50043. if (this._projectionTextureDirty) {
  50044. this._computeProjectionTextureMatrix();
  50045. }
  50046. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50047. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50048. }
  50049. return this;
  50050. };
  50051. /**
  50052. * Disposes the light and the associated resources.
  50053. */
  50054. SpotLight.prototype.dispose = function () {
  50055. _super.prototype.dispose.call(this);
  50056. if (this._projectionTexture) {
  50057. this._projectionTexture.dispose();
  50058. }
  50059. };
  50060. /**
  50061. * Prepares the list of defines specific to the light type.
  50062. * @param defines the list of defines
  50063. * @param lightIndex defines the index of the light for the effect
  50064. */
  50065. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50066. defines["SPOTLIGHT" + lightIndex] = true;
  50067. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  50068. };
  50069. __decorate([
  50070. BABYLON.serialize()
  50071. ], SpotLight.prototype, "angle", null);
  50072. __decorate([
  50073. BABYLON.serialize()
  50074. ], SpotLight.prototype, "innerAngle", null);
  50075. __decorate([
  50076. BABYLON.serialize()
  50077. ], SpotLight.prototype, "shadowAngleScale", null);
  50078. __decorate([
  50079. BABYLON.serialize()
  50080. ], SpotLight.prototype, "exponent", void 0);
  50081. __decorate([
  50082. BABYLON.serialize()
  50083. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50084. __decorate([
  50085. BABYLON.serialize()
  50086. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50087. __decorate([
  50088. BABYLON.serialize()
  50089. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50090. __decorate([
  50091. BABYLON.serializeAsTexture("projectedLightTexture")
  50092. ], SpotLight.prototype, "_projectionTexture", void 0);
  50093. return SpotLight;
  50094. }(BABYLON.ShadowLight));
  50095. BABYLON.SpotLight = SpotLight;
  50096. })(BABYLON || (BABYLON = {}));
  50097. //# sourceMappingURL=babylon.spotLight.js.map
  50098. var BABYLON;
  50099. (function (BABYLON) {
  50100. /**
  50101. * Class used to override all child animations of a given target
  50102. */
  50103. var AnimationPropertiesOverride = /** @class */ (function () {
  50104. function AnimationPropertiesOverride() {
  50105. /**
  50106. * Gets or sets a value indicating if animation blending must be used
  50107. */
  50108. this.enableBlending = false;
  50109. /**
  50110. * Gets or sets the blending speed to use when enableBlending is true
  50111. */
  50112. this.blendingSpeed = 0.01;
  50113. /**
  50114. * Gets or sets the default loop mode to use
  50115. */
  50116. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50117. }
  50118. return AnimationPropertiesOverride;
  50119. }());
  50120. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50121. })(BABYLON || (BABYLON = {}));
  50122. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50123. var BABYLON;
  50124. (function (BABYLON) {
  50125. /**
  50126. * Represents the range of an animation
  50127. */
  50128. var AnimationRange = /** @class */ (function () {
  50129. /**
  50130. * Initializes the range of an animation
  50131. * @param name The name of the animation range
  50132. * @param from The starting frame of the animation
  50133. * @param to The ending frame of the animation
  50134. */
  50135. function AnimationRange(
  50136. /**The name of the animation range**/
  50137. name,
  50138. /**The starting frame of the animation */
  50139. from,
  50140. /**The ending frame of the animation*/
  50141. to) {
  50142. this.name = name;
  50143. this.from = from;
  50144. this.to = to;
  50145. }
  50146. /**
  50147. * Makes a copy of the animation range
  50148. * @returns A copy of the animation range
  50149. */
  50150. AnimationRange.prototype.clone = function () {
  50151. return new AnimationRange(this.name, this.from, this.to);
  50152. };
  50153. return AnimationRange;
  50154. }());
  50155. BABYLON.AnimationRange = AnimationRange;
  50156. /**
  50157. * Composed of a frame, and an action function
  50158. */
  50159. var AnimationEvent = /** @class */ (function () {
  50160. /**
  50161. * Initializes the animation event
  50162. * @param frame The frame for which the event is triggered
  50163. * @param action The event to perform when triggered
  50164. * @param onlyOnce Specifies if the event should be triggered only once
  50165. */
  50166. function AnimationEvent(
  50167. /** The frame for which the event is triggered **/
  50168. frame,
  50169. /** The event to perform when triggered **/
  50170. action,
  50171. /** Specifies if the event should be triggered only once**/
  50172. onlyOnce) {
  50173. this.frame = frame;
  50174. this.action = action;
  50175. this.onlyOnce = onlyOnce;
  50176. /**
  50177. * Specifies if the animation event is done
  50178. */
  50179. this.isDone = false;
  50180. }
  50181. /** @hidden */
  50182. AnimationEvent.prototype._clone = function () {
  50183. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50184. };
  50185. return AnimationEvent;
  50186. }());
  50187. BABYLON.AnimationEvent = AnimationEvent;
  50188. /**
  50189. * A cursor which tracks a point on a path
  50190. */
  50191. var PathCursor = /** @class */ (function () {
  50192. /**
  50193. * Initializes the path cursor
  50194. * @param path The path to track
  50195. */
  50196. function PathCursor(path) {
  50197. this.path = path;
  50198. /**
  50199. * Stores path cursor callbacks for when an onchange event is triggered
  50200. */
  50201. this._onchange = new Array();
  50202. /**
  50203. * The value of the path cursor
  50204. */
  50205. this.value = 0;
  50206. /**
  50207. * The animation array of the path cursor
  50208. */
  50209. this.animations = new Array();
  50210. }
  50211. /**
  50212. * Gets the cursor point on the path
  50213. * @returns A point on the path cursor at the cursor location
  50214. */
  50215. PathCursor.prototype.getPoint = function () {
  50216. var point = this.path.getPointAtLengthPosition(this.value);
  50217. return new BABYLON.Vector3(point.x, 0, point.y);
  50218. };
  50219. /**
  50220. * Moves the cursor ahead by the step amount
  50221. * @param step The amount to move the cursor forward
  50222. * @returns This path cursor
  50223. */
  50224. PathCursor.prototype.moveAhead = function (step) {
  50225. if (step === void 0) { step = 0.002; }
  50226. this.move(step);
  50227. return this;
  50228. };
  50229. /**
  50230. * Moves the cursor behind by the step amount
  50231. * @param step The amount to move the cursor back
  50232. * @returns This path cursor
  50233. */
  50234. PathCursor.prototype.moveBack = function (step) {
  50235. if (step === void 0) { step = 0.002; }
  50236. this.move(-step);
  50237. return this;
  50238. };
  50239. /**
  50240. * Moves the cursor by the step amount
  50241. * If the step amount is greater than one, an exception is thrown
  50242. * @param step The amount to move the cursor
  50243. * @returns This path cursor
  50244. */
  50245. PathCursor.prototype.move = function (step) {
  50246. if (Math.abs(step) > 1) {
  50247. throw "step size should be less than 1.";
  50248. }
  50249. this.value += step;
  50250. this.ensureLimits();
  50251. this.raiseOnChange();
  50252. return this;
  50253. };
  50254. /**
  50255. * Ensures that the value is limited between zero and one
  50256. * @returns This path cursor
  50257. */
  50258. PathCursor.prototype.ensureLimits = function () {
  50259. while (this.value > 1) {
  50260. this.value -= 1;
  50261. }
  50262. while (this.value < 0) {
  50263. this.value += 1;
  50264. }
  50265. return this;
  50266. };
  50267. /**
  50268. * Runs onchange callbacks on change (used by the animation engine)
  50269. * @returns This path cursor
  50270. */
  50271. PathCursor.prototype.raiseOnChange = function () {
  50272. var _this = this;
  50273. this._onchange.forEach(function (f) { return f(_this); });
  50274. return this;
  50275. };
  50276. /**
  50277. * Executes a function on change
  50278. * @param f A path cursor onchange callback
  50279. * @returns This path cursor
  50280. */
  50281. PathCursor.prototype.onchange = function (f) {
  50282. this._onchange.push(f);
  50283. return this;
  50284. };
  50285. return PathCursor;
  50286. }());
  50287. BABYLON.PathCursor = PathCursor;
  50288. /**
  50289. * Enum for the animation key frame interpolation type
  50290. */
  50291. var AnimationKeyInterpolation;
  50292. (function (AnimationKeyInterpolation) {
  50293. /**
  50294. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50295. */
  50296. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50297. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50298. /**
  50299. * Class used to store any kind of animation
  50300. */
  50301. var Animation = /** @class */ (function () {
  50302. /**
  50303. * Initializes the animation
  50304. * @param name Name of the animation
  50305. * @param targetProperty Property to animate
  50306. * @param framePerSecond The frames per second of the animation
  50307. * @param dataType The data type of the animation
  50308. * @param loopMode The loop mode of the animation
  50309. * @param enableBlendings Specifies if blending should be enabled
  50310. */
  50311. function Animation(
  50312. /**Name of the animation */
  50313. name,
  50314. /**Property to animate */
  50315. targetProperty,
  50316. /**The frames per second of the animation */
  50317. framePerSecond,
  50318. /**The data type of the animation */
  50319. dataType,
  50320. /**The loop mode of the animation */
  50321. loopMode,
  50322. /**Specifies if blending should be enabled */
  50323. enableBlending) {
  50324. this.name = name;
  50325. this.targetProperty = targetProperty;
  50326. this.framePerSecond = framePerSecond;
  50327. this.dataType = dataType;
  50328. this.loopMode = loopMode;
  50329. this.enableBlending = enableBlending;
  50330. /**
  50331. * @hidden Internal use only
  50332. */
  50333. this._runtimeAnimations = new Array();
  50334. /**
  50335. * The set of event that will be linked to this animation
  50336. */
  50337. this._events = new Array();
  50338. /**
  50339. * Stores the blending speed of the animation
  50340. */
  50341. this.blendingSpeed = 0.01;
  50342. /**
  50343. * Stores the animation ranges for the animation
  50344. */
  50345. this._ranges = {};
  50346. this.targetPropertyPath = targetProperty.split(".");
  50347. this.dataType = dataType;
  50348. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50349. }
  50350. /**
  50351. * @hidden Internal use
  50352. */
  50353. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50354. var dataType = undefined;
  50355. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50356. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50357. }
  50358. else if (from instanceof BABYLON.Quaternion) {
  50359. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50360. }
  50361. else if (from instanceof BABYLON.Vector3) {
  50362. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50363. }
  50364. else if (from instanceof BABYLON.Vector2) {
  50365. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50366. }
  50367. else if (from instanceof BABYLON.Color3) {
  50368. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50369. }
  50370. else if (from instanceof BABYLON.Size) {
  50371. dataType = Animation.ANIMATIONTYPE_SIZE;
  50372. }
  50373. if (dataType == undefined) {
  50374. return null;
  50375. }
  50376. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50377. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50378. animation.setKeys(keys);
  50379. if (easingFunction !== undefined) {
  50380. animation.setEasingFunction(easingFunction);
  50381. }
  50382. return animation;
  50383. };
  50384. /**
  50385. * Sets up an animation
  50386. * @param property The property to animate
  50387. * @param animationType The animation type to apply
  50388. * @param framePerSecond The frames per second of the animation
  50389. * @param easingFunction The easing function used in the animation
  50390. * @returns The created animation
  50391. */
  50392. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50393. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50394. animation.setEasingFunction(easingFunction);
  50395. return animation;
  50396. };
  50397. /**
  50398. * Create and start an animation on a node
  50399. * @param name defines the name of the global animation that will be run on all nodes
  50400. * @param node defines the root node where the animation will take place
  50401. * @param targetProperty defines property to animate
  50402. * @param framePerSecond defines the number of frame per second yo use
  50403. * @param totalFrame defines the number of frames in total
  50404. * @param from defines the initial value
  50405. * @param to defines the final value
  50406. * @param loopMode defines which loop mode you want to use (off by default)
  50407. * @param easingFunction defines the easing function to use (linear by default)
  50408. * @param onAnimationEnd defines the callback to call when animation end
  50409. * @returns the animatable created for this animation
  50410. */
  50411. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50412. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50413. if (!animation) {
  50414. return null;
  50415. }
  50416. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50417. };
  50418. /**
  50419. * Create and start an animation on a node and its descendants
  50420. * @param name defines the name of the global animation that will be run on all nodes
  50421. * @param node defines the root node where the animation will take place
  50422. * @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
  50423. * @param targetProperty defines property to animate
  50424. * @param framePerSecond defines the number of frame per second to use
  50425. * @param totalFrame defines the number of frames in total
  50426. * @param from defines the initial value
  50427. * @param to defines the final value
  50428. * @param loopMode defines which loop mode you want to use (off by default)
  50429. * @param easingFunction defines the easing function to use (linear by default)
  50430. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50431. * @returns the list of animatables created for all nodes
  50432. * @example https://www.babylonjs-playground.com/#MH0VLI
  50433. */
  50434. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50435. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50436. if (!animation) {
  50437. return null;
  50438. }
  50439. var scene = node.getScene();
  50440. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50441. };
  50442. /**
  50443. * Creates a new animation, merges it with the existing animations and starts it
  50444. * @param name Name of the animation
  50445. * @param node Node which contains the scene that begins the animations
  50446. * @param targetProperty Specifies which property to animate
  50447. * @param framePerSecond The frames per second of the animation
  50448. * @param totalFrame The total number of frames
  50449. * @param from The frame at the beginning of the animation
  50450. * @param to The frame at the end of the animation
  50451. * @param loopMode Specifies the loop mode of the animation
  50452. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50453. * @param onAnimationEnd Callback to run once the animation is complete
  50454. * @returns Nullable animation
  50455. */
  50456. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50457. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50458. if (!animation) {
  50459. return null;
  50460. }
  50461. node.animations.push(animation);
  50462. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50463. };
  50464. /**
  50465. * Transition property of an host to the target Value
  50466. * @param property The property to transition
  50467. * @param targetValue The target Value of the property
  50468. * @param host The object where the property to animate belongs
  50469. * @param scene Scene used to run the animation
  50470. * @param frameRate Framerate (in frame/s) to use
  50471. * @param transition The transition type we want to use
  50472. * @param duration The duration of the animation, in milliseconds
  50473. * @param onAnimationEnd Callback trigger at the end of the animation
  50474. * @returns Nullable animation
  50475. */
  50476. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50477. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50478. if (duration <= 0) {
  50479. host[property] = targetValue;
  50480. if (onAnimationEnd) {
  50481. onAnimationEnd();
  50482. }
  50483. return null;
  50484. }
  50485. var endFrame = frameRate * (duration / 1000);
  50486. transition.setKeys([{
  50487. frame: 0,
  50488. value: host[property].clone ? host[property].clone() : host[property]
  50489. },
  50490. {
  50491. frame: endFrame,
  50492. value: targetValue
  50493. }]);
  50494. if (!host.animations) {
  50495. host.animations = [];
  50496. }
  50497. host.animations.push(transition);
  50498. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50499. animation.onAnimationEnd = onAnimationEnd;
  50500. return animation;
  50501. };
  50502. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50503. /**
  50504. * Return the array of runtime animations currently using this animation
  50505. */
  50506. get: function () {
  50507. return this._runtimeAnimations;
  50508. },
  50509. enumerable: true,
  50510. configurable: true
  50511. });
  50512. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50513. /**
  50514. * Specifies if any of the runtime animations are currently running
  50515. */
  50516. get: function () {
  50517. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50518. var runtimeAnimation = _a[_i];
  50519. if (!runtimeAnimation.isStopped) {
  50520. return true;
  50521. }
  50522. }
  50523. return false;
  50524. },
  50525. enumerable: true,
  50526. configurable: true
  50527. });
  50528. // Methods
  50529. /**
  50530. * Converts the animation to a string
  50531. * @param fullDetails support for multiple levels of logging within scene loading
  50532. * @returns String form of the animation
  50533. */
  50534. Animation.prototype.toString = function (fullDetails) {
  50535. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50536. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50537. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50538. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50539. if (fullDetails) {
  50540. ret += ", Ranges: {";
  50541. var first = true;
  50542. for (var name in this._ranges) {
  50543. if (first) {
  50544. ret += ", ";
  50545. first = false;
  50546. }
  50547. ret += name;
  50548. }
  50549. ret += "}";
  50550. }
  50551. return ret;
  50552. };
  50553. /**
  50554. * Add an event to this animation
  50555. * @param event Event to add
  50556. */
  50557. Animation.prototype.addEvent = function (event) {
  50558. this._events.push(event);
  50559. };
  50560. /**
  50561. * Remove all events found at the given frame
  50562. * @param frame The frame to remove events from
  50563. */
  50564. Animation.prototype.removeEvents = function (frame) {
  50565. for (var index = 0; index < this._events.length; index++) {
  50566. if (this._events[index].frame === frame) {
  50567. this._events.splice(index, 1);
  50568. index--;
  50569. }
  50570. }
  50571. };
  50572. /**
  50573. * Retrieves all the events from the animation
  50574. * @returns Events from the animation
  50575. */
  50576. Animation.prototype.getEvents = function () {
  50577. return this._events;
  50578. };
  50579. /**
  50580. * Creates an animation range
  50581. * @param name Name of the animation range
  50582. * @param from Starting frame of the animation range
  50583. * @param to Ending frame of the animation
  50584. */
  50585. Animation.prototype.createRange = function (name, from, to) {
  50586. // check name not already in use; could happen for bones after serialized
  50587. if (!this._ranges[name]) {
  50588. this._ranges[name] = new AnimationRange(name, from, to);
  50589. }
  50590. };
  50591. /**
  50592. * Deletes an animation range by name
  50593. * @param name Name of the animation range to delete
  50594. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50595. */
  50596. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50597. if (deleteFrames === void 0) { deleteFrames = true; }
  50598. var range = this._ranges[name];
  50599. if (!range) {
  50600. return;
  50601. }
  50602. if (deleteFrames) {
  50603. var from = range.from;
  50604. var to = range.to;
  50605. // this loop MUST go high to low for multiple splices to work
  50606. for (var key = this._keys.length - 1; key >= 0; key--) {
  50607. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50608. this._keys.splice(key, 1);
  50609. }
  50610. }
  50611. }
  50612. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50613. };
  50614. /**
  50615. * Gets the animation range by name, or null if not defined
  50616. * @param name Name of the animation range
  50617. * @returns Nullable animation range
  50618. */
  50619. Animation.prototype.getRange = function (name) {
  50620. return this._ranges[name];
  50621. };
  50622. /**
  50623. * Gets the key frames from the animation
  50624. * @returns The key frames of the animation
  50625. */
  50626. Animation.prototype.getKeys = function () {
  50627. return this._keys;
  50628. };
  50629. /**
  50630. * Gets the highest frame rate of the animation
  50631. * @returns Highest frame rate of the animation
  50632. */
  50633. Animation.prototype.getHighestFrame = function () {
  50634. var ret = 0;
  50635. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50636. if (ret < this._keys[key].frame) {
  50637. ret = this._keys[key].frame;
  50638. }
  50639. }
  50640. return ret;
  50641. };
  50642. /**
  50643. * Gets the easing function of the animation
  50644. * @returns Easing function of the animation
  50645. */
  50646. Animation.prototype.getEasingFunction = function () {
  50647. return this._easingFunction;
  50648. };
  50649. /**
  50650. * Sets the easing function of the animation
  50651. * @param easingFunction A custom mathematical formula for animation
  50652. */
  50653. Animation.prototype.setEasingFunction = function (easingFunction) {
  50654. this._easingFunction = easingFunction;
  50655. };
  50656. /**
  50657. * Interpolates a scalar linearly
  50658. * @param startValue Start value of the animation curve
  50659. * @param endValue End value of the animation curve
  50660. * @param gradient Scalar amount to interpolate
  50661. * @returns Interpolated scalar value
  50662. */
  50663. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50664. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50665. };
  50666. /**
  50667. * Interpolates a scalar cubically
  50668. * @param startValue Start value of the animation curve
  50669. * @param outTangent End tangent of the animation
  50670. * @param endValue End value of the animation curve
  50671. * @param inTangent Start tangent of the animation curve
  50672. * @param gradient Scalar amount to interpolate
  50673. * @returns Interpolated scalar value
  50674. */
  50675. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50676. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50677. };
  50678. /**
  50679. * Interpolates a quaternion using a spherical linear interpolation
  50680. * @param startValue Start value of the animation curve
  50681. * @param endValue End value of the animation curve
  50682. * @param gradient Scalar amount to interpolate
  50683. * @returns Interpolated quaternion value
  50684. */
  50685. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50686. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50687. };
  50688. /**
  50689. * Interpolates a quaternion cubically
  50690. * @param startValue Start value of the animation curve
  50691. * @param outTangent End tangent of the animation curve
  50692. * @param endValue End value of the animation curve
  50693. * @param inTangent Start tangent of the animation curve
  50694. * @param gradient Scalar amount to interpolate
  50695. * @returns Interpolated quaternion value
  50696. */
  50697. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50698. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50699. };
  50700. /**
  50701. * Interpolates a Vector3 linearl
  50702. * @param startValue Start value of the animation curve
  50703. * @param endValue End value of the animation curve
  50704. * @param gradient Scalar amount to interpolate
  50705. * @returns Interpolated scalar value
  50706. */
  50707. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50708. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50709. };
  50710. /**
  50711. * Interpolates a Vector3 cubically
  50712. * @param startValue Start value of the animation curve
  50713. * @param outTangent End tangent of the animation
  50714. * @param endValue End value of the animation curve
  50715. * @param inTangent Start tangent of the animation curve
  50716. * @param gradient Scalar amount to interpolate
  50717. * @returns InterpolatedVector3 value
  50718. */
  50719. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50720. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50721. };
  50722. /**
  50723. * Interpolates a Vector2 linearly
  50724. * @param startValue Start value of the animation curve
  50725. * @param endValue End value of the animation curve
  50726. * @param gradient Scalar amount to interpolate
  50727. * @returns Interpolated Vector2 value
  50728. */
  50729. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50730. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50731. };
  50732. /**
  50733. * Interpolates a Vector2 cubically
  50734. * @param startValue Start value of the animation curve
  50735. * @param outTangent End tangent of the animation
  50736. * @param endValue End value of the animation curve
  50737. * @param inTangent Start tangent of the animation curve
  50738. * @param gradient Scalar amount to interpolate
  50739. * @returns Interpolated Vector2 value
  50740. */
  50741. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50742. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50743. };
  50744. /**
  50745. * Interpolates a size linearly
  50746. * @param startValue Start value of the animation curve
  50747. * @param endValue End value of the animation curve
  50748. * @param gradient Scalar amount to interpolate
  50749. * @returns Interpolated Size value
  50750. */
  50751. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50752. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50753. };
  50754. /**
  50755. * Interpolates a Color3 linearly
  50756. * @param startValue Start value of the animation curve
  50757. * @param endValue End value of the animation curve
  50758. * @param gradient Scalar amount to interpolate
  50759. * @returns Interpolated Color3 value
  50760. */
  50761. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50762. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50763. };
  50764. /**
  50765. * @hidden Internal use only
  50766. */
  50767. Animation.prototype._getKeyValue = function (value) {
  50768. if (typeof value === "function") {
  50769. return value();
  50770. }
  50771. return value;
  50772. };
  50773. /**
  50774. * @hidden Internal use only
  50775. */
  50776. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50777. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50778. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50779. }
  50780. var keys = this.getKeys();
  50781. // Try to get a hash to find the right key
  50782. 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));
  50783. if (keys[startKeyIndex].frame >= currentFrame) {
  50784. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50785. startKeyIndex--;
  50786. }
  50787. }
  50788. for (var key = startKeyIndex; key < keys.length; key++) {
  50789. var endKey = keys[key + 1];
  50790. if (endKey.frame >= currentFrame) {
  50791. var startKey = keys[key];
  50792. var startValue = this._getKeyValue(startKey.value);
  50793. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50794. return startValue;
  50795. }
  50796. var endValue = this._getKeyValue(endKey.value);
  50797. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50798. var frameDelta = endKey.frame - startKey.frame;
  50799. // gradient : percent of currentFrame between the frame inf and the frame sup
  50800. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50801. // check for easingFunction and correction of gradient
  50802. var easingFunction = this.getEasingFunction();
  50803. if (easingFunction != null) {
  50804. gradient = easingFunction.ease(gradient);
  50805. }
  50806. switch (this.dataType) {
  50807. // Float
  50808. case Animation.ANIMATIONTYPE_FLOAT:
  50809. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50810. switch (loopMode) {
  50811. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50812. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50813. return floatValue;
  50814. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50815. return offsetValue * repeatCount + floatValue;
  50816. }
  50817. break;
  50818. // Quaternion
  50819. case Animation.ANIMATIONTYPE_QUATERNION:
  50820. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50821. switch (loopMode) {
  50822. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50823. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50824. return quatValue;
  50825. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50826. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50827. }
  50828. return quatValue;
  50829. // Vector3
  50830. case Animation.ANIMATIONTYPE_VECTOR3:
  50831. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50832. switch (loopMode) {
  50833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50835. return vec3Value;
  50836. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50837. return vec3Value.add(offsetValue.scale(repeatCount));
  50838. }
  50839. // Vector2
  50840. case Animation.ANIMATIONTYPE_VECTOR2:
  50841. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50842. switch (loopMode) {
  50843. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50844. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50845. return vec2Value;
  50846. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50847. return vec2Value.add(offsetValue.scale(repeatCount));
  50848. }
  50849. // Size
  50850. case Animation.ANIMATIONTYPE_SIZE:
  50851. switch (loopMode) {
  50852. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50853. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50854. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50855. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50856. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50857. }
  50858. // Color3
  50859. case Animation.ANIMATIONTYPE_COLOR3:
  50860. switch (loopMode) {
  50861. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50862. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50863. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50864. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50865. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50866. }
  50867. // Matrix
  50868. case Animation.ANIMATIONTYPE_MATRIX:
  50869. switch (loopMode) {
  50870. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50871. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50872. if (Animation.AllowMatricesInterpolation) {
  50873. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50874. }
  50875. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50876. return startValue;
  50877. }
  50878. default:
  50879. break;
  50880. }
  50881. break;
  50882. }
  50883. }
  50884. return this._getKeyValue(keys[keys.length - 1].value);
  50885. };
  50886. /**
  50887. * Defines the function to use to interpolate matrices
  50888. * @param startValue defines the start matrix
  50889. * @param endValue defines the end matrix
  50890. * @param gradient defines the gradient between both matrices
  50891. * @param result defines an optional target matrix where to store the interpolation
  50892. * @returns the interpolated matrix
  50893. */
  50894. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50895. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50896. if (result) {
  50897. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50898. return result;
  50899. }
  50900. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50901. }
  50902. if (result) {
  50903. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50904. return result;
  50905. }
  50906. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50907. };
  50908. /**
  50909. * Makes a copy of the animation
  50910. * @returns Cloned animation
  50911. */
  50912. Animation.prototype.clone = function () {
  50913. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50914. clone.enableBlending = this.enableBlending;
  50915. clone.blendingSpeed = this.blendingSpeed;
  50916. if (this._keys) {
  50917. clone.setKeys(this._keys);
  50918. }
  50919. if (this._ranges) {
  50920. clone._ranges = {};
  50921. for (var name in this._ranges) {
  50922. var range = this._ranges[name];
  50923. if (!range) {
  50924. continue;
  50925. }
  50926. clone._ranges[name] = range.clone();
  50927. }
  50928. }
  50929. return clone;
  50930. };
  50931. /**
  50932. * Sets the key frames of the animation
  50933. * @param values The animation key frames to set
  50934. */
  50935. Animation.prototype.setKeys = function (values) {
  50936. this._keys = values.slice(0);
  50937. };
  50938. /**
  50939. * Serializes the animation to an object
  50940. * @returns Serialized object
  50941. */
  50942. Animation.prototype.serialize = function () {
  50943. var serializationObject = {};
  50944. serializationObject.name = this.name;
  50945. serializationObject.property = this.targetProperty;
  50946. serializationObject.framePerSecond = this.framePerSecond;
  50947. serializationObject.dataType = this.dataType;
  50948. serializationObject.loopBehavior = this.loopMode;
  50949. serializationObject.enableBlending = this.enableBlending;
  50950. serializationObject.blendingSpeed = this.blendingSpeed;
  50951. var dataType = this.dataType;
  50952. serializationObject.keys = [];
  50953. var keys = this.getKeys();
  50954. for (var index = 0; index < keys.length; index++) {
  50955. var animationKey = keys[index];
  50956. var key = {};
  50957. key.frame = animationKey.frame;
  50958. switch (dataType) {
  50959. case Animation.ANIMATIONTYPE_FLOAT:
  50960. key.values = [animationKey.value];
  50961. break;
  50962. case Animation.ANIMATIONTYPE_QUATERNION:
  50963. case Animation.ANIMATIONTYPE_MATRIX:
  50964. case Animation.ANIMATIONTYPE_VECTOR3:
  50965. case Animation.ANIMATIONTYPE_COLOR3:
  50966. key.values = animationKey.value.asArray();
  50967. break;
  50968. }
  50969. serializationObject.keys.push(key);
  50970. }
  50971. serializationObject.ranges = [];
  50972. for (var name in this._ranges) {
  50973. var source = this._ranges[name];
  50974. if (!source) {
  50975. continue;
  50976. }
  50977. var range = {};
  50978. range.name = name;
  50979. range.from = source.from;
  50980. range.to = source.to;
  50981. serializationObject.ranges.push(range);
  50982. }
  50983. return serializationObject;
  50984. };
  50985. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50986. /**
  50987. * Get the float animation type
  50988. */
  50989. get: function () {
  50990. return Animation._ANIMATIONTYPE_FLOAT;
  50991. },
  50992. enumerable: true,
  50993. configurable: true
  50994. });
  50995. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50996. /**
  50997. * Get the Vector3 animation type
  50998. */
  50999. get: function () {
  51000. return Animation._ANIMATIONTYPE_VECTOR3;
  51001. },
  51002. enumerable: true,
  51003. configurable: true
  51004. });
  51005. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51006. /**
  51007. * Get the Vector2 animation type
  51008. */
  51009. get: function () {
  51010. return Animation._ANIMATIONTYPE_VECTOR2;
  51011. },
  51012. enumerable: true,
  51013. configurable: true
  51014. });
  51015. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51016. /**
  51017. * Get the Size animation type
  51018. */
  51019. get: function () {
  51020. return Animation._ANIMATIONTYPE_SIZE;
  51021. },
  51022. enumerable: true,
  51023. configurable: true
  51024. });
  51025. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51026. /**
  51027. * Get the Quaternion animation type
  51028. */
  51029. get: function () {
  51030. return Animation._ANIMATIONTYPE_QUATERNION;
  51031. },
  51032. enumerable: true,
  51033. configurable: true
  51034. });
  51035. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51036. /**
  51037. * Get the Matrix animation type
  51038. */
  51039. get: function () {
  51040. return Animation._ANIMATIONTYPE_MATRIX;
  51041. },
  51042. enumerable: true,
  51043. configurable: true
  51044. });
  51045. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51046. /**
  51047. * Get the Color3 animation type
  51048. */
  51049. get: function () {
  51050. return Animation._ANIMATIONTYPE_COLOR3;
  51051. },
  51052. enumerable: true,
  51053. configurable: true
  51054. });
  51055. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51056. /**
  51057. * Get the Relative Loop Mode
  51058. */
  51059. get: function () {
  51060. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51061. },
  51062. enumerable: true,
  51063. configurable: true
  51064. });
  51065. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51066. /**
  51067. * Get the Cycle Loop Mode
  51068. */
  51069. get: function () {
  51070. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51071. },
  51072. enumerable: true,
  51073. configurable: true
  51074. });
  51075. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51076. /**
  51077. * Get the Constant Loop Mode
  51078. */
  51079. get: function () {
  51080. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51081. },
  51082. enumerable: true,
  51083. configurable: true
  51084. });
  51085. /** @hidden */
  51086. Animation._UniversalLerp = function (left, right, amount) {
  51087. var constructor = left.constructor;
  51088. if (constructor.Lerp) { // Lerp supported
  51089. return constructor.Lerp(left, right, amount);
  51090. }
  51091. else if (constructor.Slerp) { // Slerp supported
  51092. return constructor.Slerp(left, right, amount);
  51093. }
  51094. else if (left.toFixed) { // Number
  51095. return left * (1.0 - amount) + amount * right;
  51096. }
  51097. else { // Blending not supported
  51098. return right;
  51099. }
  51100. };
  51101. /**
  51102. * Parses an animation object and creates an animation
  51103. * @param parsedAnimation Parsed animation object
  51104. * @returns Animation object
  51105. */
  51106. Animation.Parse = function (parsedAnimation) {
  51107. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51108. var dataType = parsedAnimation.dataType;
  51109. var keys = [];
  51110. var data;
  51111. var index;
  51112. if (parsedAnimation.enableBlending) {
  51113. animation.enableBlending = parsedAnimation.enableBlending;
  51114. }
  51115. if (parsedAnimation.blendingSpeed) {
  51116. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51117. }
  51118. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51119. var key = parsedAnimation.keys[index];
  51120. var inTangent;
  51121. var outTangent;
  51122. switch (dataType) {
  51123. case Animation.ANIMATIONTYPE_FLOAT:
  51124. data = key.values[0];
  51125. if (key.values.length >= 1) {
  51126. inTangent = key.values[1];
  51127. }
  51128. if (key.values.length >= 2) {
  51129. outTangent = key.values[2];
  51130. }
  51131. break;
  51132. case Animation.ANIMATIONTYPE_QUATERNION:
  51133. data = BABYLON.Quaternion.FromArray(key.values);
  51134. if (key.values.length >= 8) {
  51135. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51136. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51137. inTangent = _inTangent;
  51138. }
  51139. }
  51140. if (key.values.length >= 12) {
  51141. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51142. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51143. outTangent = _outTangent;
  51144. }
  51145. }
  51146. break;
  51147. case Animation.ANIMATIONTYPE_MATRIX:
  51148. data = BABYLON.Matrix.FromArray(key.values);
  51149. break;
  51150. case Animation.ANIMATIONTYPE_COLOR3:
  51151. data = BABYLON.Color3.FromArray(key.values);
  51152. break;
  51153. case Animation.ANIMATIONTYPE_VECTOR3:
  51154. default:
  51155. data = BABYLON.Vector3.FromArray(key.values);
  51156. break;
  51157. }
  51158. var keyData = {};
  51159. keyData.frame = key.frame;
  51160. keyData.value = data;
  51161. if (inTangent != undefined) {
  51162. keyData.inTangent = inTangent;
  51163. }
  51164. if (outTangent != undefined) {
  51165. keyData.outTangent = outTangent;
  51166. }
  51167. keys.push(keyData);
  51168. }
  51169. animation.setKeys(keys);
  51170. if (parsedAnimation.ranges) {
  51171. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51172. data = parsedAnimation.ranges[index];
  51173. animation.createRange(data.name, data.from, data.to);
  51174. }
  51175. }
  51176. return animation;
  51177. };
  51178. /**
  51179. * Appends the serialized animations from the source animations
  51180. * @param source Source containing the animations
  51181. * @param destination Target to store the animations
  51182. */
  51183. Animation.AppendSerializedAnimations = function (source, destination) {
  51184. if (source.animations) {
  51185. destination.animations = [];
  51186. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51187. var animation = source.animations[animationIndex];
  51188. destination.animations.push(animation.serialize());
  51189. }
  51190. }
  51191. };
  51192. /**
  51193. * Use matrix interpolation instead of using direct key value when animating matrices
  51194. */
  51195. Animation.AllowMatricesInterpolation = false;
  51196. /**
  51197. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51198. */
  51199. Animation.AllowMatrixDecomposeForInterpolation = true;
  51200. // Statics
  51201. /**
  51202. * Float animation type
  51203. */
  51204. Animation._ANIMATIONTYPE_FLOAT = 0;
  51205. /**
  51206. * Vector3 animation type
  51207. */
  51208. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51209. /**
  51210. * Quaternion animation type
  51211. */
  51212. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51213. /**
  51214. * Matrix animation type
  51215. */
  51216. Animation._ANIMATIONTYPE_MATRIX = 3;
  51217. /**
  51218. * Color3 animation type
  51219. */
  51220. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51221. /**
  51222. * Vector2 animation type
  51223. */
  51224. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51225. /**
  51226. * Size animation type
  51227. */
  51228. Animation._ANIMATIONTYPE_SIZE = 6;
  51229. /**
  51230. * Relative Loop Mode
  51231. */
  51232. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51233. /**
  51234. * Cycle Loop Mode
  51235. */
  51236. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51237. /**
  51238. * Constant Loop Mode
  51239. */
  51240. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51241. return Animation;
  51242. }());
  51243. BABYLON.Animation = Animation;
  51244. })(BABYLON || (BABYLON = {}));
  51245. //# sourceMappingURL=babylon.animation.js.map
  51246. var BABYLON;
  51247. (function (BABYLON) {
  51248. /**
  51249. * This class defines the direct association between an animation and a target
  51250. */
  51251. var TargetedAnimation = /** @class */ (function () {
  51252. function TargetedAnimation() {
  51253. }
  51254. return TargetedAnimation;
  51255. }());
  51256. BABYLON.TargetedAnimation = TargetedAnimation;
  51257. /**
  51258. * Use this class to create coordinated animations on multiple targets
  51259. */
  51260. var AnimationGroup = /** @class */ (function () {
  51261. /**
  51262. * Instantiates a new Animation Group.
  51263. * This helps managing several animations at once.
  51264. * @see http://doc.babylonjs.com/how_to/group
  51265. * @param name Defines the name of the group
  51266. * @param scene Defines the scene the group belongs to
  51267. */
  51268. function AnimationGroup(
  51269. /** The name of the animation group */
  51270. name, scene) {
  51271. if (scene === void 0) { scene = null; }
  51272. this.name = name;
  51273. this._targetedAnimations = new Array();
  51274. this._animatables = new Array();
  51275. this._from = Number.MAX_VALUE;
  51276. this._to = -Number.MAX_VALUE;
  51277. this._speedRatio = 1;
  51278. /**
  51279. * This observable will notify when one animation have ended.
  51280. */
  51281. this.onAnimationEndObservable = new BABYLON.Observable();
  51282. /**
  51283. * This observable will notify when all animations have ended.
  51284. */
  51285. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  51286. /**
  51287. * This observable will notify when all animations have paused.
  51288. */
  51289. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  51290. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51291. this._scene.animationGroups.push(this);
  51292. }
  51293. Object.defineProperty(AnimationGroup.prototype, "from", {
  51294. /**
  51295. * Gets the first frame
  51296. */
  51297. get: function () {
  51298. return this._from;
  51299. },
  51300. enumerable: true,
  51301. configurable: true
  51302. });
  51303. Object.defineProperty(AnimationGroup.prototype, "to", {
  51304. /**
  51305. * Gets the last frame
  51306. */
  51307. get: function () {
  51308. return this._to;
  51309. },
  51310. enumerable: true,
  51311. configurable: true
  51312. });
  51313. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51314. /**
  51315. * Define if the animations are started
  51316. */
  51317. get: function () {
  51318. return this._isStarted;
  51319. },
  51320. enumerable: true,
  51321. configurable: true
  51322. });
  51323. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51324. /**
  51325. * Gets or sets the speed ratio to use for all animations
  51326. */
  51327. get: function () {
  51328. return this._speedRatio;
  51329. },
  51330. /**
  51331. * Gets or sets the speed ratio to use for all animations
  51332. */
  51333. set: function (value) {
  51334. if (this._speedRatio === value) {
  51335. return;
  51336. }
  51337. this._speedRatio = value;
  51338. for (var index = 0; index < this._animatables.length; index++) {
  51339. var animatable = this._animatables[index];
  51340. animatable.speedRatio = this._speedRatio;
  51341. }
  51342. },
  51343. enumerable: true,
  51344. configurable: true
  51345. });
  51346. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51347. /**
  51348. * Gets the targeted animations for this animation group
  51349. */
  51350. get: function () {
  51351. return this._targetedAnimations;
  51352. },
  51353. enumerable: true,
  51354. configurable: true
  51355. });
  51356. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51357. /**
  51358. * returning the list of animatables controlled by this animation group.
  51359. */
  51360. get: function () {
  51361. return this._animatables;
  51362. },
  51363. enumerable: true,
  51364. configurable: true
  51365. });
  51366. /**
  51367. * Add an animation (with its target) in the group
  51368. * @param animation defines the animation we want to add
  51369. * @param target defines the target of the animation
  51370. * @returns the {BABYLON.TargetedAnimation} object
  51371. */
  51372. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51373. var targetedAnimation = {
  51374. animation: animation,
  51375. target: target
  51376. };
  51377. var keys = animation.getKeys();
  51378. if (this._from > keys[0].frame) {
  51379. this._from = keys[0].frame;
  51380. }
  51381. if (this._to < keys[keys.length - 1].frame) {
  51382. this._to = keys[keys.length - 1].frame;
  51383. }
  51384. this._targetedAnimations.push(targetedAnimation);
  51385. return targetedAnimation;
  51386. };
  51387. /**
  51388. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51389. * It can add constant keys at begin or end
  51390. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51391. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51392. * @returns the animation group
  51393. */
  51394. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51395. if (beginFrame === void 0) { beginFrame = null; }
  51396. if (endFrame === void 0) { endFrame = null; }
  51397. if (beginFrame == null)
  51398. beginFrame = this._from;
  51399. if (endFrame == null)
  51400. endFrame = this._to;
  51401. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51402. var targetedAnimation = this._targetedAnimations[index];
  51403. var keys = targetedAnimation.animation.getKeys();
  51404. var startKey = keys[0];
  51405. var endKey = keys[keys.length - 1];
  51406. if (startKey.frame > beginFrame) {
  51407. var newKey = {
  51408. frame: beginFrame,
  51409. value: startKey.value,
  51410. inTangent: startKey.inTangent,
  51411. outTangent: startKey.outTangent,
  51412. interpolation: startKey.interpolation
  51413. };
  51414. keys.splice(0, 0, newKey);
  51415. }
  51416. if (endKey.frame < endFrame) {
  51417. var newKey = {
  51418. frame: endFrame,
  51419. value: endKey.value,
  51420. inTangent: endKey.outTangent,
  51421. outTangent: endKey.outTangent,
  51422. interpolation: endKey.interpolation
  51423. };
  51424. keys.push(newKey);
  51425. }
  51426. }
  51427. this._from = beginFrame;
  51428. this._to = endFrame;
  51429. return this;
  51430. };
  51431. /**
  51432. * Start all animations on given targets
  51433. * @param loop defines if animations must loop
  51434. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51435. * @param from defines the from key (optional)
  51436. * @param to defines the to key (optional)
  51437. * @returns the current animation group
  51438. */
  51439. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51440. var _this = this;
  51441. if (loop === void 0) { loop = false; }
  51442. if (speedRatio === void 0) { speedRatio = 1; }
  51443. if (this._isStarted || this._targetedAnimations.length === 0) {
  51444. return this;
  51445. }
  51446. var _loop_1 = function (targetedAnimation) {
  51447. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51448. animatable.onAnimationEnd = function () {
  51449. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51450. _this._checkAnimationGroupEnded(animatable);
  51451. };
  51452. this_1._animatables.push(animatable);
  51453. };
  51454. var this_1 = this;
  51455. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51456. var targetedAnimation = _a[_i];
  51457. _loop_1(targetedAnimation);
  51458. }
  51459. this._speedRatio = speedRatio;
  51460. this._isStarted = true;
  51461. return this;
  51462. };
  51463. /**
  51464. * Pause all animations
  51465. * @returns the animation group
  51466. */
  51467. AnimationGroup.prototype.pause = function () {
  51468. if (!this._isStarted) {
  51469. return this;
  51470. }
  51471. for (var index = 0; index < this._animatables.length; index++) {
  51472. var animatable = this._animatables[index];
  51473. animatable.pause();
  51474. }
  51475. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51476. return this;
  51477. };
  51478. /**
  51479. * Play all animations to initial state
  51480. * This function will start() the animations if they were not started or will restart() them if they were paused
  51481. * @param loop defines if animations must loop
  51482. * @returns the animation group
  51483. */
  51484. AnimationGroup.prototype.play = function (loop) {
  51485. // only if all animatables are ready and exist
  51486. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51487. if (loop !== undefined) {
  51488. for (var index = 0; index < this._animatables.length; index++) {
  51489. var animatable = this._animatables[index];
  51490. animatable.loopAnimation = loop;
  51491. }
  51492. }
  51493. this.restart();
  51494. }
  51495. else {
  51496. this.stop();
  51497. this.start(loop, this._speedRatio);
  51498. }
  51499. return this;
  51500. };
  51501. /**
  51502. * Reset all animations to initial state
  51503. * @returns the animation group
  51504. */
  51505. AnimationGroup.prototype.reset = function () {
  51506. if (!this._isStarted) {
  51507. return this;
  51508. }
  51509. for (var index = 0; index < this._animatables.length; index++) {
  51510. var animatable = this._animatables[index];
  51511. animatable.reset();
  51512. }
  51513. return this;
  51514. };
  51515. /**
  51516. * Restart animations from key 0
  51517. * @returns the animation group
  51518. */
  51519. AnimationGroup.prototype.restart = function () {
  51520. if (!this._isStarted) {
  51521. return this;
  51522. }
  51523. for (var index = 0; index < this._animatables.length; index++) {
  51524. var animatable = this._animatables[index];
  51525. animatable.restart();
  51526. }
  51527. return this;
  51528. };
  51529. /**
  51530. * Stop all animations
  51531. * @returns the animation group
  51532. */
  51533. AnimationGroup.prototype.stop = function () {
  51534. if (!this._isStarted) {
  51535. return this;
  51536. }
  51537. var list = this._animatables.slice();
  51538. for (var index = 0; index < list.length; index++) {
  51539. list[index].stop();
  51540. }
  51541. this._isStarted = false;
  51542. return this;
  51543. };
  51544. /**
  51545. * Set animation weight for all animatables
  51546. * @param weight defines the weight to use
  51547. * @return the animationGroup
  51548. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51549. */
  51550. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51551. for (var index = 0; index < this._animatables.length; index++) {
  51552. var animatable = this._animatables[index];
  51553. animatable.weight = weight;
  51554. }
  51555. return this;
  51556. };
  51557. /**
  51558. * Synchronize and normalize all animatables with a source animatable
  51559. * @param root defines the root animatable to synchronize with
  51560. * @return the animationGroup
  51561. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51562. */
  51563. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51564. for (var index = 0; index < this._animatables.length; index++) {
  51565. var animatable = this._animatables[index];
  51566. animatable.syncWith(root);
  51567. }
  51568. return this;
  51569. };
  51570. /**
  51571. * Goes to a specific frame in this animation group
  51572. * @param frame the frame number to go to
  51573. * @return the animationGroup
  51574. */
  51575. AnimationGroup.prototype.goToFrame = function (frame) {
  51576. if (!this._isStarted) {
  51577. return this;
  51578. }
  51579. for (var index = 0; index < this._animatables.length; index++) {
  51580. var animatable = this._animatables[index];
  51581. animatable.goToFrame(frame);
  51582. }
  51583. return this;
  51584. };
  51585. /**
  51586. * Dispose all associated resources
  51587. */
  51588. AnimationGroup.prototype.dispose = function () {
  51589. this._targetedAnimations = [];
  51590. this._animatables = [];
  51591. var index = this._scene.animationGroups.indexOf(this);
  51592. if (index > -1) {
  51593. this._scene.animationGroups.splice(index, 1);
  51594. }
  51595. };
  51596. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51597. // animatable should be taken out of the array
  51598. var idx = this._animatables.indexOf(animatable);
  51599. if (idx > -1) {
  51600. this._animatables.splice(idx, 1);
  51601. }
  51602. // all animatables were removed? animation group ended!
  51603. if (this._animatables.length === 0) {
  51604. this._isStarted = false;
  51605. this.onAnimationGroupEndObservable.notifyObservers(this);
  51606. }
  51607. };
  51608. // Statics
  51609. /**
  51610. * Returns a new AnimationGroup object parsed from the source provided.
  51611. * @param parsedAnimationGroup defines the source
  51612. * @param scene defines the scene that will receive the animationGroup
  51613. * @returns a new AnimationGroup
  51614. */
  51615. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  51616. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  51617. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  51618. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  51619. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  51620. var id = targetedAnimation.targetId;
  51621. var targetNode = scene.getNodeByID(id);
  51622. if (targetNode != null)
  51623. animationGroup.addTargetedAnimation(animation, targetNode);
  51624. }
  51625. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  51626. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  51627. return animationGroup;
  51628. };
  51629. /**
  51630. * Returns the string "AnimationGroup"
  51631. * @returns "AnimationGroup"
  51632. */
  51633. AnimationGroup.prototype.getClassName = function () {
  51634. return "AnimationGroup";
  51635. };
  51636. /**
  51637. * Creates a detailled string about the object
  51638. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  51639. * @returns a string representing the object
  51640. */
  51641. AnimationGroup.prototype.toString = function (fullDetails) {
  51642. var ret = "Name: " + this.name;
  51643. ret += ", type: " + this.getClassName();
  51644. if (fullDetails) {
  51645. ret += ", from: " + this._from;
  51646. ret += ", to: " + this._to;
  51647. ret += ", isStarted: " + this._isStarted;
  51648. ret += ", speedRatio: " + this._speedRatio;
  51649. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  51650. ret += ", animatables length: " + this._animatables;
  51651. }
  51652. return ret;
  51653. };
  51654. return AnimationGroup;
  51655. }());
  51656. BABYLON.AnimationGroup = AnimationGroup;
  51657. })(BABYLON || (BABYLON = {}));
  51658. //# sourceMappingURL=babylon.animationGroup.js.map
  51659. var BABYLON;
  51660. (function (BABYLON) {
  51661. // Static values to help the garbage collector
  51662. // Quaternion
  51663. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  51664. // Vector3
  51665. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  51666. // Vector2
  51667. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  51668. // Size
  51669. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  51670. // Color3
  51671. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  51672. /**
  51673. * Defines a runtime animation
  51674. */
  51675. var RuntimeAnimation = /** @class */ (function () {
  51676. /**
  51677. * Create a new RuntimeAnimation object
  51678. * @param target defines the target of the animation
  51679. * @param animation defines the source animation object
  51680. * @param scene defines the hosting scene
  51681. * @param host defines the initiating Animatable
  51682. */
  51683. function RuntimeAnimation(target, animation, scene, host) {
  51684. var _this = this;
  51685. this._events = new Array();
  51686. /**
  51687. * The current frame of the runtime animation
  51688. */
  51689. this._currentFrame = 0;
  51690. /**
  51691. * The original value of the runtime animation
  51692. */
  51693. this._originalValue = new Array();
  51694. /**
  51695. * The offsets cache of the runtime animation
  51696. */
  51697. this._offsetsCache = {};
  51698. /**
  51699. * The high limits cache of the runtime animation
  51700. */
  51701. this._highLimitsCache = {};
  51702. /**
  51703. * Specifies if the runtime animation has been stopped
  51704. */
  51705. this._stopped = false;
  51706. /**
  51707. * The blending factor of the runtime animation
  51708. */
  51709. this._blendingFactor = 0;
  51710. /**
  51711. * The target path of the runtime animation
  51712. */
  51713. this._targetPath = "";
  51714. /**
  51715. * The weight of the runtime animation
  51716. */
  51717. this._weight = 1.0;
  51718. /**
  51719. * The ratio offset of the runtime animation
  51720. */
  51721. this._ratioOffset = 0;
  51722. /**
  51723. * The previous delay of the runtime animation
  51724. */
  51725. this._previousDelay = 0;
  51726. /**
  51727. * The previous ratio of the runtime animation
  51728. */
  51729. this._previousRatio = 0;
  51730. this._animation = animation;
  51731. this._target = target;
  51732. this._scene = scene;
  51733. this._host = host;
  51734. animation._runtimeAnimations.push(this);
  51735. // Cloning events locally
  51736. var events = animation.getEvents();
  51737. if (events && events.length > 0) {
  51738. events.forEach(function (e) {
  51739. _this._events.push(e._clone());
  51740. });
  51741. }
  51742. }
  51743. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51744. /**
  51745. * Gets the current frame of the runtime animation
  51746. */
  51747. get: function () {
  51748. return this._currentFrame;
  51749. },
  51750. enumerable: true,
  51751. configurable: true
  51752. });
  51753. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51754. /**
  51755. * Gets the weight of the runtime animation
  51756. */
  51757. get: function () {
  51758. return this._weight;
  51759. },
  51760. enumerable: true,
  51761. configurable: true
  51762. });
  51763. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51764. /**
  51765. * Gets the current value of the runtime animation
  51766. */
  51767. get: function () {
  51768. return this._currentValue;
  51769. },
  51770. enumerable: true,
  51771. configurable: true
  51772. });
  51773. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51774. /**
  51775. * Gets the target path of the runtime animation
  51776. */
  51777. get: function () {
  51778. return this._targetPath;
  51779. },
  51780. enumerable: true,
  51781. configurable: true
  51782. });
  51783. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51784. /**
  51785. * Gets the actual target of the runtime animation
  51786. */
  51787. get: function () {
  51788. return this._activeTarget;
  51789. },
  51790. enumerable: true,
  51791. configurable: true
  51792. });
  51793. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51794. /**
  51795. * Gets the animation from the runtime animation
  51796. */
  51797. get: function () {
  51798. return this._animation;
  51799. },
  51800. enumerable: true,
  51801. configurable: true
  51802. });
  51803. /**
  51804. * Resets the runtime animation to the beginning
  51805. * @param restoreOriginal defines whether to restore the target property to the original value
  51806. */
  51807. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51808. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51809. if (restoreOriginal) {
  51810. if (this._target instanceof Array) {
  51811. var index = 0;
  51812. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51813. var target = _a[_i];
  51814. if (this._originalValue[index] !== undefined) {
  51815. this._setValue(target, this._originalValue[index], -1);
  51816. }
  51817. index++;
  51818. }
  51819. }
  51820. else {
  51821. if (this._originalValue[0] !== undefined) {
  51822. this._setValue(this._target, this._originalValue[0], -1);
  51823. }
  51824. }
  51825. }
  51826. this._offsetsCache = {};
  51827. this._highLimitsCache = {};
  51828. this._currentFrame = 0;
  51829. this._blendingFactor = 0;
  51830. this._originalValue = new Array();
  51831. // Events
  51832. for (var index = 0; index < this._events.length; index++) {
  51833. this._events[index].isDone = false;
  51834. }
  51835. };
  51836. /**
  51837. * Specifies if the runtime animation is stopped
  51838. * @returns Boolean specifying if the runtime animation is stopped
  51839. */
  51840. RuntimeAnimation.prototype.isStopped = function () {
  51841. return this._stopped;
  51842. };
  51843. /**
  51844. * Disposes of the runtime animation
  51845. */
  51846. RuntimeAnimation.prototype.dispose = function () {
  51847. var index = this._animation.runtimeAnimations.indexOf(this);
  51848. if (index > -1) {
  51849. this._animation.runtimeAnimations.splice(index, 1);
  51850. }
  51851. };
  51852. /**
  51853. * Interpolates the animation from the current frame
  51854. * @param currentFrame The frame to interpolate the animation to
  51855. * @param repeatCount The number of times that the animation should loop
  51856. * @param loopMode The type of looping mode to use
  51857. * @param offsetValue Animation offset value
  51858. * @param highLimitValue The high limit value
  51859. * @returns The interpolated value
  51860. */
  51861. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51862. this._currentFrame = currentFrame;
  51863. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51864. this._workValue = BABYLON.Matrix.Zero();
  51865. }
  51866. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51867. };
  51868. /**
  51869. * Apply the interpolated value to the target
  51870. * @param currentValue defines the value computed by the animation
  51871. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51872. */
  51873. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51874. if (weight === void 0) { weight = 1.0; }
  51875. if (this._target instanceof Array) {
  51876. var index = 0;
  51877. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51878. var target = _a[_i];
  51879. this._setValue(target, currentValue, weight, index);
  51880. index++;
  51881. }
  51882. }
  51883. else {
  51884. this._setValue(this._target, currentValue, weight);
  51885. }
  51886. };
  51887. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51888. if (targetIndex === void 0) { targetIndex = 0; }
  51889. // Set value
  51890. var path;
  51891. var destination;
  51892. var targetPropertyPath = this._animation.targetPropertyPath;
  51893. if (targetPropertyPath.length > 1) {
  51894. var property = target[targetPropertyPath[0]];
  51895. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51896. property = property[targetPropertyPath[index]];
  51897. }
  51898. path = targetPropertyPath[targetPropertyPath.length - 1];
  51899. destination = property;
  51900. }
  51901. else {
  51902. path = targetPropertyPath[0];
  51903. destination = target;
  51904. }
  51905. this._targetPath = path;
  51906. this._activeTarget = destination;
  51907. this._weight = weight;
  51908. if (this._originalValue[targetIndex] === undefined) {
  51909. var originalValue = void 0;
  51910. if (destination.getRestPose && path === "_matrix") { // For bones
  51911. originalValue = destination.getRestPose();
  51912. }
  51913. else {
  51914. originalValue = destination[path];
  51915. }
  51916. if (originalValue && originalValue.clone) {
  51917. this._originalValue[targetIndex] = originalValue.clone();
  51918. }
  51919. else {
  51920. this._originalValue[targetIndex] = originalValue;
  51921. }
  51922. }
  51923. // Blending
  51924. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51925. if (enableBlending && this._blendingFactor <= 1.0) {
  51926. if (!this._originalBlendValue) {
  51927. var originalValue = destination[path];
  51928. if (originalValue.clone) {
  51929. this._originalBlendValue = originalValue.clone();
  51930. }
  51931. else {
  51932. this._originalBlendValue = originalValue;
  51933. }
  51934. }
  51935. if (this._originalBlendValue.m) { // Matrix
  51936. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51937. if (this._currentValue) {
  51938. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51939. }
  51940. else {
  51941. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51942. }
  51943. }
  51944. else {
  51945. if (this._currentValue) {
  51946. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51947. }
  51948. else {
  51949. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51950. }
  51951. }
  51952. }
  51953. else {
  51954. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51955. }
  51956. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51957. this._blendingFactor += blendingSpeed;
  51958. }
  51959. else {
  51960. this._currentValue = currentValue;
  51961. }
  51962. if (weight !== -1.0) {
  51963. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51964. }
  51965. else {
  51966. destination[path] = this._currentValue;
  51967. }
  51968. if (target.markAsDirty) {
  51969. target.markAsDirty(this._animation.targetProperty);
  51970. }
  51971. };
  51972. /**
  51973. * Gets the loop pmode of the runtime animation
  51974. * @returns Loop Mode
  51975. */
  51976. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51977. if (this._target && this._target.animationPropertiesOverride) {
  51978. return this._target.animationPropertiesOverride.loopMode;
  51979. }
  51980. return this._animation.loopMode;
  51981. };
  51982. /**
  51983. * Move the current animation to a given frame
  51984. * @param frame defines the frame to move to
  51985. */
  51986. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51987. var keys = this._animation.getKeys();
  51988. if (frame < keys[0].frame) {
  51989. frame = keys[0].frame;
  51990. }
  51991. else if (frame > keys[keys.length - 1].frame) {
  51992. frame = keys[keys.length - 1].frame;
  51993. }
  51994. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51995. this.setValue(currentValue, -1);
  51996. };
  51997. /**
  51998. * @hidden Internal use only
  51999. */
  52000. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52001. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52002. this._ratioOffset = this._previousRatio - newRatio;
  52003. };
  52004. /**
  52005. * Execute the current animation
  52006. * @param delay defines the delay to add to the current frame
  52007. * @param from defines the lower bound of the animation range
  52008. * @param to defines the upper bound of the animation range
  52009. * @param loop defines if the current animation must loop
  52010. * @param speedRatio defines the current speed ratio
  52011. * @param weight defines the weight of the animation (default is -1 so no weight)
  52012. * @returns a boolean indicating if the animation is running
  52013. */
  52014. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52015. if (weight === void 0) { weight = -1.0; }
  52016. var targetPropertyPath = this._animation.targetPropertyPath;
  52017. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52018. this._stopped = true;
  52019. return false;
  52020. }
  52021. var returnValue = true;
  52022. var keys = this._animation.getKeys();
  52023. // Adding a start key at frame 0 if missing
  52024. if (keys[0].frame !== 0) {
  52025. var newKey = { frame: 0, value: keys[0].value };
  52026. keys.splice(0, 0, newKey);
  52027. }
  52028. // Adding a duplicate key when there is only one key at frame zero
  52029. else if (keys.length === 1) {
  52030. var newKey = { frame: 0.001, value: keys[0].value };
  52031. keys.push(newKey);
  52032. }
  52033. // Check limits
  52034. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52035. from = keys[0].frame;
  52036. }
  52037. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52038. to = keys[keys.length - 1].frame;
  52039. }
  52040. //to and from cannot be the same key
  52041. if (from === to) {
  52042. if (from > keys[0].frame) {
  52043. from--;
  52044. }
  52045. else if (to < keys[keys.length - 1].frame) {
  52046. to++;
  52047. }
  52048. }
  52049. // Compute ratio
  52050. var range = to - from;
  52051. var offsetValue;
  52052. // ratio represents the frame delta between from and to
  52053. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52054. var highLimitValue = 0;
  52055. this._previousDelay = delay;
  52056. this._previousRatio = ratio;
  52057. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  52058. returnValue = false;
  52059. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52060. }
  52061. else {
  52062. // Get max value if required
  52063. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52064. var keyOffset = to.toString() + from.toString();
  52065. if (!this._offsetsCache[keyOffset]) {
  52066. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52067. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52068. switch (this._animation.dataType) {
  52069. // Float
  52070. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52071. this._offsetsCache[keyOffset] = toValue - fromValue;
  52072. break;
  52073. // Quaternion
  52074. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52075. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52076. break;
  52077. // Vector3
  52078. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52079. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52080. // Vector2
  52081. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52082. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52083. // Size
  52084. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52085. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52086. // Color3
  52087. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52088. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52089. default:
  52090. break;
  52091. }
  52092. this._highLimitsCache[keyOffset] = toValue;
  52093. }
  52094. highLimitValue = this._highLimitsCache[keyOffset];
  52095. offsetValue = this._offsetsCache[keyOffset];
  52096. }
  52097. }
  52098. if (offsetValue === undefined) {
  52099. switch (this._animation.dataType) {
  52100. // Float
  52101. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52102. offsetValue = 0;
  52103. break;
  52104. // Quaternion
  52105. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52106. offsetValue = _staticOffsetValueQuaternion;
  52107. break;
  52108. // Vector3
  52109. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52110. offsetValue = _staticOffsetValueVector3;
  52111. break;
  52112. // Vector2
  52113. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52114. offsetValue = _staticOffsetValueVector2;
  52115. break;
  52116. // Size
  52117. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52118. offsetValue = _staticOffsetValueSize;
  52119. break;
  52120. // Color3
  52121. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52122. offsetValue = _staticOffsetValueColor3;
  52123. }
  52124. }
  52125. // Compute value
  52126. var repeatCount = (ratio / range) >> 0;
  52127. var currentFrame = returnValue ? from + ratio % range : to;
  52128. // Need to normalize?
  52129. if (this._host && this._host.syncRoot) {
  52130. var syncRoot = this._host.syncRoot;
  52131. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52132. currentFrame = from + (to - from) * hostNormalizedFrame;
  52133. }
  52134. // Reset events if looping
  52135. var events = this._events;
  52136. if (range > 0 && this.currentFrame > currentFrame ||
  52137. range < 0 && this.currentFrame < currentFrame) {
  52138. // Need to reset animation events
  52139. for (var index = 0; index < events.length; index++) {
  52140. if (!events[index].onlyOnce) {
  52141. // reset event, the animation is looping
  52142. events[index].isDone = false;
  52143. }
  52144. }
  52145. }
  52146. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52147. // Set value
  52148. this.setValue(currentValue, weight);
  52149. // Check events
  52150. for (var index = 0; index < events.length; index++) {
  52151. // Make sure current frame has passed event frame and that event frame is within the current range
  52152. // Also, handle both forward and reverse animations
  52153. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52154. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52155. var event = events[index];
  52156. if (!event.isDone) {
  52157. // If event should be done only once, remove it.
  52158. if (event.onlyOnce) {
  52159. events.splice(index, 1);
  52160. index--;
  52161. }
  52162. event.isDone = true;
  52163. event.action(currentFrame);
  52164. } // Don't do anything if the event has already be done.
  52165. }
  52166. }
  52167. if (!returnValue) {
  52168. this._stopped = true;
  52169. }
  52170. return returnValue;
  52171. };
  52172. return RuntimeAnimation;
  52173. }());
  52174. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52175. })(BABYLON || (BABYLON = {}));
  52176. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52177. var BABYLON;
  52178. (function (BABYLON) {
  52179. /**
  52180. * Class used to store an actual running animation
  52181. */
  52182. var Animatable = /** @class */ (function () {
  52183. /**
  52184. * Creates a new Animatable
  52185. * @param scene defines the hosting scene
  52186. * @param target defines the target object
  52187. * @param fromFrame defines the starting frame number (default is 0)
  52188. * @param toFrame defines the ending frame number (default is 100)
  52189. * @param loopAnimation defines if the animation must loop (default is false)
  52190. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  52191. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  52192. * @param animations defines a group of animation to add to the new Animatable
  52193. */
  52194. function Animatable(scene,
  52195. /** defines the target object */
  52196. target,
  52197. /** defines the starting frame number (default is 0) */
  52198. fromFrame,
  52199. /** defines the ending frame number (default is 100) */
  52200. toFrame,
  52201. /** defines if the animation must loop (default is false) */
  52202. loopAnimation, speedRatio,
  52203. /** defines a callback to call when animation ends if it is not looping */
  52204. onAnimationEnd, animations) {
  52205. if (fromFrame === void 0) { fromFrame = 0; }
  52206. if (toFrame === void 0) { toFrame = 100; }
  52207. if (loopAnimation === void 0) { loopAnimation = false; }
  52208. if (speedRatio === void 0) { speedRatio = 1.0; }
  52209. this.target = target;
  52210. this.fromFrame = fromFrame;
  52211. this.toFrame = toFrame;
  52212. this.loopAnimation = loopAnimation;
  52213. this.onAnimationEnd = onAnimationEnd;
  52214. this._localDelayOffset = null;
  52215. this._pausedDelay = null;
  52216. this._runtimeAnimations = new Array();
  52217. this._paused = false;
  52218. this._speedRatio = 1;
  52219. this._weight = -1.0;
  52220. /**
  52221. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  52222. * This will only apply for non looping animation (default is true)
  52223. */
  52224. this.disposeOnEnd = true;
  52225. /**
  52226. * Gets a boolean indicating if the animation has started
  52227. */
  52228. this.animationStarted = false;
  52229. /**
  52230. * Observer raised when the animation ends
  52231. */
  52232. this.onAnimationEndObservable = new BABYLON.Observable();
  52233. this._scene = scene;
  52234. if (animations) {
  52235. this.appendAnimations(target, animations);
  52236. }
  52237. this._speedRatio = speedRatio;
  52238. scene._activeAnimatables.push(this);
  52239. }
  52240. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52241. /**
  52242. * Gets the root Animatable used to synchronize and normalize animations
  52243. */
  52244. get: function () {
  52245. return this._syncRoot;
  52246. },
  52247. enumerable: true,
  52248. configurable: true
  52249. });
  52250. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52251. /**
  52252. * Gets the current frame of the first RuntimeAnimation
  52253. * Used to synchronize Animatables
  52254. */
  52255. get: function () {
  52256. if (this._runtimeAnimations.length === 0) {
  52257. return 0;
  52258. }
  52259. return this._runtimeAnimations[0].currentFrame;
  52260. },
  52261. enumerable: true,
  52262. configurable: true
  52263. });
  52264. Object.defineProperty(Animatable.prototype, "weight", {
  52265. /**
  52266. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52267. */
  52268. get: function () {
  52269. return this._weight;
  52270. },
  52271. set: function (value) {
  52272. if (value === -1) { // -1 is ok and means no weight
  52273. this._weight = -1;
  52274. return;
  52275. }
  52276. // Else weight must be in [0, 1] range
  52277. this._weight = Math.min(Math.max(value, 0), 1.0);
  52278. },
  52279. enumerable: true,
  52280. configurable: true
  52281. });
  52282. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52283. /**
  52284. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52285. */
  52286. get: function () {
  52287. return this._speedRatio;
  52288. },
  52289. set: function (value) {
  52290. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52291. var animation = this._runtimeAnimations[index];
  52292. animation._prepareForSpeedRatioChange(value);
  52293. }
  52294. this._speedRatio = value;
  52295. },
  52296. enumerable: true,
  52297. configurable: true
  52298. });
  52299. // Methods
  52300. /**
  52301. * Synchronize and normalize current Animatable with a source Animatable
  52302. * This is useful when using animation weights and when animations are not of the same length
  52303. * @param root defines the root Animatable to synchronize with
  52304. * @returns the current Animatable
  52305. */
  52306. Animatable.prototype.syncWith = function (root) {
  52307. this._syncRoot = root;
  52308. if (root) {
  52309. // Make sure this animatable will animate after the root
  52310. var index = this._scene._activeAnimatables.indexOf(this);
  52311. if (index > -1) {
  52312. this._scene._activeAnimatables.splice(index, 1);
  52313. this._scene._activeAnimatables.push(this);
  52314. }
  52315. }
  52316. return this;
  52317. };
  52318. /**
  52319. * Gets the list of runtime animations
  52320. * @returns an array of RuntimeAnimation
  52321. */
  52322. Animatable.prototype.getAnimations = function () {
  52323. return this._runtimeAnimations;
  52324. };
  52325. /**
  52326. * Adds more animations to the current animatable
  52327. * @param target defines the target of the animations
  52328. * @param animations defines the new animations to add
  52329. */
  52330. Animatable.prototype.appendAnimations = function (target, animations) {
  52331. for (var index = 0; index < animations.length; index++) {
  52332. var animation = animations[index];
  52333. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52334. }
  52335. };
  52336. /**
  52337. * Gets the source animation for a specific property
  52338. * @param property defines the propertyu to look for
  52339. * @returns null or the source animation for the given property
  52340. */
  52341. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52342. var runtimeAnimations = this._runtimeAnimations;
  52343. for (var index = 0; index < runtimeAnimations.length; index++) {
  52344. if (runtimeAnimations[index].animation.targetProperty === property) {
  52345. return runtimeAnimations[index].animation;
  52346. }
  52347. }
  52348. return null;
  52349. };
  52350. /**
  52351. * Gets the runtime animation for a specific property
  52352. * @param property defines the propertyu to look for
  52353. * @returns null or the runtime animation for the given property
  52354. */
  52355. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52356. var runtimeAnimations = this._runtimeAnimations;
  52357. for (var index = 0; index < runtimeAnimations.length; index++) {
  52358. if (runtimeAnimations[index].animation.targetProperty === property) {
  52359. return runtimeAnimations[index];
  52360. }
  52361. }
  52362. return null;
  52363. };
  52364. /**
  52365. * Resets the animatable to its original state
  52366. */
  52367. Animatable.prototype.reset = function () {
  52368. var runtimeAnimations = this._runtimeAnimations;
  52369. for (var index = 0; index < runtimeAnimations.length; index++) {
  52370. runtimeAnimations[index].reset(true);
  52371. }
  52372. this._localDelayOffset = null;
  52373. this._pausedDelay = null;
  52374. };
  52375. /**
  52376. * Allows the animatable to blend with current running animations
  52377. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52378. * @param blendingSpeed defines the blending speed to use
  52379. */
  52380. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52381. var runtimeAnimations = this._runtimeAnimations;
  52382. for (var index = 0; index < runtimeAnimations.length; index++) {
  52383. runtimeAnimations[index].animation.enableBlending = true;
  52384. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52385. }
  52386. };
  52387. /**
  52388. * Disable animation blending
  52389. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52390. */
  52391. Animatable.prototype.disableBlending = function () {
  52392. var runtimeAnimations = this._runtimeAnimations;
  52393. for (var index = 0; index < runtimeAnimations.length; index++) {
  52394. runtimeAnimations[index].animation.enableBlending = false;
  52395. }
  52396. };
  52397. /**
  52398. * Jump directly to a given frame
  52399. * @param frame defines the frame to jump to
  52400. */
  52401. Animatable.prototype.goToFrame = function (frame) {
  52402. var runtimeAnimations = this._runtimeAnimations;
  52403. if (runtimeAnimations[0]) {
  52404. var fps = runtimeAnimations[0].animation.framePerSecond;
  52405. var currentFrame = runtimeAnimations[0].currentFrame;
  52406. var adjustTime = frame - currentFrame;
  52407. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52408. if (this._localDelayOffset === null) {
  52409. this._localDelayOffset = 0;
  52410. }
  52411. this._localDelayOffset -= delay;
  52412. }
  52413. for (var index = 0; index < runtimeAnimations.length; index++) {
  52414. runtimeAnimations[index].goToFrame(frame);
  52415. }
  52416. };
  52417. /**
  52418. * Pause the animation
  52419. */
  52420. Animatable.prototype.pause = function () {
  52421. if (this._paused) {
  52422. return;
  52423. }
  52424. this._paused = true;
  52425. };
  52426. /**
  52427. * Restart the animation
  52428. */
  52429. Animatable.prototype.restart = function () {
  52430. this._paused = false;
  52431. };
  52432. Animatable.prototype._raiseOnAnimationEnd = function () {
  52433. if (this.onAnimationEnd) {
  52434. this.onAnimationEnd();
  52435. }
  52436. this.onAnimationEndObservable.notifyObservers(this);
  52437. };
  52438. /**
  52439. * Stop and delete the current animation
  52440. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52441. * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
  52442. */
  52443. Animatable.prototype.stop = function (animationName, targetMask) {
  52444. if (animationName || targetMask) {
  52445. var idx = this._scene._activeAnimatables.indexOf(this);
  52446. if (idx > -1) {
  52447. var runtimeAnimations = this._runtimeAnimations;
  52448. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52449. var runtimeAnimation = runtimeAnimations[index];
  52450. if (animationName && runtimeAnimation.animation.name != animationName) {
  52451. continue;
  52452. }
  52453. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52454. continue;
  52455. }
  52456. runtimeAnimation.dispose();
  52457. runtimeAnimations.splice(index, 1);
  52458. }
  52459. if (runtimeAnimations.length == 0) {
  52460. this._scene._activeAnimatables.splice(idx, 1);
  52461. this._raiseOnAnimationEnd();
  52462. }
  52463. }
  52464. }
  52465. else {
  52466. var index = this._scene._activeAnimatables.indexOf(this);
  52467. if (index > -1) {
  52468. this._scene._activeAnimatables.splice(index, 1);
  52469. var runtimeAnimations = this._runtimeAnimations;
  52470. for (var index = 0; index < runtimeAnimations.length; index++) {
  52471. runtimeAnimations[index].dispose();
  52472. }
  52473. this._raiseOnAnimationEnd();
  52474. }
  52475. }
  52476. };
  52477. /**
  52478. * Wait asynchronously for the animation to end
  52479. * @returns a promise which will be fullfilled when the animation ends
  52480. */
  52481. Animatable.prototype.waitAsync = function () {
  52482. var _this = this;
  52483. return new Promise(function (resolve, reject) {
  52484. _this.onAnimationEndObservable.add(function () {
  52485. resolve(_this);
  52486. }, undefined, undefined, _this, true);
  52487. });
  52488. };
  52489. /** @hidden */
  52490. Animatable.prototype._animate = function (delay) {
  52491. if (this._paused) {
  52492. this.animationStarted = false;
  52493. if (this._pausedDelay === null) {
  52494. this._pausedDelay = delay;
  52495. }
  52496. return true;
  52497. }
  52498. if (this._localDelayOffset === null) {
  52499. this._localDelayOffset = delay;
  52500. this._pausedDelay = null;
  52501. }
  52502. else if (this._pausedDelay !== null) {
  52503. this._localDelayOffset += delay - this._pausedDelay;
  52504. this._pausedDelay = null;
  52505. }
  52506. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52507. return true;
  52508. }
  52509. // Animating
  52510. var running = false;
  52511. var runtimeAnimations = this._runtimeAnimations;
  52512. var index;
  52513. for (index = 0; index < runtimeAnimations.length; index++) {
  52514. var animation = runtimeAnimations[index];
  52515. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52516. running = running || isRunning;
  52517. }
  52518. this.animationStarted = running;
  52519. if (!running) {
  52520. if (this.disposeOnEnd) {
  52521. // Remove from active animatables
  52522. index = this._scene._activeAnimatables.indexOf(this);
  52523. this._scene._activeAnimatables.splice(index, 1);
  52524. // Dispose all runtime animations
  52525. for (index = 0; index < runtimeAnimations.length; index++) {
  52526. runtimeAnimations[index].dispose();
  52527. }
  52528. }
  52529. this._raiseOnAnimationEnd();
  52530. if (this.disposeOnEnd) {
  52531. this.onAnimationEnd = null;
  52532. this.onAnimationEndObservable.clear();
  52533. }
  52534. }
  52535. return running;
  52536. };
  52537. return Animatable;
  52538. }());
  52539. BABYLON.Animatable = Animatable;
  52540. })(BABYLON || (BABYLON = {}));
  52541. //# sourceMappingURL=babylon.animatable.js.map
  52542. var BABYLON;
  52543. (function (BABYLON) {
  52544. /**
  52545. * Base class used for every default easing function.
  52546. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52547. */
  52548. var EasingFunction = /** @class */ (function () {
  52549. function EasingFunction() {
  52550. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52551. }
  52552. /**
  52553. * Sets the easing mode of the current function.
  52554. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  52555. */
  52556. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52557. var n = Math.min(Math.max(easingMode, 0), 2);
  52558. this._easingMode = n;
  52559. };
  52560. /**
  52561. * Gets the current easing mode.
  52562. * @returns the easing mode
  52563. */
  52564. EasingFunction.prototype.getEasingMode = function () {
  52565. return this._easingMode;
  52566. };
  52567. /**
  52568. * @hidden
  52569. */
  52570. EasingFunction.prototype.easeInCore = function (gradient) {
  52571. throw new Error('You must implement this method');
  52572. };
  52573. /**
  52574. * Given an input gradient between 0 and 1, this returns the corrseponding value
  52575. * of the easing function.
  52576. * @param gradient Defines the value between 0 and 1 we want the easing value for
  52577. * @returns the corresponding value on the curve defined by the easing function
  52578. */
  52579. EasingFunction.prototype.ease = function (gradient) {
  52580. switch (this._easingMode) {
  52581. case EasingFunction.EASINGMODE_EASEIN:
  52582. return this.easeInCore(gradient);
  52583. case EasingFunction.EASINGMODE_EASEOUT:
  52584. return (1 - this.easeInCore(1 - gradient));
  52585. }
  52586. if (gradient >= 0.5) {
  52587. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52588. }
  52589. return (this.easeInCore(gradient * 2) * 0.5);
  52590. };
  52591. /**
  52592. * Interpolation follows the mathematical formula associated with the easing function.
  52593. */
  52594. EasingFunction.EASINGMODE_EASEIN = 0;
  52595. /**
  52596. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  52597. */
  52598. EasingFunction.EASINGMODE_EASEOUT = 1;
  52599. /**
  52600. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  52601. */
  52602. EasingFunction.EASINGMODE_EASEINOUT = 2;
  52603. return EasingFunction;
  52604. }());
  52605. BABYLON.EasingFunction = EasingFunction;
  52606. /**
  52607. * Easing function with a circle shape (see link below).
  52608. * @see https://easings.net/#easeInCirc
  52609. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52610. */
  52611. var CircleEase = /** @class */ (function (_super) {
  52612. __extends(CircleEase, _super);
  52613. function CircleEase() {
  52614. return _super !== null && _super.apply(this, arguments) || this;
  52615. }
  52616. /** @hidden */
  52617. CircleEase.prototype.easeInCore = function (gradient) {
  52618. gradient = Math.max(0, Math.min(1, gradient));
  52619. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52620. };
  52621. return CircleEase;
  52622. }(EasingFunction));
  52623. BABYLON.CircleEase = CircleEase;
  52624. /**
  52625. * Easing function with a ease back shape (see link below).
  52626. * @see https://easings.net/#easeInBack
  52627. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52628. */
  52629. var BackEase = /** @class */ (function (_super) {
  52630. __extends(BackEase, _super);
  52631. /**
  52632. * Instantiates a back ease easing
  52633. * @see https://easings.net/#easeInBack
  52634. * @param amplitude Defines the amplitude of the function
  52635. */
  52636. function BackEase(
  52637. /** Defines the amplitude of the function */
  52638. amplitude) {
  52639. if (amplitude === void 0) { amplitude = 1; }
  52640. var _this = _super.call(this) || this;
  52641. _this.amplitude = amplitude;
  52642. return _this;
  52643. }
  52644. /** @hidden */
  52645. BackEase.prototype.easeInCore = function (gradient) {
  52646. var num = Math.max(0, this.amplitude);
  52647. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52648. };
  52649. return BackEase;
  52650. }(EasingFunction));
  52651. BABYLON.BackEase = BackEase;
  52652. /**
  52653. * Easing function with a bouncing shape (see link below).
  52654. * @see https://easings.net/#easeInBounce
  52655. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52656. */
  52657. var BounceEase = /** @class */ (function (_super) {
  52658. __extends(BounceEase, _super);
  52659. /**
  52660. * Instantiates a bounce easing
  52661. * @see https://easings.net/#easeInBounce
  52662. * @param bounces Defines the number of bounces
  52663. * @param bounciness Defines the amplitude of the bounce
  52664. */
  52665. function BounceEase(
  52666. /** Defines the number of bounces */
  52667. bounces,
  52668. /** Defines the amplitude of the bounce */
  52669. bounciness) {
  52670. if (bounces === void 0) { bounces = 3; }
  52671. if (bounciness === void 0) { bounciness = 2; }
  52672. var _this = _super.call(this) || this;
  52673. _this.bounces = bounces;
  52674. _this.bounciness = bounciness;
  52675. return _this;
  52676. }
  52677. /** @hidden */
  52678. BounceEase.prototype.easeInCore = function (gradient) {
  52679. var y = Math.max(0.0, this.bounces);
  52680. var bounciness = this.bounciness;
  52681. if (bounciness <= 1.0) {
  52682. bounciness = 1.001;
  52683. }
  52684. var num9 = Math.pow(bounciness, y);
  52685. var num5 = 1.0 - bounciness;
  52686. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52687. var num15 = gradient * num4;
  52688. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52689. var num3 = Math.floor(num65);
  52690. var num13 = num3 + 1.0;
  52691. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52692. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52693. var num7 = (num8 + num12) * 0.5;
  52694. var num6 = gradient - num7;
  52695. var num2 = num7 - num8;
  52696. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52697. };
  52698. return BounceEase;
  52699. }(EasingFunction));
  52700. BABYLON.BounceEase = BounceEase;
  52701. /**
  52702. * Easing function with a power of 3 shape (see link below).
  52703. * @see https://easings.net/#easeInCubic
  52704. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52705. */
  52706. var CubicEase = /** @class */ (function (_super) {
  52707. __extends(CubicEase, _super);
  52708. function CubicEase() {
  52709. return _super !== null && _super.apply(this, arguments) || this;
  52710. }
  52711. /** @hidden */
  52712. CubicEase.prototype.easeInCore = function (gradient) {
  52713. return (gradient * gradient * gradient);
  52714. };
  52715. return CubicEase;
  52716. }(EasingFunction));
  52717. BABYLON.CubicEase = CubicEase;
  52718. /**
  52719. * Easing function with an elastic shape (see link below).
  52720. * @see https://easings.net/#easeInElastic
  52721. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52722. */
  52723. var ElasticEase = /** @class */ (function (_super) {
  52724. __extends(ElasticEase, _super);
  52725. /**
  52726. * Instantiates an elastic easing function
  52727. * @see https://easings.net/#easeInElastic
  52728. * @param oscillations Defines the number of oscillations
  52729. * @param springiness Defines the amplitude of the oscillations
  52730. */
  52731. function ElasticEase(
  52732. /** Defines the number of oscillations*/
  52733. oscillations,
  52734. /** Defines the amplitude of the oscillations*/
  52735. springiness) {
  52736. if (oscillations === void 0) { oscillations = 3; }
  52737. if (springiness === void 0) { springiness = 3; }
  52738. var _this = _super.call(this) || this;
  52739. _this.oscillations = oscillations;
  52740. _this.springiness = springiness;
  52741. return _this;
  52742. }
  52743. /** @hidden */
  52744. ElasticEase.prototype.easeInCore = function (gradient) {
  52745. var num2;
  52746. var num3 = Math.max(0.0, this.oscillations);
  52747. var num = Math.max(0.0, this.springiness);
  52748. if (num == 0) {
  52749. num2 = gradient;
  52750. }
  52751. else {
  52752. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52753. }
  52754. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52755. };
  52756. return ElasticEase;
  52757. }(EasingFunction));
  52758. BABYLON.ElasticEase = ElasticEase;
  52759. /**
  52760. * Easing function with an exponential shape (see link below).
  52761. * @see https://easings.net/#easeInExpo
  52762. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52763. */
  52764. var ExponentialEase = /** @class */ (function (_super) {
  52765. __extends(ExponentialEase, _super);
  52766. /**
  52767. * Instantiates an exponential easing function
  52768. * @see https://easings.net/#easeInExpo
  52769. * @param exponent Defines the exponent of the function
  52770. */
  52771. function ExponentialEase(
  52772. /** Defines the exponent of the function */
  52773. exponent) {
  52774. if (exponent === void 0) { exponent = 2; }
  52775. var _this = _super.call(this) || this;
  52776. _this.exponent = exponent;
  52777. return _this;
  52778. }
  52779. /** @hidden */
  52780. ExponentialEase.prototype.easeInCore = function (gradient) {
  52781. if (this.exponent <= 0) {
  52782. return gradient;
  52783. }
  52784. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52785. };
  52786. return ExponentialEase;
  52787. }(EasingFunction));
  52788. BABYLON.ExponentialEase = ExponentialEase;
  52789. /**
  52790. * Easing function with a power shape (see link below).
  52791. * @see https://easings.net/#easeInQuad
  52792. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52793. */
  52794. var PowerEase = /** @class */ (function (_super) {
  52795. __extends(PowerEase, _super);
  52796. /**
  52797. * Instantiates an power base easing function
  52798. * @see https://easings.net/#easeInQuad
  52799. * @param power Defines the power of the function
  52800. */
  52801. function PowerEase(
  52802. /** Defines the power of the function */
  52803. power) {
  52804. if (power === void 0) { power = 2; }
  52805. var _this = _super.call(this) || this;
  52806. _this.power = power;
  52807. return _this;
  52808. }
  52809. /** @hidden */
  52810. PowerEase.prototype.easeInCore = function (gradient) {
  52811. var y = Math.max(0.0, this.power);
  52812. return Math.pow(gradient, y);
  52813. };
  52814. return PowerEase;
  52815. }(EasingFunction));
  52816. BABYLON.PowerEase = PowerEase;
  52817. /**
  52818. * Easing function with a power of 2 shape (see link below).
  52819. * @see https://easings.net/#easeInQuad
  52820. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52821. */
  52822. var QuadraticEase = /** @class */ (function (_super) {
  52823. __extends(QuadraticEase, _super);
  52824. function QuadraticEase() {
  52825. return _super !== null && _super.apply(this, arguments) || this;
  52826. }
  52827. /** @hidden */
  52828. QuadraticEase.prototype.easeInCore = function (gradient) {
  52829. return (gradient * gradient);
  52830. };
  52831. return QuadraticEase;
  52832. }(EasingFunction));
  52833. BABYLON.QuadraticEase = QuadraticEase;
  52834. /**
  52835. * Easing function with a power of 4 shape (see link below).
  52836. * @see https://easings.net/#easeInQuart
  52837. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52838. */
  52839. var QuarticEase = /** @class */ (function (_super) {
  52840. __extends(QuarticEase, _super);
  52841. function QuarticEase() {
  52842. return _super !== null && _super.apply(this, arguments) || this;
  52843. }
  52844. /** @hidden */
  52845. QuarticEase.prototype.easeInCore = function (gradient) {
  52846. return (gradient * gradient * gradient * gradient);
  52847. };
  52848. return QuarticEase;
  52849. }(EasingFunction));
  52850. BABYLON.QuarticEase = QuarticEase;
  52851. /**
  52852. * Easing function with a power of 5 shape (see link below).
  52853. * @see https://easings.net/#easeInQuint
  52854. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52855. */
  52856. var QuinticEase = /** @class */ (function (_super) {
  52857. __extends(QuinticEase, _super);
  52858. function QuinticEase() {
  52859. return _super !== null && _super.apply(this, arguments) || this;
  52860. }
  52861. /** @hidden */
  52862. QuinticEase.prototype.easeInCore = function (gradient) {
  52863. return (gradient * gradient * gradient * gradient * gradient);
  52864. };
  52865. return QuinticEase;
  52866. }(EasingFunction));
  52867. BABYLON.QuinticEase = QuinticEase;
  52868. /**
  52869. * Easing function with a sin shape (see link below).
  52870. * @see https://easings.net/#easeInSine
  52871. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52872. */
  52873. var SineEase = /** @class */ (function (_super) {
  52874. __extends(SineEase, _super);
  52875. function SineEase() {
  52876. return _super !== null && _super.apply(this, arguments) || this;
  52877. }
  52878. /** @hidden */
  52879. SineEase.prototype.easeInCore = function (gradient) {
  52880. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52881. };
  52882. return SineEase;
  52883. }(EasingFunction));
  52884. BABYLON.SineEase = SineEase;
  52885. /**
  52886. * Easing function with a bezier shape (see link below).
  52887. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52888. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  52889. */
  52890. var BezierCurveEase = /** @class */ (function (_super) {
  52891. __extends(BezierCurveEase, _super);
  52892. /**
  52893. * Instantiates a bezier function
  52894. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  52895. * @param x1 Defines the x component of the start tangent in the bezier curve
  52896. * @param y1 Defines the y component of the start tangent in the bezier curve
  52897. * @param x2 Defines the x component of the end tangent in the bezier curve
  52898. * @param y2 Defines the y component of the end tangent in the bezier curve
  52899. */
  52900. function BezierCurveEase(
  52901. /** Defines the x component of the start tangent in the bezier curve */
  52902. x1,
  52903. /** Defines the y component of the start tangent in the bezier curve */
  52904. y1,
  52905. /** Defines the x component of the end tangent in the bezier curve */
  52906. x2,
  52907. /** Defines the y component of the end tangent in the bezier curve */
  52908. y2) {
  52909. if (x1 === void 0) { x1 = 0; }
  52910. if (y1 === void 0) { y1 = 0; }
  52911. if (x2 === void 0) { x2 = 1; }
  52912. if (y2 === void 0) { y2 = 1; }
  52913. var _this = _super.call(this) || this;
  52914. _this.x1 = x1;
  52915. _this.y1 = y1;
  52916. _this.x2 = x2;
  52917. _this.y2 = y2;
  52918. return _this;
  52919. }
  52920. /** @hidden */
  52921. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52922. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52923. };
  52924. return BezierCurveEase;
  52925. }(EasingFunction));
  52926. BABYLON.BezierCurveEase = BezierCurveEase;
  52927. })(BABYLON || (BABYLON = {}));
  52928. //# sourceMappingURL=babylon.easing.js.map
  52929. var BABYLON;
  52930. (function (BABYLON) {
  52931. /**
  52932. * A Condition applied to an Action
  52933. */
  52934. var Condition = /** @class */ (function () {
  52935. /**
  52936. * Creates a new Condition
  52937. * @param actionManager the manager of the action the condition is applied to
  52938. */
  52939. function Condition(actionManager) {
  52940. this._actionManager = actionManager;
  52941. }
  52942. /**
  52943. * Check if the current condition is valid
  52944. * @returns a boolean
  52945. */
  52946. Condition.prototype.isValid = function () {
  52947. return true;
  52948. };
  52949. /**
  52950. * Internal only
  52951. * @hidden
  52952. */
  52953. Condition.prototype._getProperty = function (propertyPath) {
  52954. return this._actionManager._getProperty(propertyPath);
  52955. };
  52956. /**
  52957. * Internal only
  52958. * @hidden
  52959. */
  52960. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52961. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52962. };
  52963. /**
  52964. * Serialize placeholder for child classes
  52965. * @returns the serialized object
  52966. */
  52967. Condition.prototype.serialize = function () {
  52968. };
  52969. /**
  52970. * Internal only
  52971. * @hidden
  52972. */
  52973. Condition.prototype._serialize = function (serializedCondition) {
  52974. return {
  52975. type: 2,
  52976. children: [],
  52977. name: serializedCondition.name,
  52978. properties: serializedCondition.properties
  52979. };
  52980. };
  52981. return Condition;
  52982. }());
  52983. BABYLON.Condition = Condition;
  52984. /**
  52985. * Defines specific conditional operators as extensions of Condition
  52986. */
  52987. var ValueCondition = /** @class */ (function (_super) {
  52988. __extends(ValueCondition, _super);
  52989. /**
  52990. * Creates a new ValueCondition
  52991. * @param actionManager manager for the action the condition applies to
  52992. * @param target for the action
  52993. * @param propertyPath path to specify the property of the target the conditional operator uses
  52994. * @param value the value compared by the conditional operator against the current value of the property
  52995. * @param operator the conditional operator, default ValueCondition.IsEqual
  52996. */
  52997. function ValueCondition(actionManager, target,
  52998. /** path to specify the property of the target the conditional operator uses */
  52999. propertyPath,
  53000. /** the value compared by the conditional operator against the current value of the property */
  53001. value,
  53002. /** the conditional operator, default ValueCondition.IsEqual */
  53003. operator) {
  53004. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  53005. var _this = _super.call(this, actionManager) || this;
  53006. _this.propertyPath = propertyPath;
  53007. _this.value = value;
  53008. _this.operator = operator;
  53009. _this._target = target;
  53010. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  53011. _this._property = _this._getProperty(_this.propertyPath);
  53012. return _this;
  53013. }
  53014. Object.defineProperty(ValueCondition, "IsEqual", {
  53015. /**
  53016. * returns the number for IsEqual
  53017. */
  53018. get: function () {
  53019. return ValueCondition._IsEqual;
  53020. },
  53021. enumerable: true,
  53022. configurable: true
  53023. });
  53024. Object.defineProperty(ValueCondition, "IsDifferent", {
  53025. /**
  53026. * Returns the number for IsDifferent
  53027. */
  53028. get: function () {
  53029. return ValueCondition._IsDifferent;
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(ValueCondition, "IsGreater", {
  53035. /**
  53036. * Returns the number for IsGreater
  53037. */
  53038. get: function () {
  53039. return ValueCondition._IsGreater;
  53040. },
  53041. enumerable: true,
  53042. configurable: true
  53043. });
  53044. Object.defineProperty(ValueCondition, "IsLesser", {
  53045. /**
  53046. * Returns the number for IsLesser
  53047. */
  53048. get: function () {
  53049. return ValueCondition._IsLesser;
  53050. },
  53051. enumerable: true,
  53052. configurable: true
  53053. });
  53054. /**
  53055. * Compares the given value with the property value for the specified conditional operator
  53056. * @returns the result of the comparison
  53057. */
  53058. ValueCondition.prototype.isValid = function () {
  53059. switch (this.operator) {
  53060. case ValueCondition.IsGreater:
  53061. return this._effectiveTarget[this._property] > this.value;
  53062. case ValueCondition.IsLesser:
  53063. return this._effectiveTarget[this._property] < this.value;
  53064. case ValueCondition.IsEqual:
  53065. case ValueCondition.IsDifferent:
  53066. var check;
  53067. if (this.value.equals) {
  53068. check = this.value.equals(this._effectiveTarget[this._property]);
  53069. }
  53070. else {
  53071. check = this.value === this._effectiveTarget[this._property];
  53072. }
  53073. return this.operator === ValueCondition.IsEqual ? check : !check;
  53074. }
  53075. return false;
  53076. };
  53077. /**
  53078. * Serialize the ValueCondition into a JSON compatible object
  53079. * @returns serialization object
  53080. */
  53081. ValueCondition.prototype.serialize = function () {
  53082. return this._serialize({
  53083. name: "ValueCondition",
  53084. properties: [
  53085. BABYLON.Action._GetTargetProperty(this._target),
  53086. { name: "propertyPath", value: this.propertyPath },
  53087. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53088. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  53089. ]
  53090. });
  53091. };
  53092. /**
  53093. * Gets the name of the conditional operator for the ValueCondition
  53094. * @param operator the conditional operator
  53095. * @returns the name
  53096. */
  53097. ValueCondition.GetOperatorName = function (operator) {
  53098. switch (operator) {
  53099. case ValueCondition._IsEqual: return "IsEqual";
  53100. case ValueCondition._IsDifferent: return "IsDifferent";
  53101. case ValueCondition._IsGreater: return "IsGreater";
  53102. case ValueCondition._IsLesser: return "IsLesser";
  53103. default: return "";
  53104. }
  53105. };
  53106. /**
  53107. * Internal only
  53108. * @hidden
  53109. */
  53110. ValueCondition._IsEqual = 0;
  53111. /**
  53112. * Internal only
  53113. * @hidden
  53114. */
  53115. ValueCondition._IsDifferent = 1;
  53116. /**
  53117. * Internal only
  53118. * @hidden
  53119. */
  53120. ValueCondition._IsGreater = 2;
  53121. /**
  53122. * Internal only
  53123. * @hidden
  53124. */
  53125. ValueCondition._IsLesser = 3;
  53126. return ValueCondition;
  53127. }(Condition));
  53128. BABYLON.ValueCondition = ValueCondition;
  53129. /**
  53130. * Defines a predicate condition as an extension of Condition
  53131. */
  53132. var PredicateCondition = /** @class */ (function (_super) {
  53133. __extends(PredicateCondition, _super);
  53134. /**
  53135. * Creates a new PredicateCondition
  53136. * @param actionManager manager for the action the condition applies to
  53137. * @param predicate defines the predicate function used to validate the condition
  53138. */
  53139. function PredicateCondition(actionManager,
  53140. /** defines the predicate function used to validate the condition */
  53141. predicate) {
  53142. var _this = _super.call(this, actionManager) || this;
  53143. _this.predicate = predicate;
  53144. return _this;
  53145. }
  53146. /**
  53147. * @returns the validity of the predicate condition
  53148. */
  53149. PredicateCondition.prototype.isValid = function () {
  53150. return this.predicate();
  53151. };
  53152. return PredicateCondition;
  53153. }(Condition));
  53154. BABYLON.PredicateCondition = PredicateCondition;
  53155. /**
  53156. * Defines a state condition as an extension of Condition
  53157. */
  53158. var StateCondition = /** @class */ (function (_super) {
  53159. __extends(StateCondition, _super);
  53160. /**
  53161. * Creates a new StateCondition
  53162. * @param actionManager manager for the action the condition applies to
  53163. * @param target of the condition
  53164. * @param value to compare with target state
  53165. */
  53166. function StateCondition(actionManager, target, value) {
  53167. var _this = _super.call(this, actionManager) || this;
  53168. _this.value = value;
  53169. _this._target = target;
  53170. return _this;
  53171. }
  53172. /**
  53173. * @returns the validity of the state
  53174. */
  53175. StateCondition.prototype.isValid = function () {
  53176. return this._target.state === this.value;
  53177. };
  53178. /**
  53179. * Serialize the StateCondition into a JSON compatible object
  53180. * @returns serialization object
  53181. */
  53182. StateCondition.prototype.serialize = function () {
  53183. return this._serialize({
  53184. name: "StateCondition",
  53185. properties: [
  53186. BABYLON.Action._GetTargetProperty(this._target),
  53187. { name: "value", value: this.value }
  53188. ]
  53189. });
  53190. };
  53191. return StateCondition;
  53192. }(Condition));
  53193. BABYLON.StateCondition = StateCondition;
  53194. })(BABYLON || (BABYLON = {}));
  53195. //# sourceMappingURL=babylon.condition.js.map
  53196. var BABYLON;
  53197. (function (BABYLON) {
  53198. /**
  53199. * The action to be carried out following a trigger
  53200. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  53201. */
  53202. var Action = /** @class */ (function () {
  53203. /**
  53204. * Creates a new Action
  53205. * @param triggerOptions the trigger, with or without parameters, for the action
  53206. * @param condition an optional determinant of action
  53207. */
  53208. function Action(
  53209. /** the trigger, with or without parameters, for the action */
  53210. triggerOptions, condition) {
  53211. this.triggerOptions = triggerOptions;
  53212. /**
  53213. * An event triggered prior to action being executed.
  53214. */
  53215. this.onBeforeExecuteObservable = new BABYLON.Observable();
  53216. if (triggerOptions.parameter) {
  53217. this.trigger = triggerOptions.trigger;
  53218. this._triggerParameter = triggerOptions.parameter;
  53219. }
  53220. else if (triggerOptions.trigger) {
  53221. this.trigger = triggerOptions.trigger;
  53222. }
  53223. else {
  53224. this.trigger = triggerOptions;
  53225. }
  53226. this._nextActiveAction = this;
  53227. this._condition = condition;
  53228. }
  53229. /**
  53230. * Internal only
  53231. * @hidden
  53232. */
  53233. Action.prototype._prepare = function () {
  53234. };
  53235. /**
  53236. * Gets the trigger parameters
  53237. * @returns the trigger parameters
  53238. */
  53239. Action.prototype.getTriggerParameter = function () {
  53240. return this._triggerParameter;
  53241. };
  53242. /**
  53243. * Internal only - executes current action event
  53244. * @hidden
  53245. */
  53246. Action.prototype._executeCurrent = function (evt) {
  53247. if (this._nextActiveAction._condition) {
  53248. var condition = this._nextActiveAction._condition;
  53249. var currentRenderId = this._actionManager.getScene().getRenderId();
  53250. // We cache the current evaluation for the current frame
  53251. if (condition._evaluationId === currentRenderId) {
  53252. if (!condition._currentResult) {
  53253. return;
  53254. }
  53255. }
  53256. else {
  53257. condition._evaluationId = currentRenderId;
  53258. if (!condition.isValid()) {
  53259. condition._currentResult = false;
  53260. return;
  53261. }
  53262. condition._currentResult = true;
  53263. }
  53264. }
  53265. this.onBeforeExecuteObservable.notifyObservers(this);
  53266. this._nextActiveAction.execute(evt);
  53267. this.skipToNextActiveAction();
  53268. };
  53269. /**
  53270. * Execute placeholder for child classes
  53271. * @param evt optional action event
  53272. */
  53273. Action.prototype.execute = function (evt) {
  53274. };
  53275. /**
  53276. * Skips to next active action
  53277. */
  53278. Action.prototype.skipToNextActiveAction = function () {
  53279. if (this._nextActiveAction._child) {
  53280. if (!this._nextActiveAction._child._actionManager) {
  53281. this._nextActiveAction._child._actionManager = this._actionManager;
  53282. }
  53283. this._nextActiveAction = this._nextActiveAction._child;
  53284. }
  53285. else {
  53286. this._nextActiveAction = this;
  53287. }
  53288. };
  53289. /**
  53290. * Adds action to chain of actions, may be a DoNothingAction
  53291. * @param action defines the next action to execute
  53292. * @returns The action passed in
  53293. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53294. */
  53295. Action.prototype.then = function (action) {
  53296. this._child = action;
  53297. action._actionManager = this._actionManager;
  53298. action._prepare();
  53299. return action;
  53300. };
  53301. /**
  53302. * Internal only
  53303. * @hidden
  53304. */
  53305. Action.prototype._getProperty = function (propertyPath) {
  53306. return this._actionManager._getProperty(propertyPath);
  53307. };
  53308. /**
  53309. * Internal only
  53310. * @hidden
  53311. */
  53312. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53313. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53314. };
  53315. /**
  53316. * Serialize placeholder for child classes
  53317. * @param parent of child
  53318. * @returns the serialized object
  53319. */
  53320. Action.prototype.serialize = function (parent) {
  53321. };
  53322. /**
  53323. * Internal only called by serialize
  53324. * @hidden
  53325. */
  53326. Action.prototype._serialize = function (serializedAction, parent) {
  53327. var serializationObject = {
  53328. type: 1,
  53329. children: [],
  53330. name: serializedAction.name,
  53331. properties: serializedAction.properties || []
  53332. };
  53333. // Serialize child
  53334. if (this._child) {
  53335. this._child.serialize(serializationObject);
  53336. }
  53337. // Check if "this" has a condition
  53338. if (this._condition) {
  53339. var serializedCondition = this._condition.serialize();
  53340. serializedCondition.children.push(serializationObject);
  53341. if (parent) {
  53342. parent.children.push(serializedCondition);
  53343. }
  53344. return serializedCondition;
  53345. }
  53346. if (parent) {
  53347. parent.children.push(serializationObject);
  53348. }
  53349. return serializationObject;
  53350. };
  53351. /**
  53352. * Internal only
  53353. * @hidden
  53354. */
  53355. Action._SerializeValueAsString = function (value) {
  53356. if (typeof value === "number") {
  53357. return value.toString();
  53358. }
  53359. if (typeof value === "boolean") {
  53360. return value ? "true" : "false";
  53361. }
  53362. if (value instanceof BABYLON.Vector2) {
  53363. return value.x + ", " + value.y;
  53364. }
  53365. if (value instanceof BABYLON.Vector3) {
  53366. return value.x + ", " + value.y + ", " + value.z;
  53367. }
  53368. if (value instanceof BABYLON.Color3) {
  53369. return value.r + ", " + value.g + ", " + value.b;
  53370. }
  53371. if (value instanceof BABYLON.Color4) {
  53372. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53373. }
  53374. return value; // string
  53375. };
  53376. /**
  53377. * Internal only
  53378. * @hidden
  53379. */
  53380. Action._GetTargetProperty = function (target) {
  53381. return {
  53382. name: "target",
  53383. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53384. : target instanceof BABYLON.Light ? "LightProperties"
  53385. : target instanceof BABYLON.Camera ? "CameraProperties"
  53386. : "SceneProperties",
  53387. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53388. };
  53389. };
  53390. return Action;
  53391. }());
  53392. BABYLON.Action = Action;
  53393. })(BABYLON || (BABYLON = {}));
  53394. //# sourceMappingURL=babylon.action.js.map
  53395. var BABYLON;
  53396. (function (BABYLON) {
  53397. /**
  53398. * ActionEvent is the event being sent when an action is triggered.
  53399. */
  53400. var ActionEvent = /** @class */ (function () {
  53401. /**
  53402. * Creates a new ActionEvent
  53403. * @param source The mesh or sprite that triggered the action
  53404. * @param pointerX The X mouse cursor position at the time of the event
  53405. * @param pointerY The Y mouse cursor position at the time of the event
  53406. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53407. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53408. * @param additionalData additional data for the event
  53409. */
  53410. function ActionEvent(
  53411. /** The mesh or sprite that triggered the action */
  53412. source,
  53413. /** The X mouse cursor position at the time of the event */
  53414. pointerX,
  53415. /** The Y mouse cursor position at the time of the event */
  53416. pointerY,
  53417. /** The mesh that is currently pointed at (can be null) */
  53418. meshUnderPointer,
  53419. /** the original (browser) event that triggered the ActionEvent */
  53420. sourceEvent,
  53421. /** additional data for the event */
  53422. additionalData) {
  53423. this.source = source;
  53424. this.pointerX = pointerX;
  53425. this.pointerY = pointerY;
  53426. this.meshUnderPointer = meshUnderPointer;
  53427. this.sourceEvent = sourceEvent;
  53428. this.additionalData = additionalData;
  53429. }
  53430. /**
  53431. * Helper function to auto-create an ActionEvent from a source mesh.
  53432. * @param source The source mesh that triggered the event
  53433. * @param evt The original (browser) event
  53434. * @param additionalData additional data for the event
  53435. * @returns the new ActionEvent
  53436. */
  53437. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53438. var scene = source.getScene();
  53439. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53440. };
  53441. /**
  53442. * Helper function to auto-create an ActionEvent from a source sprite
  53443. * @param source The source sprite that triggered the event
  53444. * @param scene Scene associated with the sprite
  53445. * @param evt The original (browser) event
  53446. * @param additionalData additional data for the event
  53447. * @returns the new ActionEvent
  53448. */
  53449. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53450. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53451. };
  53452. /**
  53453. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53454. * @param scene the scene where the event occurred
  53455. * @param evt The original (browser) event
  53456. * @returns the new ActionEvent
  53457. */
  53458. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53459. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53460. };
  53461. /**
  53462. * Helper function to auto-create an ActionEvent from a primitive
  53463. * @param prim defines the target primitive
  53464. * @param pointerPos defines the pointer position
  53465. * @param evt The original (browser) event
  53466. * @param additionalData additional data for the event
  53467. * @returns the new ActionEvent
  53468. */
  53469. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53470. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53471. };
  53472. return ActionEvent;
  53473. }());
  53474. BABYLON.ActionEvent = ActionEvent;
  53475. /**
  53476. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53477. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53478. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53479. */
  53480. var ActionManager = /** @class */ (function () {
  53481. /**
  53482. * Creates a new action manager
  53483. * @param scene defines the hosting scene
  53484. */
  53485. function ActionManager(scene) {
  53486. // Members
  53487. /** Gets the list of actions */
  53488. this.actions = new Array();
  53489. /** Gets the cursor to use when hovering items */
  53490. this.hoverCursor = '';
  53491. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53492. scene.actionManagers.push(this);
  53493. }
  53494. // Methods
  53495. /**
  53496. * Releases all associated resources
  53497. */
  53498. ActionManager.prototype.dispose = function () {
  53499. var index = this._scene.actionManagers.indexOf(this);
  53500. for (var i = 0; i < this.actions.length; i++) {
  53501. var action = this.actions[i];
  53502. ActionManager.Triggers[action.trigger]--;
  53503. if (ActionManager.Triggers[action.trigger] === 0) {
  53504. delete ActionManager.Triggers[action.trigger];
  53505. }
  53506. }
  53507. if (index > -1) {
  53508. this._scene.actionManagers.splice(index, 1);
  53509. }
  53510. };
  53511. /**
  53512. * Gets hosting scene
  53513. * @returns the hosting scene
  53514. */
  53515. ActionManager.prototype.getScene = function () {
  53516. return this._scene;
  53517. };
  53518. /**
  53519. * Does this action manager handles actions of any of the given triggers
  53520. * @param triggers defines the triggers to be tested
  53521. * @return a boolean indicating whether one (or more) of the triggers is handled
  53522. */
  53523. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53524. for (var index = 0; index < this.actions.length; index++) {
  53525. var action = this.actions[index];
  53526. if (triggers.indexOf(action.trigger) > -1) {
  53527. return true;
  53528. }
  53529. }
  53530. return false;
  53531. };
  53532. /**
  53533. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  53534. * speed.
  53535. * @param triggerA defines the trigger to be tested
  53536. * @param triggerB defines the trigger to be tested
  53537. * @return a boolean indicating whether one (or more) of the triggers is handled
  53538. */
  53539. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  53540. for (var index = 0; index < this.actions.length; index++) {
  53541. var action = this.actions[index];
  53542. if (triggerA == action.trigger || triggerB == action.trigger) {
  53543. return true;
  53544. }
  53545. }
  53546. return false;
  53547. };
  53548. /**
  53549. * Does this action manager handles actions of a given trigger
  53550. * @param trigger defines the trigger to be tested
  53551. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53552. * @return whether the trigger is handled
  53553. */
  53554. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53555. for (var index = 0; index < this.actions.length; index++) {
  53556. var action = this.actions[index];
  53557. if (action.trigger === trigger) {
  53558. if (parameterPredicate) {
  53559. if (parameterPredicate(action.getTriggerParameter())) {
  53560. return true;
  53561. }
  53562. }
  53563. else {
  53564. return true;
  53565. }
  53566. }
  53567. }
  53568. return false;
  53569. };
  53570. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53571. /**
  53572. * Does this action manager has pointer triggers
  53573. */
  53574. get: function () {
  53575. for (var index = 0; index < this.actions.length; index++) {
  53576. var action = this.actions[index];
  53577. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  53578. return true;
  53579. }
  53580. }
  53581. return false;
  53582. },
  53583. enumerable: true,
  53584. configurable: true
  53585. });
  53586. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53587. /**
  53588. * Does this action manager has pick triggers
  53589. */
  53590. get: function () {
  53591. for (var index = 0; index < this.actions.length; index++) {
  53592. var action = this.actions[index];
  53593. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  53594. return true;
  53595. }
  53596. }
  53597. return false;
  53598. },
  53599. enumerable: true,
  53600. configurable: true
  53601. });
  53602. Object.defineProperty(ActionManager, "HasTriggers", {
  53603. /**
  53604. * Does exist one action manager with at least one trigger
  53605. **/
  53606. get: function () {
  53607. for (var t in ActionManager.Triggers) {
  53608. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53609. return true;
  53610. }
  53611. }
  53612. return false;
  53613. },
  53614. enumerable: true,
  53615. configurable: true
  53616. });
  53617. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53618. /**
  53619. * Does exist one action manager with at least one pick trigger
  53620. **/
  53621. get: function () {
  53622. for (var t in ActionManager.Triggers) {
  53623. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53624. var t_int = parseInt(t);
  53625. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  53626. return true;
  53627. }
  53628. }
  53629. }
  53630. return false;
  53631. },
  53632. enumerable: true,
  53633. configurable: true
  53634. });
  53635. /**
  53636. * Does exist one action manager that handles actions of a given trigger
  53637. * @param trigger defines the trigger to be tested
  53638. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53639. **/
  53640. ActionManager.HasSpecificTrigger = function (trigger) {
  53641. for (var t in ActionManager.Triggers) {
  53642. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53643. var t_int = parseInt(t);
  53644. if (t_int === trigger) {
  53645. return true;
  53646. }
  53647. }
  53648. }
  53649. return false;
  53650. };
  53651. /**
  53652. * Registers an action to this action manager
  53653. * @param action defines the action to be registered
  53654. * @return the action amended (prepared) after registration
  53655. */
  53656. ActionManager.prototype.registerAction = function (action) {
  53657. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53658. if (this.getScene().actionManager !== this) {
  53659. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53660. return null;
  53661. }
  53662. }
  53663. this.actions.push(action);
  53664. if (ActionManager.Triggers[action.trigger]) {
  53665. ActionManager.Triggers[action.trigger]++;
  53666. }
  53667. else {
  53668. ActionManager.Triggers[action.trigger] = 1;
  53669. }
  53670. action._actionManager = this;
  53671. action._prepare();
  53672. return action;
  53673. };
  53674. /**
  53675. * Unregisters an action to this action manager
  53676. * @param action defines the action to be unregistered
  53677. * @return a boolean indicating whether the action has been unregistered
  53678. */
  53679. ActionManager.prototype.unregisterAction = function (action) {
  53680. var index = this.actions.indexOf(action);
  53681. if (index !== -1) {
  53682. this.actions.splice(index, 1);
  53683. ActionManager.Triggers[action.trigger] -= 1;
  53684. if (ActionManager.Triggers[action.trigger] === 0) {
  53685. delete ActionManager.Triggers[action.trigger];
  53686. }
  53687. delete action._actionManager;
  53688. return true;
  53689. }
  53690. return false;
  53691. };
  53692. /**
  53693. * Process a specific trigger
  53694. * @param trigger defines the trigger to process
  53695. * @param evt defines the event details to be processed
  53696. */
  53697. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53698. for (var index = 0; index < this.actions.length; index++) {
  53699. var action = this.actions[index];
  53700. if (action.trigger === trigger) {
  53701. if (evt) {
  53702. if (trigger === ActionManager.OnKeyUpTrigger
  53703. || trigger === ActionManager.OnKeyDownTrigger) {
  53704. var parameter = action.getTriggerParameter();
  53705. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53706. if (!parameter.toLowerCase) {
  53707. continue;
  53708. }
  53709. var lowerCase = parameter.toLowerCase();
  53710. if (lowerCase !== evt.sourceEvent.key) {
  53711. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53712. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53713. if (actualkey !== lowerCase) {
  53714. continue;
  53715. }
  53716. }
  53717. }
  53718. }
  53719. }
  53720. action._executeCurrent(evt);
  53721. }
  53722. }
  53723. };
  53724. /** @hidden */
  53725. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53726. var properties = propertyPath.split(".");
  53727. for (var index = 0; index < properties.length - 1; index++) {
  53728. target = target[properties[index]];
  53729. }
  53730. return target;
  53731. };
  53732. /** @hidden */
  53733. ActionManager.prototype._getProperty = function (propertyPath) {
  53734. var properties = propertyPath.split(".");
  53735. return properties[properties.length - 1];
  53736. };
  53737. /**
  53738. * Serialize this manager to a JSON object
  53739. * @param name defines the property name to store this manager
  53740. * @returns a JSON representation of this manager
  53741. */
  53742. ActionManager.prototype.serialize = function (name) {
  53743. var root = {
  53744. children: new Array(),
  53745. name: name,
  53746. type: 3,
  53747. properties: new Array() // Empty for root but required
  53748. };
  53749. for (var i = 0; i < this.actions.length; i++) {
  53750. var triggerObject = {
  53751. type: 0,
  53752. children: new Array(),
  53753. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53754. properties: new Array()
  53755. };
  53756. var triggerOptions = this.actions[i].triggerOptions;
  53757. if (triggerOptions && typeof triggerOptions !== "number") {
  53758. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53759. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53760. }
  53761. else {
  53762. var parameter = {};
  53763. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53764. if (triggerOptions.parameter.mesh) {
  53765. parameter._meshId = triggerOptions.parameter.mesh.id;
  53766. }
  53767. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53768. }
  53769. }
  53770. // Serialize child action, recursively
  53771. this.actions[i].serialize(triggerObject);
  53772. // Add serialized trigger
  53773. root.children.push(triggerObject);
  53774. }
  53775. return root;
  53776. };
  53777. /**
  53778. * Creates a new ActionManager from a JSON data
  53779. * @param parsedActions defines the JSON data to read from
  53780. * @param object defines the hosting mesh
  53781. * @param scene defines the hosting scene
  53782. */
  53783. ActionManager.Parse = function (parsedActions, object, scene) {
  53784. var actionManager = new ActionManager(scene);
  53785. if (object === null)
  53786. scene.actionManager = actionManager;
  53787. else
  53788. object.actionManager = actionManager;
  53789. // instanciate a new object
  53790. var instanciate = function (name, params) {
  53791. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53792. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53793. newInstance.constructor.apply(newInstance, params);
  53794. return newInstance;
  53795. };
  53796. var parseParameter = function (name, value, target, propertyPath) {
  53797. if (propertyPath === null) {
  53798. // String, boolean or float
  53799. var floatValue = parseFloat(value);
  53800. if (value === "true" || value === "false")
  53801. return value === "true";
  53802. else
  53803. return isNaN(floatValue) ? value : floatValue;
  53804. }
  53805. var effectiveTarget = propertyPath.split(".");
  53806. var values = value.split(",");
  53807. // Get effective Target
  53808. for (var i = 0; i < effectiveTarget.length; i++) {
  53809. target = target[effectiveTarget[i]];
  53810. }
  53811. // Return appropriate value with its type
  53812. if (typeof (target) === "boolean")
  53813. return values[0] === "true";
  53814. if (typeof (target) === "string")
  53815. return values[0];
  53816. // Parameters with multiple values such as Vector3 etc.
  53817. var split = new Array();
  53818. for (var i = 0; i < values.length; i++)
  53819. split.push(parseFloat(values[i]));
  53820. if (target instanceof BABYLON.Vector3)
  53821. return BABYLON.Vector3.FromArray(split);
  53822. if (target instanceof BABYLON.Vector4)
  53823. return BABYLON.Vector4.FromArray(split);
  53824. if (target instanceof BABYLON.Color3)
  53825. return BABYLON.Color3.FromArray(split);
  53826. if (target instanceof BABYLON.Color4)
  53827. return BABYLON.Color4.FromArray(split);
  53828. return parseFloat(values[0]);
  53829. };
  53830. // traverse graph per trigger
  53831. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53832. if (combineArray === void 0) { combineArray = null; }
  53833. if (parsedAction.detached)
  53834. return;
  53835. var parameters = new Array();
  53836. var target = null;
  53837. var propertyPath = null;
  53838. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53839. // Parameters
  53840. if (parsedAction.type === 2)
  53841. parameters.push(actionManager);
  53842. else
  53843. parameters.push(trigger);
  53844. if (combine) {
  53845. var actions = new Array();
  53846. for (var j = 0; j < parsedAction.combine.length; j++) {
  53847. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53848. }
  53849. parameters.push(actions);
  53850. }
  53851. else {
  53852. for (var i = 0; i < parsedAction.properties.length; i++) {
  53853. var value = parsedAction.properties[i].value;
  53854. var name = parsedAction.properties[i].name;
  53855. var targetType = parsedAction.properties[i].targetType;
  53856. if (name === "target")
  53857. if (targetType !== null && targetType === "SceneProperties")
  53858. value = target = scene;
  53859. else
  53860. value = target = scene.getNodeByName(value);
  53861. else if (name === "parent")
  53862. value = scene.getNodeByName(value);
  53863. else if (name === "sound") {
  53864. // Can not externalize to component, so only checks for the presence off the API.
  53865. if (scene.getSoundByName) {
  53866. value = scene.getSoundByName(value);
  53867. }
  53868. }
  53869. else if (name !== "propertyPath") {
  53870. if (parsedAction.type === 2 && name === "operator")
  53871. value = BABYLON.ValueCondition[value];
  53872. else
  53873. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53874. }
  53875. else {
  53876. propertyPath = value;
  53877. }
  53878. parameters.push(value);
  53879. }
  53880. }
  53881. if (combineArray === null) {
  53882. parameters.push(condition);
  53883. }
  53884. else {
  53885. parameters.push(null);
  53886. }
  53887. // If interpolate value action
  53888. if (parsedAction.name === "InterpolateValueAction") {
  53889. var param = parameters[parameters.length - 2];
  53890. parameters[parameters.length - 1] = param;
  53891. parameters[parameters.length - 2] = condition;
  53892. }
  53893. // Action or condition(s) and not CombineAction
  53894. var newAction = instanciate(parsedAction.name, parameters);
  53895. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53896. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53897. if (action)
  53898. action.then(nothing);
  53899. else
  53900. actionManager.registerAction(nothing);
  53901. action = nothing;
  53902. }
  53903. if (combineArray === null) {
  53904. if (newAction instanceof BABYLON.Condition) {
  53905. condition = newAction;
  53906. newAction = action;
  53907. }
  53908. else {
  53909. condition = null;
  53910. if (action)
  53911. action.then(newAction);
  53912. else
  53913. actionManager.registerAction(newAction);
  53914. }
  53915. }
  53916. else {
  53917. combineArray.push(newAction);
  53918. }
  53919. for (var i = 0; i < parsedAction.children.length; i++)
  53920. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53921. };
  53922. // triggers
  53923. for (var i = 0; i < parsedActions.children.length; i++) {
  53924. var triggerParams;
  53925. var trigger = parsedActions.children[i];
  53926. if (trigger.properties.length > 0) {
  53927. var param = trigger.properties[0].value;
  53928. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53929. if (value._meshId) {
  53930. value.mesh = scene.getMeshByID(value._meshId);
  53931. }
  53932. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53933. }
  53934. else
  53935. triggerParams = ActionManager[trigger.name];
  53936. for (var j = 0; j < trigger.children.length; j++) {
  53937. if (!trigger.detached)
  53938. traverse(trigger.children[j], triggerParams, null, null);
  53939. }
  53940. }
  53941. };
  53942. /**
  53943. * Get a trigger name by index
  53944. * @param trigger defines the trigger index
  53945. * @returns a trigger name
  53946. */
  53947. ActionManager.GetTriggerName = function (trigger) {
  53948. switch (trigger) {
  53949. case 0: return "NothingTrigger";
  53950. case 1: return "OnPickTrigger";
  53951. case 2: return "OnLeftPickTrigger";
  53952. case 3: return "OnRightPickTrigger";
  53953. case 4: return "OnCenterPickTrigger";
  53954. case 5: return "OnPickDownTrigger";
  53955. case 6: return "OnPickUpTrigger";
  53956. case 7: return "OnLongPressTrigger";
  53957. case 8: return "OnPointerOverTrigger";
  53958. case 9: return "OnPointerOutTrigger";
  53959. case 10: return "OnEveryFrameTrigger";
  53960. case 11: return "OnIntersectionEnterTrigger";
  53961. case 12: return "OnIntersectionExitTrigger";
  53962. case 13: return "OnKeyDownTrigger";
  53963. case 14: return "OnKeyUpTrigger";
  53964. case 15: return "OnPickOutTrigger";
  53965. default: return "";
  53966. }
  53967. };
  53968. /**
  53969. * Nothing
  53970. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53971. */
  53972. ActionManager.NothingTrigger = 0;
  53973. /**
  53974. * On pick
  53975. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53976. */
  53977. ActionManager.OnPickTrigger = 1;
  53978. /**
  53979. * On left pick
  53980. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53981. */
  53982. ActionManager.OnLeftPickTrigger = 2;
  53983. /**
  53984. * On right pick
  53985. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53986. */
  53987. ActionManager.OnRightPickTrigger = 3;
  53988. /**
  53989. * On center pick
  53990. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53991. */
  53992. ActionManager.OnCenterPickTrigger = 4;
  53993. /**
  53994. * On pick down
  53995. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53996. */
  53997. ActionManager.OnPickDownTrigger = 5;
  53998. /**
  53999. * On double pick
  54000. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54001. */
  54002. ActionManager.OnDoublePickTrigger = 6;
  54003. /**
  54004. * On pick up
  54005. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54006. */
  54007. ActionManager.OnPickUpTrigger = 7;
  54008. /**
  54009. * On pick out.
  54010. * This trigger will only be raised if you also declared a OnPickDown
  54011. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54012. */
  54013. ActionManager.OnPickOutTrigger = 16;
  54014. /**
  54015. * On long press
  54016. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54017. */
  54018. ActionManager.OnLongPressTrigger = 8;
  54019. /**
  54020. * On pointer over
  54021. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54022. */
  54023. ActionManager.OnPointerOverTrigger = 9;
  54024. /**
  54025. * On pointer out
  54026. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54027. */
  54028. ActionManager.OnPointerOutTrigger = 10;
  54029. /**
  54030. * On every frame
  54031. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54032. */
  54033. ActionManager.OnEveryFrameTrigger = 11;
  54034. /**
  54035. * On intersection enter
  54036. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54037. */
  54038. ActionManager.OnIntersectionEnterTrigger = 12;
  54039. /**
  54040. * On intersection exit
  54041. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54042. */
  54043. ActionManager.OnIntersectionExitTrigger = 13;
  54044. /**
  54045. * On key down
  54046. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54047. */
  54048. ActionManager.OnKeyDownTrigger = 14;
  54049. /**
  54050. * On key up
  54051. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  54052. */
  54053. ActionManager.OnKeyUpTrigger = 15;
  54054. /** Gets the list of active triggers */
  54055. ActionManager.Triggers = {};
  54056. return ActionManager;
  54057. }());
  54058. BABYLON.ActionManager = ActionManager;
  54059. })(BABYLON || (BABYLON = {}));
  54060. //# sourceMappingURL=babylon.actionManager.js.map
  54061. var BABYLON;
  54062. (function (BABYLON) {
  54063. /**
  54064. * This defines an action responsible to change the value of a property
  54065. * by interpolating between its current value and the newly set one once triggered.
  54066. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54067. */
  54068. var InterpolateValueAction = /** @class */ (function (_super) {
  54069. __extends(InterpolateValueAction, _super);
  54070. /**
  54071. * Instantiate the action
  54072. * @param triggerOptions defines the trigger options
  54073. * @param target defines the object containing the value to interpolate
  54074. * @param propertyPath defines the path to the property in the target object
  54075. * @param value defines the target value at the end of the interpolation
  54076. * @param duration deines the time it will take for the property to interpolate to the value.
  54077. * @param condition defines the trigger related conditions
  54078. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  54079. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  54080. */
  54081. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  54082. if (duration === void 0) { duration = 1000; }
  54083. var _this = _super.call(this, triggerOptions, condition) || this;
  54084. /**
  54085. * Defines the time it will take for the property to interpolate to the value.
  54086. */
  54087. _this.duration = 1000;
  54088. /**
  54089. * Observable triggered once the interpolation animation has been done.
  54090. */
  54091. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  54092. _this.propertyPath = propertyPath;
  54093. _this.value = value;
  54094. _this.duration = duration;
  54095. _this.stopOtherAnimations = stopOtherAnimations;
  54096. _this.onInterpolationDone = onInterpolationDone;
  54097. _this._target = _this._effectiveTarget = target;
  54098. return _this;
  54099. }
  54100. /** @hidden */
  54101. InterpolateValueAction.prototype._prepare = function () {
  54102. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54103. this._property = this._getProperty(this.propertyPath);
  54104. };
  54105. /**
  54106. * Execute the action starts the value interpolation.
  54107. */
  54108. InterpolateValueAction.prototype.execute = function () {
  54109. var _this = this;
  54110. var scene = this._actionManager.getScene();
  54111. var keys = [
  54112. {
  54113. frame: 0,
  54114. value: this._effectiveTarget[this._property]
  54115. }, {
  54116. frame: 100,
  54117. value: this.value
  54118. }
  54119. ];
  54120. var dataType;
  54121. if (typeof this.value === "number") {
  54122. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  54123. }
  54124. else if (this.value instanceof BABYLON.Color3) {
  54125. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  54126. }
  54127. else if (this.value instanceof BABYLON.Vector3) {
  54128. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  54129. }
  54130. else if (this.value instanceof BABYLON.Matrix) {
  54131. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  54132. }
  54133. else if (this.value instanceof BABYLON.Quaternion) {
  54134. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  54135. }
  54136. else {
  54137. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  54138. return;
  54139. }
  54140. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  54141. animation.setKeys(keys);
  54142. if (this.stopOtherAnimations) {
  54143. scene.stopAnimation(this._effectiveTarget);
  54144. }
  54145. var wrapper = function () {
  54146. _this.onInterpolationDoneObservable.notifyObservers(_this);
  54147. if (_this.onInterpolationDone) {
  54148. _this.onInterpolationDone();
  54149. }
  54150. };
  54151. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  54152. };
  54153. /**
  54154. * Serializes the actions and its related information.
  54155. * @param parent defines the object to serialize in
  54156. * @returns the serialized object
  54157. */
  54158. InterpolateValueAction.prototype.serialize = function (parent) {
  54159. return _super.prototype._serialize.call(this, {
  54160. name: "InterpolateValueAction",
  54161. properties: [
  54162. BABYLON.Action._GetTargetProperty(this._target),
  54163. { name: "propertyPath", value: this.propertyPath },
  54164. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54165. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54166. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54167. ]
  54168. }, parent);
  54169. };
  54170. return InterpolateValueAction;
  54171. }(BABYLON.Action));
  54172. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54173. })(BABYLON || (BABYLON = {}));
  54174. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54175. var BABYLON;
  54176. (function (BABYLON) {
  54177. /**
  54178. * This defines an action responsible to toggle a boolean once triggered.
  54179. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54180. */
  54181. var SwitchBooleanAction = /** @class */ (function (_super) {
  54182. __extends(SwitchBooleanAction, _super);
  54183. /**
  54184. * Instantiate the action
  54185. * @param triggerOptions defines the trigger options
  54186. * @param target defines the object containing the boolean
  54187. * @param propertyPath defines the path to the boolean property in the target object
  54188. * @param condition defines the trigger related conditions
  54189. */
  54190. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54191. var _this = _super.call(this, triggerOptions, condition) || this;
  54192. _this.propertyPath = propertyPath;
  54193. _this._target = _this._effectiveTarget = target;
  54194. return _this;
  54195. }
  54196. /** @hidden */
  54197. SwitchBooleanAction.prototype._prepare = function () {
  54198. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54199. this._property = this._getProperty(this.propertyPath);
  54200. };
  54201. /**
  54202. * Execute the action toggle the boolean value.
  54203. */
  54204. SwitchBooleanAction.prototype.execute = function () {
  54205. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54206. };
  54207. /**
  54208. * Serializes the actions and its related information.
  54209. * @param parent defines the object to serialize in
  54210. * @returns the serialized object
  54211. */
  54212. SwitchBooleanAction.prototype.serialize = function (parent) {
  54213. return _super.prototype._serialize.call(this, {
  54214. name: "SwitchBooleanAction",
  54215. properties: [
  54216. BABYLON.Action._GetTargetProperty(this._target),
  54217. { name: "propertyPath", value: this.propertyPath }
  54218. ]
  54219. }, parent);
  54220. };
  54221. return SwitchBooleanAction;
  54222. }(BABYLON.Action));
  54223. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54224. /**
  54225. * This defines an action responsible to set a the state field of the target
  54226. * to a desired value once triggered.
  54227. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54228. */
  54229. var SetStateAction = /** @class */ (function (_super) {
  54230. __extends(SetStateAction, _super);
  54231. /**
  54232. * Instantiate the action
  54233. * @param triggerOptions defines the trigger options
  54234. * @param target defines the object containing the state property
  54235. * @param value defines the value to store in the state field
  54236. * @param condition defines the trigger related conditions
  54237. */
  54238. function SetStateAction(triggerOptions, target, value, condition) {
  54239. var _this = _super.call(this, triggerOptions, condition) || this;
  54240. _this.value = value;
  54241. _this._target = target;
  54242. return _this;
  54243. }
  54244. /**
  54245. * Execute the action and store the value on the target state property.
  54246. */
  54247. SetStateAction.prototype.execute = function () {
  54248. this._target.state = this.value;
  54249. };
  54250. /**
  54251. * Serializes the actions and its related information.
  54252. * @param parent defines the object to serialize in
  54253. * @returns the serialized object
  54254. */
  54255. SetStateAction.prototype.serialize = function (parent) {
  54256. return _super.prototype._serialize.call(this, {
  54257. name: "SetStateAction",
  54258. properties: [
  54259. BABYLON.Action._GetTargetProperty(this._target),
  54260. { name: "value", value: this.value }
  54261. ]
  54262. }, parent);
  54263. };
  54264. return SetStateAction;
  54265. }(BABYLON.Action));
  54266. BABYLON.SetStateAction = SetStateAction;
  54267. /**
  54268. * This defines an action responsible to set a property of the target
  54269. * to a desired value once triggered.
  54270. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54271. */
  54272. var SetValueAction = /** @class */ (function (_super) {
  54273. __extends(SetValueAction, _super);
  54274. /**
  54275. * Instantiate the action
  54276. * @param triggerOptions defines the trigger options
  54277. * @param target defines the object containing the property
  54278. * @param propertyPath defines the path of the property to set in the target
  54279. * @param value defines the value to set in the property
  54280. * @param condition defines the trigger related conditions
  54281. */
  54282. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54283. var _this = _super.call(this, triggerOptions, condition) || this;
  54284. _this.propertyPath = propertyPath;
  54285. _this.value = value;
  54286. _this._target = _this._effectiveTarget = target;
  54287. return _this;
  54288. }
  54289. /** @hidden */
  54290. SetValueAction.prototype._prepare = function () {
  54291. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54292. this._property = this._getProperty(this.propertyPath);
  54293. };
  54294. /**
  54295. * Execute the action and set the targetted property to the desired value.
  54296. */
  54297. SetValueAction.prototype.execute = function () {
  54298. this._effectiveTarget[this._property] = this.value;
  54299. if (this._target.markAsDirty) {
  54300. this._target.markAsDirty(this._property);
  54301. }
  54302. };
  54303. /**
  54304. * Serializes the actions and its related information.
  54305. * @param parent defines the object to serialize in
  54306. * @returns the serialized object
  54307. */
  54308. SetValueAction.prototype.serialize = function (parent) {
  54309. return _super.prototype._serialize.call(this, {
  54310. name: "SetValueAction",
  54311. properties: [
  54312. BABYLON.Action._GetTargetProperty(this._target),
  54313. { name: "propertyPath", value: this.propertyPath },
  54314. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54315. ]
  54316. }, parent);
  54317. };
  54318. return SetValueAction;
  54319. }(BABYLON.Action));
  54320. BABYLON.SetValueAction = SetValueAction;
  54321. /**
  54322. * This defines an action responsible to increment the target value
  54323. * to a desired value once triggered.
  54324. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54325. */
  54326. var IncrementValueAction = /** @class */ (function (_super) {
  54327. __extends(IncrementValueAction, _super);
  54328. /**
  54329. * Instantiate the action
  54330. * @param triggerOptions defines the trigger options
  54331. * @param target defines the object containing the property
  54332. * @param propertyPath defines the path of the property to increment in the target
  54333. * @param value defines the value value we should increment the property by
  54334. * @param condition defines the trigger related conditions
  54335. */
  54336. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54337. var _this = _super.call(this, triggerOptions, condition) || this;
  54338. _this.propertyPath = propertyPath;
  54339. _this.value = value;
  54340. _this._target = _this._effectiveTarget = target;
  54341. return _this;
  54342. }
  54343. /** @hidden */
  54344. IncrementValueAction.prototype._prepare = function () {
  54345. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54346. this._property = this._getProperty(this.propertyPath);
  54347. if (typeof this._effectiveTarget[this._property] !== "number") {
  54348. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54349. }
  54350. };
  54351. /**
  54352. * Execute the action and increment the target of the value amount.
  54353. */
  54354. IncrementValueAction.prototype.execute = function () {
  54355. this._effectiveTarget[this._property] += this.value;
  54356. if (this._target.markAsDirty) {
  54357. this._target.markAsDirty(this._property);
  54358. }
  54359. };
  54360. /**
  54361. * Serializes the actions and its related information.
  54362. * @param parent defines the object to serialize in
  54363. * @returns the serialized object
  54364. */
  54365. IncrementValueAction.prototype.serialize = function (parent) {
  54366. return _super.prototype._serialize.call(this, {
  54367. name: "IncrementValueAction",
  54368. properties: [
  54369. BABYLON.Action._GetTargetProperty(this._target),
  54370. { name: "propertyPath", value: this.propertyPath },
  54371. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54372. ]
  54373. }, parent);
  54374. };
  54375. return IncrementValueAction;
  54376. }(BABYLON.Action));
  54377. BABYLON.IncrementValueAction = IncrementValueAction;
  54378. /**
  54379. * This defines an action responsible to start an animation once triggered.
  54380. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54381. */
  54382. var PlayAnimationAction = /** @class */ (function (_super) {
  54383. __extends(PlayAnimationAction, _super);
  54384. /**
  54385. * Instantiate the action
  54386. * @param triggerOptions defines the trigger options
  54387. * @param target defines the target animation or animation name
  54388. * @param from defines from where the animation should start (animation frame)
  54389. * @param end defines where the animation should stop (animation frame)
  54390. * @param loop defines if the animation should loop or stop after the first play
  54391. * @param condition defines the trigger related conditions
  54392. */
  54393. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54394. var _this = _super.call(this, triggerOptions, condition) || this;
  54395. _this.from = from;
  54396. _this.to = to;
  54397. _this.loop = loop;
  54398. _this._target = target;
  54399. return _this;
  54400. }
  54401. /** @hidden */
  54402. PlayAnimationAction.prototype._prepare = function () {
  54403. };
  54404. /**
  54405. * Execute the action and play the animation.
  54406. */
  54407. PlayAnimationAction.prototype.execute = function () {
  54408. var scene = this._actionManager.getScene();
  54409. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54410. };
  54411. /**
  54412. * Serializes the actions and its related information.
  54413. * @param parent defines the object to serialize in
  54414. * @returns the serialized object
  54415. */
  54416. PlayAnimationAction.prototype.serialize = function (parent) {
  54417. return _super.prototype._serialize.call(this, {
  54418. name: "PlayAnimationAction",
  54419. properties: [
  54420. BABYLON.Action._GetTargetProperty(this._target),
  54421. { name: "from", value: String(this.from) },
  54422. { name: "to", value: String(this.to) },
  54423. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54424. ]
  54425. }, parent);
  54426. };
  54427. return PlayAnimationAction;
  54428. }(BABYLON.Action));
  54429. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54430. /**
  54431. * This defines an action responsible to stop an animation once triggered.
  54432. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54433. */
  54434. var StopAnimationAction = /** @class */ (function (_super) {
  54435. __extends(StopAnimationAction, _super);
  54436. /**
  54437. * Instantiate the action
  54438. * @param triggerOptions defines the trigger options
  54439. * @param target defines the target animation or animation name
  54440. * @param condition defines the trigger related conditions
  54441. */
  54442. function StopAnimationAction(triggerOptions, target, condition) {
  54443. var _this = _super.call(this, triggerOptions, condition) || this;
  54444. _this._target = target;
  54445. return _this;
  54446. }
  54447. /** @hidden */
  54448. StopAnimationAction.prototype._prepare = function () {
  54449. };
  54450. /**
  54451. * Execute the action and stop the animation.
  54452. */
  54453. StopAnimationAction.prototype.execute = function () {
  54454. var scene = this._actionManager.getScene();
  54455. scene.stopAnimation(this._target);
  54456. };
  54457. /**
  54458. * Serializes the actions and its related information.
  54459. * @param parent defines the object to serialize in
  54460. * @returns the serialized object
  54461. */
  54462. StopAnimationAction.prototype.serialize = function (parent) {
  54463. return _super.prototype._serialize.call(this, {
  54464. name: "StopAnimationAction",
  54465. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54466. }, parent);
  54467. };
  54468. return StopAnimationAction;
  54469. }(BABYLON.Action));
  54470. BABYLON.StopAnimationAction = StopAnimationAction;
  54471. /**
  54472. * This defines an action responsible that does nothing once triggered.
  54473. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54474. */
  54475. var DoNothingAction = /** @class */ (function (_super) {
  54476. __extends(DoNothingAction, _super);
  54477. /**
  54478. * Instantiate the action
  54479. * @param triggerOptions defines the trigger options
  54480. * @param condition defines the trigger related conditions
  54481. */
  54482. function DoNothingAction(triggerOptions, condition) {
  54483. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54484. return _super.call(this, triggerOptions, condition) || this;
  54485. }
  54486. /**
  54487. * Execute the action and do nothing.
  54488. */
  54489. DoNothingAction.prototype.execute = function () {
  54490. };
  54491. /**
  54492. * Serializes the actions and its related information.
  54493. * @param parent defines the object to serialize in
  54494. * @returns the serialized object
  54495. */
  54496. DoNothingAction.prototype.serialize = function (parent) {
  54497. return _super.prototype._serialize.call(this, {
  54498. name: "DoNothingAction",
  54499. properties: []
  54500. }, parent);
  54501. };
  54502. return DoNothingAction;
  54503. }(BABYLON.Action));
  54504. BABYLON.DoNothingAction = DoNothingAction;
  54505. /**
  54506. * This defines an action responsible to trigger several actions once triggered.
  54507. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54508. */
  54509. var CombineAction = /** @class */ (function (_super) {
  54510. __extends(CombineAction, _super);
  54511. /**
  54512. * Instantiate the action
  54513. * @param triggerOptions defines the trigger options
  54514. * @param children defines the list of aggregated animations to run
  54515. * @param condition defines the trigger related conditions
  54516. */
  54517. function CombineAction(triggerOptions, children, condition) {
  54518. var _this = _super.call(this, triggerOptions, condition) || this;
  54519. _this.children = children;
  54520. return _this;
  54521. }
  54522. /** @hidden */
  54523. CombineAction.prototype._prepare = function () {
  54524. for (var index = 0; index < this.children.length; index++) {
  54525. this.children[index]._actionManager = this._actionManager;
  54526. this.children[index]._prepare();
  54527. }
  54528. };
  54529. /**
  54530. * Execute the action and executes all the aggregated actions.
  54531. */
  54532. CombineAction.prototype.execute = function (evt) {
  54533. for (var index = 0; index < this.children.length; index++) {
  54534. this.children[index].execute(evt);
  54535. }
  54536. };
  54537. /**
  54538. * Serializes the actions and its related information.
  54539. * @param parent defines the object to serialize in
  54540. * @returns the serialized object
  54541. */
  54542. CombineAction.prototype.serialize = function (parent) {
  54543. var serializationObject = _super.prototype._serialize.call(this, {
  54544. name: "CombineAction",
  54545. properties: [],
  54546. combine: []
  54547. }, parent);
  54548. for (var i = 0; i < this.children.length; i++) {
  54549. serializationObject.combine.push(this.children[i].serialize(null));
  54550. }
  54551. return serializationObject;
  54552. };
  54553. return CombineAction;
  54554. }(BABYLON.Action));
  54555. BABYLON.CombineAction = CombineAction;
  54556. /**
  54557. * This defines an action responsible to run code (external event) once triggered.
  54558. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54559. */
  54560. var ExecuteCodeAction = /** @class */ (function (_super) {
  54561. __extends(ExecuteCodeAction, _super);
  54562. /**
  54563. * Instantiate the action
  54564. * @param triggerOptions defines the trigger options
  54565. * @param func defines the callback function to run
  54566. * @param condition defines the trigger related conditions
  54567. */
  54568. function ExecuteCodeAction(triggerOptions, func, condition) {
  54569. var _this = _super.call(this, triggerOptions, condition) || this;
  54570. _this.func = func;
  54571. return _this;
  54572. }
  54573. /**
  54574. * Execute the action and run the attached code.
  54575. */
  54576. ExecuteCodeAction.prototype.execute = function (evt) {
  54577. this.func(evt);
  54578. };
  54579. return ExecuteCodeAction;
  54580. }(BABYLON.Action));
  54581. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54582. /**
  54583. * This defines an action responsible to set the parent property of the target once triggered.
  54584. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  54585. */
  54586. var SetParentAction = /** @class */ (function (_super) {
  54587. __extends(SetParentAction, _super);
  54588. /**
  54589. * Instantiate the action
  54590. * @param triggerOptions defines the trigger options
  54591. * @param target defines the target containing the parent property
  54592. * @param parent defines from where the animation should start (animation frame)
  54593. * @param condition defines the trigger related conditions
  54594. */
  54595. function SetParentAction(triggerOptions, target, parent, condition) {
  54596. var _this = _super.call(this, triggerOptions, condition) || this;
  54597. _this._target = target;
  54598. _this._parent = parent;
  54599. return _this;
  54600. }
  54601. /** @hidden */
  54602. SetParentAction.prototype._prepare = function () {
  54603. };
  54604. /**
  54605. * Execute the action and set the parent property.
  54606. */
  54607. SetParentAction.prototype.execute = function () {
  54608. if (this._target.parent === this._parent) {
  54609. return;
  54610. }
  54611. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54612. invertParentWorldMatrix.invert();
  54613. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54614. this._target.parent = this._parent;
  54615. };
  54616. /**
  54617. * Serializes the actions and its related information.
  54618. * @param parent defines the object to serialize in
  54619. * @returns the serialized object
  54620. */
  54621. SetParentAction.prototype.serialize = function (parent) {
  54622. return _super.prototype._serialize.call(this, {
  54623. name: "SetParentAction",
  54624. properties: [
  54625. BABYLON.Action._GetTargetProperty(this._target),
  54626. BABYLON.Action._GetTargetProperty(this._parent),
  54627. ]
  54628. }, parent);
  54629. };
  54630. return SetParentAction;
  54631. }(BABYLON.Action));
  54632. BABYLON.SetParentAction = SetParentAction;
  54633. })(BABYLON || (BABYLON = {}));
  54634. //# sourceMappingURL=babylon.directActions.js.map
  54635. var BABYLON;
  54636. (function (BABYLON) {
  54637. var SpriteManager = /** @class */ (function () {
  54638. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54639. if (epsilon === void 0) { epsilon = 0.01; }
  54640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54641. this.name = name;
  54642. this.sprites = new Array();
  54643. this.renderingGroupId = 0;
  54644. this.layerMask = 0x0FFFFFFF;
  54645. this.fogEnabled = true;
  54646. this.isPickable = false;
  54647. /**
  54648. * An event triggered when the manager is disposed.
  54649. */
  54650. this.onDisposeObservable = new BABYLON.Observable();
  54651. this._vertexBuffers = {};
  54652. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  54653. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  54654. }
  54655. this._capacity = capacity;
  54656. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54657. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54658. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54659. if (cellSize.width && cellSize.height) {
  54660. this.cellWidth = cellSize.width;
  54661. this.cellHeight = cellSize.height;
  54662. }
  54663. else if (cellSize !== undefined) {
  54664. this.cellWidth = cellSize;
  54665. this.cellHeight = cellSize;
  54666. }
  54667. else {
  54668. return;
  54669. }
  54670. this._epsilon = epsilon;
  54671. this._scene = scene;
  54672. this._scene.spriteManagers.push(this);
  54673. var indices = [];
  54674. var index = 0;
  54675. for (var count = 0; count < capacity; count++) {
  54676. indices.push(index);
  54677. indices.push(index + 1);
  54678. indices.push(index + 2);
  54679. indices.push(index);
  54680. indices.push(index + 2);
  54681. indices.push(index + 3);
  54682. index += 4;
  54683. }
  54684. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54685. // VBO
  54686. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54687. this._vertexData = new Float32Array(capacity * 16 * 4);
  54688. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54689. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54690. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54691. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54692. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54694. this._vertexBuffers["options"] = options;
  54695. this._vertexBuffers["cellInfo"] = cellInfo;
  54696. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54697. // Effects
  54698. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54699. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54700. }
  54701. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54702. set: function (callback) {
  54703. if (this._onDisposeObserver) {
  54704. this.onDisposeObservable.remove(this._onDisposeObserver);
  54705. }
  54706. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54707. },
  54708. enumerable: true,
  54709. configurable: true
  54710. });
  54711. Object.defineProperty(SpriteManager.prototype, "texture", {
  54712. get: function () {
  54713. return this._spriteTexture;
  54714. },
  54715. set: function (value) {
  54716. this._spriteTexture = value;
  54717. },
  54718. enumerable: true,
  54719. configurable: true
  54720. });
  54721. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54722. var arrayOffset = index * 16;
  54723. if (offsetX === 0)
  54724. offsetX = this._epsilon;
  54725. else if (offsetX === 1)
  54726. offsetX = 1 - this._epsilon;
  54727. if (offsetY === 0)
  54728. offsetY = this._epsilon;
  54729. else if (offsetY === 1)
  54730. offsetY = 1 - this._epsilon;
  54731. this._vertexData[arrayOffset] = sprite.position.x;
  54732. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54733. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54734. this._vertexData[arrayOffset + 3] = sprite.angle;
  54735. this._vertexData[arrayOffset + 4] = sprite.width;
  54736. this._vertexData[arrayOffset + 5] = sprite.height;
  54737. this._vertexData[arrayOffset + 6] = offsetX;
  54738. this._vertexData[arrayOffset + 7] = offsetY;
  54739. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54740. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54741. var offset = (sprite.cellIndex / rowSize) >> 0;
  54742. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54743. this._vertexData[arrayOffset + 11] = offset;
  54744. // Color
  54745. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54746. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54747. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54748. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54749. };
  54750. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54751. var count = Math.min(this._capacity, this.sprites.length);
  54752. var min = BABYLON.Vector3.Zero();
  54753. var max = BABYLON.Vector3.Zero();
  54754. var distance = Number.MAX_VALUE;
  54755. var currentSprite = null;
  54756. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54757. var cameraView = camera.getViewMatrix();
  54758. for (var index = 0; index < count; index++) {
  54759. var sprite = this.sprites[index];
  54760. if (!sprite) {
  54761. continue;
  54762. }
  54763. if (predicate) {
  54764. if (!predicate(sprite)) {
  54765. continue;
  54766. }
  54767. }
  54768. else if (!sprite.isPickable) {
  54769. continue;
  54770. }
  54771. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54772. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54773. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54774. if (ray.intersectsBoxMinMax(min, max)) {
  54775. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54776. if (distance > currentDistance) {
  54777. distance = currentDistance;
  54778. currentSprite = sprite;
  54779. if (fastCheck) {
  54780. break;
  54781. }
  54782. }
  54783. }
  54784. }
  54785. if (currentSprite) {
  54786. var result = new BABYLON.PickingInfo();
  54787. result.hit = true;
  54788. result.pickedSprite = currentSprite;
  54789. result.distance = distance;
  54790. return result;
  54791. }
  54792. return null;
  54793. };
  54794. SpriteManager.prototype.render = function () {
  54795. // Check
  54796. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54797. return;
  54798. var engine = this._scene.getEngine();
  54799. var baseSize = this._spriteTexture.getBaseSize();
  54800. // Sprites
  54801. var deltaTime = engine.getDeltaTime();
  54802. var max = Math.min(this._capacity, this.sprites.length);
  54803. var rowSize = baseSize.width / this.cellWidth;
  54804. var offset = 0;
  54805. for (var index = 0; index < max; index++) {
  54806. var sprite = this.sprites[index];
  54807. if (!sprite || !sprite.isVisible) {
  54808. continue;
  54809. }
  54810. sprite._animate(deltaTime);
  54811. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54812. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54813. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54814. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54815. }
  54816. this._buffer.update(this._vertexData);
  54817. // Render
  54818. var effect = this._effectBase;
  54819. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54820. effect = this._effectFog;
  54821. }
  54822. engine.enableEffect(effect);
  54823. var viewMatrix = this._scene.getViewMatrix();
  54824. effect.setTexture("diffuseSampler", this._spriteTexture);
  54825. effect.setMatrix("view", viewMatrix);
  54826. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54827. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54828. // Fog
  54829. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54830. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54831. effect.setColor3("vFogColor", this._scene.fogColor);
  54832. }
  54833. // VBOs
  54834. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54835. // Draw order
  54836. engine.setDepthFunctionToLessOrEqual();
  54837. effect.setBool("alphaTest", true);
  54838. engine.setColorWrite(false);
  54839. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54840. engine.setColorWrite(true);
  54841. effect.setBool("alphaTest", false);
  54842. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54843. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54844. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54845. };
  54846. SpriteManager.prototype.dispose = function () {
  54847. if (this._buffer) {
  54848. this._buffer.dispose();
  54849. this._buffer = null;
  54850. }
  54851. if (this._indexBuffer) {
  54852. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54853. this._indexBuffer = null;
  54854. }
  54855. if (this._spriteTexture) {
  54856. this._spriteTexture.dispose();
  54857. this._spriteTexture = null;
  54858. }
  54859. // Remove from scene
  54860. var index = this._scene.spriteManagers.indexOf(this);
  54861. this._scene.spriteManagers.splice(index, 1);
  54862. // Callback
  54863. this.onDisposeObservable.notifyObservers(this);
  54864. this.onDisposeObservable.clear();
  54865. };
  54866. return SpriteManager;
  54867. }());
  54868. BABYLON.SpriteManager = SpriteManager;
  54869. })(BABYLON || (BABYLON = {}));
  54870. //# sourceMappingURL=babylon.spriteManager.js.map
  54871. var BABYLON;
  54872. (function (BABYLON) {
  54873. var Sprite = /** @class */ (function () {
  54874. function Sprite(name, manager) {
  54875. this.name = name;
  54876. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54877. this.width = 1.0;
  54878. this.height = 1.0;
  54879. this.angle = 0;
  54880. this.cellIndex = 0;
  54881. this.invertU = 0;
  54882. this.invertV = 0;
  54883. this.animations = new Array();
  54884. this.isPickable = false;
  54885. this._animationStarted = false;
  54886. this._loopAnimation = false;
  54887. this._fromIndex = 0;
  54888. this._toIndex = 0;
  54889. this._delay = 0;
  54890. this._direction = 1;
  54891. this._time = 0;
  54892. /**
  54893. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54894. */
  54895. this.isVisible = true;
  54896. this._manager = manager;
  54897. this._manager.sprites.push(this);
  54898. this.position = BABYLON.Vector3.Zero();
  54899. }
  54900. Object.defineProperty(Sprite.prototype, "size", {
  54901. get: function () {
  54902. return this.width;
  54903. },
  54904. set: function (value) {
  54905. this.width = value;
  54906. this.height = value;
  54907. },
  54908. enumerable: true,
  54909. configurable: true
  54910. });
  54911. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54912. this._fromIndex = from;
  54913. this._toIndex = to;
  54914. this._loopAnimation = loop;
  54915. this._delay = delay;
  54916. this._animationStarted = true;
  54917. this._direction = from < to ? 1 : -1;
  54918. this.cellIndex = from;
  54919. this._time = 0;
  54920. this._onAnimationEnd = onAnimationEnd;
  54921. };
  54922. Sprite.prototype.stopAnimation = function () {
  54923. this._animationStarted = false;
  54924. };
  54925. /** @hidden */
  54926. Sprite.prototype._animate = function (deltaTime) {
  54927. if (!this._animationStarted)
  54928. return;
  54929. this._time += deltaTime;
  54930. if (this._time > this._delay) {
  54931. this._time = this._time % this._delay;
  54932. this.cellIndex += this._direction;
  54933. if (this.cellIndex > this._toIndex) {
  54934. if (this._loopAnimation) {
  54935. this.cellIndex = this._fromIndex;
  54936. }
  54937. else {
  54938. this.cellIndex = this._toIndex;
  54939. this._animationStarted = false;
  54940. if (this._onAnimationEnd) {
  54941. this._onAnimationEnd();
  54942. }
  54943. if (this.disposeWhenFinishedAnimating) {
  54944. this.dispose();
  54945. }
  54946. }
  54947. }
  54948. }
  54949. };
  54950. Sprite.prototype.dispose = function () {
  54951. for (var i = 0; i < this._manager.sprites.length; i++) {
  54952. if (this._manager.sprites[i] == this) {
  54953. this._manager.sprites.splice(i, 1);
  54954. }
  54955. }
  54956. };
  54957. return Sprite;
  54958. }());
  54959. BABYLON.Sprite = Sprite;
  54960. })(BABYLON || (BABYLON = {}));
  54961. //# sourceMappingURL=babylon.sprite.js.map
  54962. var BABYLON;
  54963. (function (BABYLON) {
  54964. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  54965. if (!BABYLON.PickingInfo) {
  54966. return null;
  54967. }
  54968. var pickingInfo = null;
  54969. if (!camera) {
  54970. if (!this.activeCamera) {
  54971. return null;
  54972. }
  54973. camera = this.activeCamera;
  54974. }
  54975. if (this.spriteManagers.length > 0) {
  54976. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  54977. var spriteManager = this.spriteManagers[spriteIndex];
  54978. if (!spriteManager.isPickable) {
  54979. continue;
  54980. }
  54981. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  54982. if (!result || !result.hit)
  54983. continue;
  54984. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  54985. continue;
  54986. pickingInfo = result;
  54987. if (fastCheck) {
  54988. break;
  54989. }
  54990. }
  54991. }
  54992. return pickingInfo || new BABYLON.PickingInfo();
  54993. };
  54994. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  54995. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  54996. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  54997. };
  54998. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  54999. if (!this._tempSpritePickingRay) {
  55000. return null;
  55001. }
  55002. if (!camera) {
  55003. if (!this.activeCamera) {
  55004. return null;
  55005. }
  55006. camera = this.activeCamera;
  55007. }
  55008. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  55009. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  55010. };
  55011. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  55012. if (this._pointerOverSprite === sprite) {
  55013. return;
  55014. }
  55015. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55016. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55017. }
  55018. this._pointerOverSprite = sprite;
  55019. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  55020. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  55021. }
  55022. };
  55023. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  55024. return this._pointerOverSprite;
  55025. };
  55026. /**
  55027. * Defines the sprite scene component responsible to manage sprites
  55028. * in a given scene.
  55029. */
  55030. var SpriteSceneComponent = /** @class */ (function () {
  55031. /**
  55032. * Creates a new instance of the component for the given scene
  55033. * @param scene Defines the scene to register the component in
  55034. */
  55035. function SpriteSceneComponent(scene) {
  55036. /**
  55037. * The component name helpfull to identify the component in the list of scene components.
  55038. */
  55039. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  55040. this.scene = scene;
  55041. this.scene.spriteManagers = new Array();
  55042. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  55043. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  55044. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  55045. this._spritePredicate = function (sprite) {
  55046. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  55047. };
  55048. }
  55049. /**
  55050. * Registers the component in a given scene
  55051. */
  55052. SpriteSceneComponent.prototype.register = function () {
  55053. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  55054. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  55055. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  55056. };
  55057. /**
  55058. * Rebuilds the elements related to this component in case of
  55059. * context lost for instance.
  55060. */
  55061. SpriteSceneComponent.prototype.rebuild = function () {
  55062. /** Nothing to do for sprites */
  55063. };
  55064. /**
  55065. * Disposes the component and the associated ressources.
  55066. */
  55067. SpriteSceneComponent.prototype.dispose = function () {
  55068. this.scene.onBeforeSpritesRenderingObservable.clear();
  55069. this.scene.onAfterSpritesRenderingObservable.clear();
  55070. var spriteManagers = this.scene.spriteManagers;
  55071. while (spriteManagers.length) {
  55072. spriteManagers[0].dispose();
  55073. }
  55074. };
  55075. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  55076. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  55077. if (result) {
  55078. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  55079. }
  55080. return result;
  55081. };
  55082. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  55083. var scene = this.scene;
  55084. if (isMeshPicked) {
  55085. scene.setPointerOverSprite(null);
  55086. }
  55087. else {
  55088. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  55089. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55090. scene.setPointerOverSprite(pickResult.pickedSprite);
  55091. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  55092. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  55093. }
  55094. else {
  55095. canvas.style.cursor = scene.hoverCursor;
  55096. }
  55097. }
  55098. else {
  55099. scene.setPointerOverSprite(null);
  55100. }
  55101. }
  55102. return pickResult;
  55103. };
  55104. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55105. var scene = this.scene;
  55106. scene._pickedDownSprite = null;
  55107. if (scene.spriteManagers.length > 0) {
  55108. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55109. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  55110. if (pickResult.pickedSprite.actionManager) {
  55111. scene._pickedDownSprite = pickResult.pickedSprite;
  55112. switch (evt.button) {
  55113. case 0:
  55114. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55115. break;
  55116. case 1:
  55117. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55118. break;
  55119. case 2:
  55120. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55121. break;
  55122. }
  55123. if (pickResult.pickedSprite.actionManager) {
  55124. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  55125. }
  55126. }
  55127. }
  55128. }
  55129. return pickResult;
  55130. };
  55131. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  55132. var scene = this.scene;
  55133. if (scene.spriteManagers.length > 0) {
  55134. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  55135. if (spritePickResult) {
  55136. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  55137. if (spritePickResult.pickedSprite.actionManager) {
  55138. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55139. if (spritePickResult.pickedSprite.actionManager) {
  55140. if (!this.scene._isPointerSwiping()) {
  55141. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  55142. }
  55143. }
  55144. }
  55145. }
  55146. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  55147. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  55148. }
  55149. }
  55150. }
  55151. return pickResult;
  55152. };
  55153. return SpriteSceneComponent;
  55154. }());
  55155. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  55156. })(BABYLON || (BABYLON = {}));
  55157. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  55158. var BABYLON;
  55159. (function (BABYLON) {
  55160. var IntersectionInfo = /** @class */ (function () {
  55161. function IntersectionInfo(bu, bv, distance) {
  55162. this.bu = bu;
  55163. this.bv = bv;
  55164. this.distance = distance;
  55165. this.faceId = 0;
  55166. this.subMeshId = 0;
  55167. }
  55168. return IntersectionInfo;
  55169. }());
  55170. BABYLON.IntersectionInfo = IntersectionInfo;
  55171. /**
  55172. * Information about the result of picking within a scene
  55173. * See https://doc.babylonjs.com/babylon101/picking_collisions
  55174. */
  55175. var PickingInfo = /** @class */ (function () {
  55176. function PickingInfo() {
  55177. /**
  55178. * If the pick collided with an object
  55179. */
  55180. this.hit = false;
  55181. /**
  55182. * Distance away where the pick collided
  55183. */
  55184. this.distance = 0;
  55185. /**
  55186. * The location of pick collision
  55187. */
  55188. this.pickedPoint = null;
  55189. /**
  55190. * The mesh corresponding the the pick collision
  55191. */
  55192. this.pickedMesh = null;
  55193. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  55194. this.bu = 0;
  55195. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  55196. this.bv = 0;
  55197. /** The id of the face on the mesh that was picked */
  55198. this.faceId = -1;
  55199. /** Id of the the submesh that was picked */
  55200. this.subMeshId = 0;
  55201. /** If a sprite was picked, this will be the sprite the pick collided with */
  55202. this.pickedSprite = null;
  55203. /**
  55204. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  55205. */
  55206. this.originMesh = null;
  55207. /**
  55208. * The ray that was used to perform the picking.
  55209. */
  55210. this.ray = null;
  55211. }
  55212. /**
  55213. * Gets the normal correspodning to the face the pick collided with
  55214. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  55215. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  55216. * @returns The normal correspodning to the face the pick collided with
  55217. */
  55218. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  55219. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  55220. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  55221. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  55222. return null;
  55223. }
  55224. var indices = this.pickedMesh.getIndices();
  55225. if (!indices) {
  55226. return null;
  55227. }
  55228. var result;
  55229. if (useVerticesNormals) {
  55230. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55231. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  55232. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  55233. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  55234. normal0 = normal0.scale(this.bu);
  55235. normal1 = normal1.scale(this.bv);
  55236. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  55237. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  55238. }
  55239. else {
  55240. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55241. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  55242. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  55243. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  55244. var p1p2 = vertex1.subtract(vertex2);
  55245. var p3p2 = vertex3.subtract(vertex2);
  55246. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  55247. }
  55248. if (useWorldCoordinates) {
  55249. var wm = this.pickedMesh.getWorldMatrix();
  55250. if (this.pickedMesh.nonUniformScaling) {
  55251. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  55252. wm = BABYLON.Tmp.Matrix[0];
  55253. wm.setTranslationFromFloats(0, 0, 0);
  55254. wm.invert();
  55255. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  55256. wm = BABYLON.Tmp.Matrix[1];
  55257. }
  55258. result = BABYLON.Vector3.TransformNormal(result, wm);
  55259. }
  55260. result.normalize();
  55261. return result;
  55262. };
  55263. /**
  55264. * Gets the texture coordinates of where the pick occured
  55265. * @returns the vector containing the coordnates of the texture
  55266. */
  55267. PickingInfo.prototype.getTextureCoordinates = function () {
  55268. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55269. return null;
  55270. }
  55271. var indices = this.pickedMesh.getIndices();
  55272. if (!indices) {
  55273. return null;
  55274. }
  55275. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55276. if (!uvs) {
  55277. return null;
  55278. }
  55279. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  55280. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  55281. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  55282. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  55283. uv1 = uv1.scale(this.bu);
  55284. uv2 = uv2.scale(this.bv);
  55285. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  55286. };
  55287. return PickingInfo;
  55288. }());
  55289. BABYLON.PickingInfo = PickingInfo;
  55290. })(BABYLON || (BABYLON = {}));
  55291. //# sourceMappingURL=babylon.pickingInfo.js.map
  55292. var BABYLON;
  55293. (function (BABYLON) {
  55294. var Ray = /** @class */ (function () {
  55295. function Ray(origin, direction, length) {
  55296. if (length === void 0) { length = Number.MAX_VALUE; }
  55297. this.origin = origin;
  55298. this.direction = direction;
  55299. this.length = length;
  55300. }
  55301. // Methods
  55302. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  55303. var d = 0.0;
  55304. var maxValue = Number.MAX_VALUE;
  55305. var inv;
  55306. var min;
  55307. var max;
  55308. var temp;
  55309. if (Math.abs(this.direction.x) < 0.0000001) {
  55310. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  55311. return false;
  55312. }
  55313. }
  55314. else {
  55315. inv = 1.0 / this.direction.x;
  55316. min = (minimum.x - this.origin.x) * inv;
  55317. max = (maximum.x - this.origin.x) * inv;
  55318. if (max === -Infinity) {
  55319. max = Infinity;
  55320. }
  55321. if (min > max) {
  55322. temp = min;
  55323. min = max;
  55324. max = temp;
  55325. }
  55326. d = Math.max(min, d);
  55327. maxValue = Math.min(max, maxValue);
  55328. if (d > maxValue) {
  55329. return false;
  55330. }
  55331. }
  55332. if (Math.abs(this.direction.y) < 0.0000001) {
  55333. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  55334. return false;
  55335. }
  55336. }
  55337. else {
  55338. inv = 1.0 / this.direction.y;
  55339. min = (minimum.y - this.origin.y) * inv;
  55340. max = (maximum.y - this.origin.y) * inv;
  55341. if (max === -Infinity) {
  55342. max = Infinity;
  55343. }
  55344. if (min > max) {
  55345. temp = min;
  55346. min = max;
  55347. max = temp;
  55348. }
  55349. d = Math.max(min, d);
  55350. maxValue = Math.min(max, maxValue);
  55351. if (d > maxValue) {
  55352. return false;
  55353. }
  55354. }
  55355. if (Math.abs(this.direction.z) < 0.0000001) {
  55356. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  55357. return false;
  55358. }
  55359. }
  55360. else {
  55361. inv = 1.0 / this.direction.z;
  55362. min = (minimum.z - this.origin.z) * inv;
  55363. max = (maximum.z - this.origin.z) * inv;
  55364. if (max === -Infinity) {
  55365. max = Infinity;
  55366. }
  55367. if (min > max) {
  55368. temp = min;
  55369. min = max;
  55370. max = temp;
  55371. }
  55372. d = Math.max(min, d);
  55373. maxValue = Math.min(max, maxValue);
  55374. if (d > maxValue) {
  55375. return false;
  55376. }
  55377. }
  55378. return true;
  55379. };
  55380. Ray.prototype.intersectsBox = function (box) {
  55381. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  55382. };
  55383. Ray.prototype.intersectsSphere = function (sphere) {
  55384. var x = sphere.center.x - this.origin.x;
  55385. var y = sphere.center.y - this.origin.y;
  55386. var z = sphere.center.z - this.origin.z;
  55387. var pyth = (x * x) + (y * y) + (z * z);
  55388. var rr = sphere.radius * sphere.radius;
  55389. if (pyth <= rr) {
  55390. return true;
  55391. }
  55392. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  55393. if (dot < 0.0) {
  55394. return false;
  55395. }
  55396. var temp = pyth - (dot * dot);
  55397. return temp <= rr;
  55398. };
  55399. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  55400. if (!this._edge1) {
  55401. this._edge1 = BABYLON.Vector3.Zero();
  55402. this._edge2 = BABYLON.Vector3.Zero();
  55403. this._pvec = BABYLON.Vector3.Zero();
  55404. this._tvec = BABYLON.Vector3.Zero();
  55405. this._qvec = BABYLON.Vector3.Zero();
  55406. }
  55407. vertex1.subtractToRef(vertex0, this._edge1);
  55408. vertex2.subtractToRef(vertex0, this._edge2);
  55409. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  55410. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  55411. if (det === 0) {
  55412. return null;
  55413. }
  55414. var invdet = 1 / det;
  55415. this.origin.subtractToRef(vertex0, this._tvec);
  55416. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  55417. if (bu < 0 || bu > 1.0) {
  55418. return null;
  55419. }
  55420. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  55421. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  55422. if (bv < 0 || bu + bv > 1.0) {
  55423. return null;
  55424. }
  55425. //check if the distance is longer than the predefined length.
  55426. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  55427. if (distance > this.length) {
  55428. return null;
  55429. }
  55430. return new BABYLON.IntersectionInfo(bu, bv, distance);
  55431. };
  55432. Ray.prototype.intersectsPlane = function (plane) {
  55433. var distance;
  55434. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  55435. if (Math.abs(result1) < 9.99999997475243E-07) {
  55436. return null;
  55437. }
  55438. else {
  55439. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  55440. distance = (-plane.d - result2) / result1;
  55441. if (distance < 0.0) {
  55442. if (distance < -9.99999997475243E-07) {
  55443. return null;
  55444. }
  55445. else {
  55446. return 0;
  55447. }
  55448. }
  55449. return distance;
  55450. }
  55451. };
  55452. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  55453. var tm = BABYLON.Tmp.Matrix[0];
  55454. mesh.getWorldMatrix().invertToRef(tm);
  55455. if (this._tmpRay) {
  55456. Ray.TransformToRef(this, tm, this._tmpRay);
  55457. }
  55458. else {
  55459. this._tmpRay = Ray.Transform(this, tm);
  55460. }
  55461. return mesh.intersects(this._tmpRay, fastCheck);
  55462. };
  55463. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  55464. if (results) {
  55465. results.length = 0;
  55466. }
  55467. else {
  55468. results = [];
  55469. }
  55470. for (var i = 0; i < meshes.length; i++) {
  55471. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  55472. if (pickInfo.hit) {
  55473. results.push(pickInfo);
  55474. }
  55475. }
  55476. results.sort(this._comparePickingInfo);
  55477. return results;
  55478. };
  55479. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  55480. if (pickingInfoA.distance < pickingInfoB.distance) {
  55481. return -1;
  55482. }
  55483. else if (pickingInfoA.distance > pickingInfoB.distance) {
  55484. return 1;
  55485. }
  55486. else {
  55487. return 0;
  55488. }
  55489. };
  55490. /**
  55491. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  55492. * @param sega the first point of the segment to test the intersection against
  55493. * @param segb the second point of the segment to test the intersection against
  55494. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  55495. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  55496. */
  55497. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  55498. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  55499. var u = segb.subtract(sega);
  55500. var v = rsegb.subtract(this.origin);
  55501. var w = sega.subtract(this.origin);
  55502. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  55503. var b = BABYLON.Vector3.Dot(u, v);
  55504. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  55505. var d = BABYLON.Vector3.Dot(u, w);
  55506. var e = BABYLON.Vector3.Dot(v, w);
  55507. var D = a * c - b * b; // always >= 0
  55508. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  55509. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  55510. // compute the line parameters of the two closest points
  55511. if (D < Ray.smallnum) { // the lines are almost parallel
  55512. sN = 0.0; // force using point P0 on segment S1
  55513. sD = 1.0; // to prevent possible division by 0.0 later
  55514. tN = e;
  55515. tD = c;
  55516. }
  55517. else { // get the closest points on the infinite lines
  55518. sN = (b * e - c * d);
  55519. tN = (a * e - b * d);
  55520. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  55521. sN = 0.0;
  55522. tN = e;
  55523. tD = c;
  55524. }
  55525. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  55526. sN = sD;
  55527. tN = e + b;
  55528. tD = c;
  55529. }
  55530. }
  55531. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  55532. tN = 0.0;
  55533. // recompute sc for this edge
  55534. if (-d < 0.0) {
  55535. sN = 0.0;
  55536. }
  55537. else if (-d > a)
  55538. sN = sD;
  55539. else {
  55540. sN = -d;
  55541. sD = a;
  55542. }
  55543. }
  55544. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  55545. tN = tD;
  55546. // recompute sc for this edge
  55547. if ((-d + b) < 0.0) {
  55548. sN = 0;
  55549. }
  55550. else if ((-d + b) > a) {
  55551. sN = sD;
  55552. }
  55553. else {
  55554. sN = (-d + b);
  55555. sD = a;
  55556. }
  55557. }
  55558. // finally do the division to get sc and tc
  55559. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  55560. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  55561. // get the difference of the two closest points
  55562. var qtc = v.multiplyByFloats(tc, tc, tc);
  55563. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  55564. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  55565. if (isIntersected) {
  55566. return qtc.length();
  55567. }
  55568. return -1;
  55569. };
  55570. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55571. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55572. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55573. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55574. this.direction.normalize();
  55575. return this;
  55576. };
  55577. // Statics
  55578. Ray.Zero = function () {
  55579. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55580. };
  55581. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55582. var result = Ray.Zero();
  55583. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55584. };
  55585. /**
  55586. * 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
  55587. * transformed to the given world matrix.
  55588. * @param origin The origin point
  55589. * @param end The end point
  55590. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55591. */
  55592. Ray.CreateNewFromTo = function (origin, end, world) {
  55593. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55594. var direction = end.subtract(origin);
  55595. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55596. direction.normalize();
  55597. return Ray.Transform(new Ray(origin, direction, length), world);
  55598. };
  55599. Ray.Transform = function (ray, matrix) {
  55600. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55601. Ray.TransformToRef(ray, matrix, result);
  55602. return result;
  55603. };
  55604. Ray.TransformToRef = function (ray, matrix, result) {
  55605. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55606. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55607. result.length = ray.length;
  55608. var dir = result.direction;
  55609. var len = dir.length();
  55610. if (!(len === 0 || len === 1)) {
  55611. var num = 1.0 / len;
  55612. dir.x *= num;
  55613. dir.y *= num;
  55614. dir.z *= num;
  55615. result.length *= len;
  55616. }
  55617. };
  55618. Ray.smallnum = 0.00000001;
  55619. Ray.rayl = 10e8;
  55620. return Ray;
  55621. }());
  55622. BABYLON.Ray = Ray;
  55623. })(BABYLON || (BABYLON = {}));
  55624. //# sourceMappingURL=babylon.ray.js.map
  55625. var BABYLON;
  55626. (function (BABYLON) {
  55627. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55628. if (boxMin.x > sphereCenter.x + sphereRadius)
  55629. return false;
  55630. if (sphereCenter.x - sphereRadius > boxMax.x)
  55631. return false;
  55632. if (boxMin.y > sphereCenter.y + sphereRadius)
  55633. return false;
  55634. if (sphereCenter.y - sphereRadius > boxMax.y)
  55635. return false;
  55636. if (boxMin.z > sphereCenter.z + sphereRadius)
  55637. return false;
  55638. if (sphereCenter.z - sphereRadius > boxMax.z)
  55639. return false;
  55640. return true;
  55641. };
  55642. var getLowestRoot = (function () {
  55643. var result = { root: 0, found: false };
  55644. return function (a, b, c, maxR) {
  55645. result.root = 0;
  55646. result.found = false;
  55647. var determinant = b * b - 4.0 * a * c;
  55648. if (determinant < 0)
  55649. return result;
  55650. var sqrtD = Math.sqrt(determinant);
  55651. var r1 = (-b - sqrtD) / (2.0 * a);
  55652. var r2 = (-b + sqrtD) / (2.0 * a);
  55653. if (r1 > r2) {
  55654. var temp = r2;
  55655. r2 = r1;
  55656. r1 = temp;
  55657. }
  55658. if (r1 > 0 && r1 < maxR) {
  55659. result.root = r1;
  55660. result.found = true;
  55661. return result;
  55662. }
  55663. if (r2 > 0 && r2 < maxR) {
  55664. result.root = r2;
  55665. result.found = true;
  55666. return result;
  55667. }
  55668. return result;
  55669. };
  55670. })();
  55671. /** @hidden */
  55672. var Collider = /** @class */ (function () {
  55673. function Collider() {
  55674. this._collisionPoint = BABYLON.Vector3.Zero();
  55675. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55676. this._tempVector = BABYLON.Vector3.Zero();
  55677. this._tempVector2 = BABYLON.Vector3.Zero();
  55678. this._tempVector3 = BABYLON.Vector3.Zero();
  55679. this._tempVector4 = BABYLON.Vector3.Zero();
  55680. this._edge = BABYLON.Vector3.Zero();
  55681. this._baseToVertex = BABYLON.Vector3.Zero();
  55682. this._destinationPoint = BABYLON.Vector3.Zero();
  55683. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55684. this._displacementVector = BABYLON.Vector3.Zero();
  55685. /** @hidden */
  55686. this._radius = BABYLON.Vector3.One();
  55687. /** @hidden */
  55688. this._retry = 0;
  55689. /** @hidden */
  55690. this._basePointWorld = BABYLON.Vector3.Zero();
  55691. this._velocityWorld = BABYLON.Vector3.Zero();
  55692. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55693. this._collisionMask = -1;
  55694. }
  55695. Object.defineProperty(Collider.prototype, "collisionMask", {
  55696. get: function () {
  55697. return this._collisionMask;
  55698. },
  55699. set: function (mask) {
  55700. this._collisionMask = !isNaN(mask) ? mask : -1;
  55701. },
  55702. enumerable: true,
  55703. configurable: true
  55704. });
  55705. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55706. /**
  55707. * Gets the plane normal used to compute the sliding response (in local space)
  55708. */
  55709. get: function () {
  55710. return this._slidePlaneNormal;
  55711. },
  55712. enumerable: true,
  55713. configurable: true
  55714. });
  55715. // Methods
  55716. /** @hidden */
  55717. Collider.prototype._initialize = function (source, dir, e) {
  55718. this._velocity = dir;
  55719. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55720. this._basePoint = source;
  55721. source.multiplyToRef(this._radius, this._basePointWorld);
  55722. dir.multiplyToRef(this._radius, this._velocityWorld);
  55723. this._velocityWorldLength = this._velocityWorld.length();
  55724. this._epsilon = e;
  55725. this.collisionFound = false;
  55726. };
  55727. /** @hidden */
  55728. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55729. pa.subtractToRef(point, this._tempVector);
  55730. pb.subtractToRef(point, this._tempVector2);
  55731. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55732. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55733. if (d < 0)
  55734. return false;
  55735. pc.subtractToRef(point, this._tempVector3);
  55736. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55737. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55738. if (d < 0)
  55739. return false;
  55740. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55741. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55742. return d >= 0;
  55743. };
  55744. /** @hidden */
  55745. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55746. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55747. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55748. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55749. return false;
  55750. }
  55751. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55752. return false;
  55753. return true;
  55754. };
  55755. /** @hidden */
  55756. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55757. var t0;
  55758. var embeddedInPlane = false;
  55759. //defensive programming, actually not needed.
  55760. if (!trianglePlaneArray) {
  55761. trianglePlaneArray = [];
  55762. }
  55763. if (!trianglePlaneArray[faceIndex]) {
  55764. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55765. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55766. }
  55767. var trianglePlane = trianglePlaneArray[faceIndex];
  55768. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55769. return;
  55770. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55771. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55772. if (normalDotVelocity == 0) {
  55773. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55774. return;
  55775. embeddedInPlane = true;
  55776. t0 = 0;
  55777. }
  55778. else {
  55779. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55780. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55781. if (t0 > t1) {
  55782. var temp = t1;
  55783. t1 = t0;
  55784. t0 = temp;
  55785. }
  55786. if (t0 > 1.0 || t1 < 0.0)
  55787. return;
  55788. if (t0 < 0)
  55789. t0 = 0;
  55790. if (t0 > 1.0)
  55791. t0 = 1.0;
  55792. }
  55793. this._collisionPoint.copyFromFloats(0, 0, 0);
  55794. var found = false;
  55795. var t = 1.0;
  55796. if (!embeddedInPlane) {
  55797. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55798. this._velocity.scaleToRef(t0, this._tempVector);
  55799. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55800. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55801. found = true;
  55802. t = t0;
  55803. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55804. }
  55805. }
  55806. if (!found) {
  55807. var velocitySquaredLength = this._velocity.lengthSquared();
  55808. var a = velocitySquaredLength;
  55809. this._basePoint.subtractToRef(p1, this._tempVector);
  55810. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55811. var c = this._tempVector.lengthSquared() - 1.0;
  55812. var lowestRoot = getLowestRoot(a, b, c, t);
  55813. if (lowestRoot.found) {
  55814. t = lowestRoot.root;
  55815. found = true;
  55816. this._collisionPoint.copyFrom(p1);
  55817. }
  55818. this._basePoint.subtractToRef(p2, this._tempVector);
  55819. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55820. c = this._tempVector.lengthSquared() - 1.0;
  55821. lowestRoot = getLowestRoot(a, b, c, t);
  55822. if (lowestRoot.found) {
  55823. t = lowestRoot.root;
  55824. found = true;
  55825. this._collisionPoint.copyFrom(p2);
  55826. }
  55827. this._basePoint.subtractToRef(p3, this._tempVector);
  55828. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55829. c = this._tempVector.lengthSquared() - 1.0;
  55830. lowestRoot = getLowestRoot(a, b, c, t);
  55831. if (lowestRoot.found) {
  55832. t = lowestRoot.root;
  55833. found = true;
  55834. this._collisionPoint.copyFrom(p3);
  55835. }
  55836. p2.subtractToRef(p1, this._edge);
  55837. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55838. var edgeSquaredLength = this._edge.lengthSquared();
  55839. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55840. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55841. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55842. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55843. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55844. lowestRoot = getLowestRoot(a, b, c, t);
  55845. if (lowestRoot.found) {
  55846. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55847. if (f >= 0.0 && f <= 1.0) {
  55848. t = lowestRoot.root;
  55849. found = true;
  55850. this._edge.scaleInPlace(f);
  55851. p1.addToRef(this._edge, this._collisionPoint);
  55852. }
  55853. }
  55854. p3.subtractToRef(p2, this._edge);
  55855. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55856. edgeSquaredLength = this._edge.lengthSquared();
  55857. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55858. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55859. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55860. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55861. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55862. lowestRoot = getLowestRoot(a, b, c, t);
  55863. if (lowestRoot.found) {
  55864. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55865. if (f >= 0.0 && f <= 1.0) {
  55866. t = lowestRoot.root;
  55867. found = true;
  55868. this._edge.scaleInPlace(f);
  55869. p2.addToRef(this._edge, this._collisionPoint);
  55870. }
  55871. }
  55872. p1.subtractToRef(p3, this._edge);
  55873. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55874. edgeSquaredLength = this._edge.lengthSquared();
  55875. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55876. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55877. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55878. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55879. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55880. lowestRoot = getLowestRoot(a, b, c, t);
  55881. if (lowestRoot.found) {
  55882. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55883. if (f >= 0.0 && f <= 1.0) {
  55884. t = lowestRoot.root;
  55885. found = true;
  55886. this._edge.scaleInPlace(f);
  55887. p3.addToRef(this._edge, this._collisionPoint);
  55888. }
  55889. }
  55890. }
  55891. if (found) {
  55892. var distToCollision = t * this._velocity.length();
  55893. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55894. if (!this.intersectionPoint) {
  55895. this.intersectionPoint = this._collisionPoint.clone();
  55896. }
  55897. else {
  55898. this.intersectionPoint.copyFrom(this._collisionPoint);
  55899. }
  55900. this._nearestDistance = distToCollision;
  55901. this.collisionFound = true;
  55902. }
  55903. }
  55904. };
  55905. /** @hidden */
  55906. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55907. for (var i = indexStart; i < indexEnd; i += 3) {
  55908. var p1 = pts[indices[i] - decal];
  55909. var p2 = pts[indices[i + 1] - decal];
  55910. var p3 = pts[indices[i + 2] - decal];
  55911. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55912. }
  55913. };
  55914. /** @hidden */
  55915. Collider.prototype._getResponse = function (pos, vel) {
  55916. pos.addToRef(vel, this._destinationPoint);
  55917. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55918. this._basePoint.addToRef(vel, pos);
  55919. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55920. this._slidePlaneNormal.normalize();
  55921. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55922. pos.addInPlace(this._displacementVector);
  55923. this.intersectionPoint.addInPlace(this._displacementVector);
  55924. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55925. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55926. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55927. };
  55928. return Collider;
  55929. }());
  55930. BABYLON.Collider = Collider;
  55931. })(BABYLON || (BABYLON = {}));
  55932. //# sourceMappingURL=babylon.collider.js.map
  55933. var BABYLON;
  55934. (function (BABYLON) {
  55935. //WebWorker code will be inserted to this variable.
  55936. /** @hidden */
  55937. BABYLON.CollisionWorker = "";
  55938. /** Defines supported task for worker process */
  55939. var WorkerTaskType;
  55940. (function (WorkerTaskType) {
  55941. /** Initialization */
  55942. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55943. /** Update of geometry */
  55944. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55945. /** Evaluate collision */
  55946. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55947. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55948. /** Defines kind of replies returned by worker */
  55949. var WorkerReplyType;
  55950. (function (WorkerReplyType) {
  55951. /** Success */
  55952. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55953. /** Unkown error */
  55954. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55955. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55956. /** @hidden */
  55957. var CollisionCoordinatorWorker = /** @class */ (function () {
  55958. function CollisionCoordinatorWorker() {
  55959. var _this = this;
  55960. this._scaledPosition = BABYLON.Vector3.Zero();
  55961. this._scaledVelocity = BABYLON.Vector3.Zero();
  55962. this.onMeshUpdated = function (transformNode) {
  55963. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55964. };
  55965. this.onGeometryUpdated = function (geometry) {
  55966. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55967. };
  55968. this._afterRender = function () {
  55969. if (!_this._init)
  55970. return;
  55971. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55972. return;
  55973. }
  55974. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55975. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55976. if (_this._runningUpdated > 4) {
  55977. return;
  55978. }
  55979. ++_this._runningUpdated;
  55980. var payload = {
  55981. updatedMeshes: _this._addUpdateMeshesList,
  55982. updatedGeometries: _this._addUpdateGeometriesList,
  55983. removedGeometries: _this._toRemoveGeometryArray,
  55984. removedMeshes: _this._toRemoveMeshesArray
  55985. };
  55986. var message = {
  55987. payload: payload,
  55988. taskType: WorkerTaskType.UPDATE
  55989. };
  55990. var serializable = [];
  55991. for (var id in payload.updatedGeometries) {
  55992. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55993. //prepare transferables
  55994. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55995. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55996. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55997. }
  55998. }
  55999. _this._worker.postMessage(message, serializable);
  56000. _this._addUpdateMeshesList = {};
  56001. _this._addUpdateGeometriesList = {};
  56002. _this._toRemoveGeometryArray = [];
  56003. _this._toRemoveMeshesArray = [];
  56004. };
  56005. this._onMessageFromWorker = function (e) {
  56006. var returnData = e.data;
  56007. if (returnData.error != WorkerReplyType.SUCCESS) {
  56008. //TODO what errors can be returned from the worker?
  56009. BABYLON.Tools.Warn("error returned from worker!");
  56010. return;
  56011. }
  56012. switch (returnData.taskType) {
  56013. case WorkerTaskType.INIT:
  56014. _this._init = true;
  56015. //Update the worked with ALL of the scene's current state
  56016. _this._scene.meshes.forEach(function (mesh) {
  56017. _this.onMeshAdded(mesh);
  56018. });
  56019. _this._scene.getGeometries().forEach(function (geometry) {
  56020. _this.onGeometryAdded(geometry);
  56021. });
  56022. break;
  56023. case WorkerTaskType.UPDATE:
  56024. _this._runningUpdated--;
  56025. break;
  56026. case WorkerTaskType.COLLIDE:
  56027. var returnPayload = returnData.payload;
  56028. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  56029. return;
  56030. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  56031. if (callback) {
  56032. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  56033. if (mesh) {
  56034. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  56035. }
  56036. }
  56037. //cleanup
  56038. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  56039. break;
  56040. }
  56041. };
  56042. this._collisionsCallbackArray = [];
  56043. this._init = false;
  56044. this._runningUpdated = 0;
  56045. this._addUpdateMeshesList = {};
  56046. this._addUpdateGeometriesList = {};
  56047. this._toRemoveGeometryArray = [];
  56048. this._toRemoveMeshesArray = [];
  56049. }
  56050. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56051. if (!this._init)
  56052. return;
  56053. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  56054. return;
  56055. position.divideToRef(collider._radius, this._scaledPosition);
  56056. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56057. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  56058. var payload = {
  56059. collider: {
  56060. position: this._scaledPosition.asArray(),
  56061. velocity: this._scaledVelocity.asArray(),
  56062. radius: collider._radius.asArray()
  56063. },
  56064. collisionId: collisionIndex,
  56065. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  56066. maximumRetry: maximumRetry
  56067. };
  56068. var message = {
  56069. payload: payload,
  56070. taskType: WorkerTaskType.COLLIDE
  56071. };
  56072. this._worker.postMessage(message);
  56073. };
  56074. CollisionCoordinatorWorker.prototype.init = function (scene) {
  56075. this._scene = scene;
  56076. this._scene.registerAfterRender(this._afterRender);
  56077. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  56078. this._worker = new Worker(workerUrl);
  56079. this._worker.onmessage = this._onMessageFromWorker;
  56080. var message = {
  56081. payload: {},
  56082. taskType: WorkerTaskType.INIT
  56083. };
  56084. this._worker.postMessage(message);
  56085. };
  56086. CollisionCoordinatorWorker.prototype.destroy = function () {
  56087. this._scene.unregisterAfterRender(this._afterRender);
  56088. this._worker.terminate();
  56089. };
  56090. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  56091. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  56092. this.onMeshUpdated(mesh);
  56093. };
  56094. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  56095. this._toRemoveMeshesArray.push(mesh.uniqueId);
  56096. };
  56097. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  56098. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  56099. geometry.onGeometryUpdated = this.onGeometryUpdated;
  56100. this.onGeometryUpdated(geometry);
  56101. };
  56102. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  56103. this._toRemoveGeometryArray.push(geometry.id);
  56104. };
  56105. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  56106. var submeshes = [];
  56107. if (mesh.subMeshes) {
  56108. submeshes = mesh.subMeshes.map(function (sm, idx) {
  56109. var boundingInfo = sm.getBoundingInfo();
  56110. return {
  56111. position: idx,
  56112. verticesStart: sm.verticesStart,
  56113. verticesCount: sm.verticesCount,
  56114. indexStart: sm.indexStart,
  56115. indexCount: sm.indexCount,
  56116. hasMaterial: !!sm.getMaterial(),
  56117. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56118. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56119. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56120. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  56121. };
  56122. });
  56123. }
  56124. var geometryId = null;
  56125. if (mesh instanceof BABYLON.Mesh) {
  56126. var geometry = mesh.geometry;
  56127. geometryId = geometry ? geometry.id : null;
  56128. }
  56129. else if (mesh instanceof BABYLON.InstancedMesh) {
  56130. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  56131. geometryId = geometry ? geometry.id : null;
  56132. }
  56133. var boundingInfo = mesh.getBoundingInfo();
  56134. return {
  56135. uniqueId: mesh.uniqueId,
  56136. id: mesh.id,
  56137. name: mesh.name,
  56138. geometryId: geometryId,
  56139. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  56140. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  56141. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  56142. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  56143. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  56144. subMeshes: submeshes,
  56145. checkCollisions: mesh.checkCollisions
  56146. };
  56147. };
  56148. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  56149. return {
  56150. id: geometry.id,
  56151. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  56152. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  56153. indices: new Uint32Array(geometry.getIndices() || []),
  56154. };
  56155. };
  56156. return CollisionCoordinatorWorker;
  56157. }());
  56158. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  56159. /** @hidden */
  56160. var CollisionCoordinatorLegacy = /** @class */ (function () {
  56161. function CollisionCoordinatorLegacy() {
  56162. this._scaledPosition = BABYLON.Vector3.Zero();
  56163. this._scaledVelocity = BABYLON.Vector3.Zero();
  56164. this._finalPosition = BABYLON.Vector3.Zero();
  56165. }
  56166. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  56167. position.divideToRef(collider._radius, this._scaledPosition);
  56168. displacement.divideToRef(collider._radius, this._scaledVelocity);
  56169. collider.collidedMesh = null;
  56170. collider._retry = 0;
  56171. collider._initialVelocity = this._scaledVelocity;
  56172. collider._initialPosition = this._scaledPosition;
  56173. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  56174. this._finalPosition.multiplyInPlace(collider._radius);
  56175. //run the callback
  56176. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  56177. };
  56178. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  56179. this._scene = scene;
  56180. };
  56181. CollisionCoordinatorLegacy.prototype.destroy = function () {
  56182. //Legacy need no destruction method.
  56183. };
  56184. //No update in legacy mode
  56185. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  56186. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  56187. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  56188. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  56189. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  56190. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  56191. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  56192. if (excludedMesh === void 0) { excludedMesh = null; }
  56193. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  56194. if (collider._retry >= maximumRetry) {
  56195. finalPosition.copyFrom(position);
  56196. return;
  56197. }
  56198. // Check if this is a mesh else camera or -1
  56199. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  56200. collider._initialize(position, velocity, closeDistance);
  56201. // Check all meshes
  56202. for (var index = 0; index < this._scene.meshes.length; index++) {
  56203. var mesh = this._scene.meshes[index];
  56204. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  56205. mesh._checkCollision(collider);
  56206. }
  56207. }
  56208. if (!collider.collisionFound) {
  56209. position.addToRef(velocity, finalPosition);
  56210. return;
  56211. }
  56212. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  56213. collider._getResponse(position, velocity);
  56214. }
  56215. if (velocity.length() <= closeDistance) {
  56216. finalPosition.copyFrom(position);
  56217. return;
  56218. }
  56219. collider._retry++;
  56220. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  56221. };
  56222. return CollisionCoordinatorLegacy;
  56223. }());
  56224. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  56225. })(BABYLON || (BABYLON = {}));
  56226. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  56227. var BABYLON;
  56228. (function (BABYLON) {
  56229. /**
  56230. * A particle represents one of the element emitted by a particle system.
  56231. * This is mainly define by its coordinates, direction, velocity and age.
  56232. */
  56233. var Particle = /** @class */ (function () {
  56234. /**
  56235. * Creates a new instance Particle
  56236. * @param particleSystem the particle system the particle belongs to
  56237. */
  56238. function Particle(
  56239. /**
  56240. * The particle system the particle belongs to.
  56241. */
  56242. particleSystem) {
  56243. this.particleSystem = particleSystem;
  56244. /**
  56245. * The world position of the particle in the scene.
  56246. */
  56247. this.position = BABYLON.Vector3.Zero();
  56248. /**
  56249. * The world direction of the particle in the scene.
  56250. */
  56251. this.direction = BABYLON.Vector3.Zero();
  56252. /**
  56253. * The color of the particle.
  56254. */
  56255. this.color = new BABYLON.Color4(0, 0, 0, 0);
  56256. /**
  56257. * The color change of the particle per step.
  56258. */
  56259. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  56260. /**
  56261. * Defines how long will the life of the particle be.
  56262. */
  56263. this.lifeTime = 1.0;
  56264. /**
  56265. * The current age of the particle.
  56266. */
  56267. this.age = 0;
  56268. /**
  56269. * The current size of the particle.
  56270. */
  56271. this.size = 0;
  56272. /**
  56273. * The current scale of the particle.
  56274. */
  56275. this.scale = new BABYLON.Vector2(1, 1);
  56276. /**
  56277. * The current angle of the particle.
  56278. */
  56279. this.angle = 0;
  56280. /**
  56281. * Defines how fast is the angle changing.
  56282. */
  56283. this.angularSpeed = 0;
  56284. /**
  56285. * Defines the cell index used by the particle to be rendered from a sprite.
  56286. */
  56287. this.cellIndex = 0;
  56288. /** @hidden */
  56289. this._attachedSubEmitters = null;
  56290. /** @hidden */
  56291. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  56292. /** @hidden */
  56293. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  56294. /** @hidden */
  56295. this._currentSize1 = 0;
  56296. /** @hidden */
  56297. this._currentSize2 = 0;
  56298. /** @hidden */
  56299. this._currentAngularSpeed1 = 0;
  56300. /** @hidden */
  56301. this._currentAngularSpeed2 = 0;
  56302. /** @hidden */
  56303. this._currentVelocity1 = 0;
  56304. /** @hidden */
  56305. this._currentVelocity2 = 0;
  56306. /** @hidden */
  56307. this._currentLimitVelocity1 = 0;
  56308. /** @hidden */
  56309. this._currentLimitVelocity2 = 0;
  56310. /** @hidden */
  56311. this._currentDrag1 = 0;
  56312. /** @hidden */
  56313. this._currentDrag2 = 0;
  56314. this.id = Particle._Count++;
  56315. if (!this.particleSystem.isAnimationSheetEnabled) {
  56316. return;
  56317. }
  56318. this.updateCellInfoFromSystem();
  56319. }
  56320. Particle.prototype.updateCellInfoFromSystem = function () {
  56321. this.cellIndex = this.particleSystem.startSpriteCellID;
  56322. };
  56323. /**
  56324. * Defines how the sprite cell index is updated for the particle
  56325. */
  56326. Particle.prototype.updateCellIndex = function () {
  56327. var offsetAge = this.age;
  56328. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  56329. if (this.particleSystem.spriteRandomStartCell) {
  56330. if (this._randomCellOffset === undefined) {
  56331. this._randomCellOffset = Math.random() * this.lifeTime;
  56332. }
  56333. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  56334. changeSpeed = 1;
  56335. offsetAge = this._randomCellOffset;
  56336. }
  56337. else {
  56338. offsetAge += this._randomCellOffset;
  56339. }
  56340. }
  56341. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  56342. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  56343. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  56344. };
  56345. /** @hidden */
  56346. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  56347. if (subEmitter.particleSystem.emitter.position) {
  56348. var emitterMesh = subEmitter.particleSystem.emitter;
  56349. emitterMesh.position.copyFrom(this.position);
  56350. if (subEmitter.inheritDirection) {
  56351. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  56352. // Look at using Y as forward
  56353. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  56354. }
  56355. }
  56356. else {
  56357. var emitterPosition = subEmitter.particleSystem.emitter;
  56358. emitterPosition.copyFrom(this.position);
  56359. }
  56360. // Set inheritedVelocityOffset to be used when new particles are created
  56361. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  56362. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  56363. };
  56364. /** @hidden */
  56365. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  56366. var _this = this;
  56367. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  56368. this._attachedSubEmitters.forEach(function (subEmitter) {
  56369. _this._inheritParticleInfoToSubEmitter(subEmitter);
  56370. });
  56371. }
  56372. };
  56373. /** @hidden */
  56374. Particle.prototype._reset = function () {
  56375. this.age = 0;
  56376. this._currentColorGradient = null;
  56377. this._currentSizeGradient = null;
  56378. this._currentAngularSpeedGradient = null;
  56379. this._currentVelocityGradient = null;
  56380. this._currentLimitVelocityGradient = null;
  56381. this._currentDragGradient = null;
  56382. this.cellIndex = this.particleSystem.startSpriteCellID;
  56383. this._randomCellOffset = undefined;
  56384. };
  56385. /**
  56386. * Copy the properties of particle to another one.
  56387. * @param other the particle to copy the information to.
  56388. */
  56389. Particle.prototype.copyTo = function (other) {
  56390. other.position.copyFrom(this.position);
  56391. if (this._initialDirection) {
  56392. if (other._initialDirection) {
  56393. other._initialDirection.copyFrom(this._initialDirection);
  56394. }
  56395. else {
  56396. other._initialDirection = this._initialDirection.clone();
  56397. }
  56398. }
  56399. else {
  56400. other._initialDirection = null;
  56401. }
  56402. other.direction.copyFrom(this.direction);
  56403. other.color.copyFrom(this.color);
  56404. other.colorStep.copyFrom(this.colorStep);
  56405. other.lifeTime = this.lifeTime;
  56406. other.age = this.age;
  56407. other._randomCellOffset = this._randomCellOffset;
  56408. other.size = this.size;
  56409. other.scale.copyFrom(this.scale);
  56410. other.angle = this.angle;
  56411. other.angularSpeed = this.angularSpeed;
  56412. other.particleSystem = this.particleSystem;
  56413. other.cellIndex = this.cellIndex;
  56414. other.id = this.id;
  56415. other._attachedSubEmitters = this._attachedSubEmitters;
  56416. if (this._currentColorGradient) {
  56417. other._currentColorGradient = this._currentColorGradient;
  56418. other._currentColor1.copyFrom(this._currentColor1);
  56419. other._currentColor2.copyFrom(this._currentColor2);
  56420. }
  56421. if (this._currentSizeGradient) {
  56422. other._currentSizeGradient = this._currentSizeGradient;
  56423. other._currentSize1 = this._currentSize1;
  56424. other._currentSize2 = this._currentSize2;
  56425. }
  56426. if (this._currentAngularSpeedGradient) {
  56427. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  56428. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  56429. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  56430. }
  56431. if (this._currentVelocityGradient) {
  56432. other._currentVelocityGradient = this._currentVelocityGradient;
  56433. other._currentVelocity1 = this._currentVelocity1;
  56434. other._currentVelocity2 = this._currentVelocity2;
  56435. }
  56436. if (this._currentLimitVelocityGradient) {
  56437. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  56438. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  56439. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  56440. }
  56441. if (this._currentDragGradient) {
  56442. other._currentDragGradient = this._currentDragGradient;
  56443. other._currentDrag1 = this._currentDrag1;
  56444. other._currentDrag2 = this._currentDrag2;
  56445. }
  56446. if (this.particleSystem.isAnimationSheetEnabled) {
  56447. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  56448. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  56449. }
  56450. if (this.particleSystem.useRampGradients) {
  56451. other.remapData.copyFrom(this.remapData);
  56452. }
  56453. if (this._randomNoiseCoordinates1) {
  56454. if (other._randomNoiseCoordinates1) {
  56455. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  56456. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  56457. }
  56458. else {
  56459. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  56460. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  56461. }
  56462. }
  56463. };
  56464. Particle._Count = 0;
  56465. return Particle;
  56466. }());
  56467. BABYLON.Particle = Particle;
  56468. })(BABYLON || (BABYLON = {}));
  56469. //# sourceMappingURL=babylon.particle.js.map
  56470. var BABYLON;
  56471. (function (BABYLON) {
  56472. /**
  56473. * This represents the base class for particle system in Babylon.
  56474. * 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.
  56475. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56476. * @example https://doc.babylonjs.com/babylon101/particles
  56477. */
  56478. var BaseParticleSystem = /** @class */ (function () {
  56479. /**
  56480. * Instantiates a particle system.
  56481. * 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.
  56482. * @param name The name of the particle system
  56483. */
  56484. function BaseParticleSystem(name) {
  56485. /**
  56486. * List of animations used by the particle system.
  56487. */
  56488. this.animations = [];
  56489. /**
  56490. * The rendering group used by the Particle system to chose when to render.
  56491. */
  56492. this.renderingGroupId = 0;
  56493. /**
  56494. * The emitter represents the Mesh or position we are attaching the particle system to.
  56495. */
  56496. this.emitter = null;
  56497. /**
  56498. * The maximum number of particles to emit per frame
  56499. */
  56500. this.emitRate = 10;
  56501. /**
  56502. * If you want to launch only a few particles at once, that can be done, as well.
  56503. */
  56504. this.manualEmitCount = -1;
  56505. /**
  56506. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56507. */
  56508. this.updateSpeed = 0.01;
  56509. /**
  56510. * The amount of time the particle system is running (depends of the overall update speed).
  56511. */
  56512. this.targetStopDuration = 0;
  56513. /**
  56514. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  56515. */
  56516. this.disposeOnStop = false;
  56517. /**
  56518. * Minimum power of emitting particles.
  56519. */
  56520. this.minEmitPower = 1;
  56521. /**
  56522. * Maximum power of emitting particles.
  56523. */
  56524. this.maxEmitPower = 1;
  56525. /**
  56526. * Minimum life time of emitting particles.
  56527. */
  56528. this.minLifeTime = 1;
  56529. /**
  56530. * Maximum life time of emitting particles.
  56531. */
  56532. this.maxLifeTime = 1;
  56533. /**
  56534. * Minimum Size of emitting particles.
  56535. */
  56536. this.minSize = 1;
  56537. /**
  56538. * Maximum Size of emitting particles.
  56539. */
  56540. this.maxSize = 1;
  56541. /**
  56542. * Minimum scale of emitting particles on X axis.
  56543. */
  56544. this.minScaleX = 1;
  56545. /**
  56546. * Maximum scale of emitting particles on X axis.
  56547. */
  56548. this.maxScaleX = 1;
  56549. /**
  56550. * Minimum scale of emitting particles on Y axis.
  56551. */
  56552. this.minScaleY = 1;
  56553. /**
  56554. * Maximum scale of emitting particles on Y axis.
  56555. */
  56556. this.maxScaleY = 1;
  56557. /**
  56558. * Gets or sets the minimal initial rotation in radians.
  56559. */
  56560. this.minInitialRotation = 0;
  56561. /**
  56562. * Gets or sets the maximal initial rotation in radians.
  56563. */
  56564. this.maxInitialRotation = 0;
  56565. /**
  56566. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56567. */
  56568. this.minAngularSpeed = 0;
  56569. /**
  56570. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56571. */
  56572. this.maxAngularSpeed = 0;
  56573. /**
  56574. * The layer mask we are rendering the particles through.
  56575. */
  56576. this.layerMask = 0x0FFFFFFF;
  56577. /**
  56578. * This can help using your own shader to render the particle system.
  56579. * The according effect will be created
  56580. */
  56581. this.customShader = null;
  56582. /**
  56583. * By default particle system starts as soon as they are created. This prevents the
  56584. * automatic start to happen and let you decide when to start emitting particles.
  56585. */
  56586. this.preventAutoStart = false;
  56587. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  56588. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  56589. /**
  56590. * Callback triggered when the particle animation is ending.
  56591. */
  56592. this.onAnimationEnd = null;
  56593. /**
  56594. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56595. */
  56596. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56597. /**
  56598. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56599. * to override the particles.
  56600. */
  56601. this.forceDepthWrite = false;
  56602. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  56603. this.preWarmCycles = 0;
  56604. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56605. this.preWarmStepOffset = 1;
  56606. /**
  56607. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  56608. */
  56609. this.spriteCellChangeSpeed = 1;
  56610. /**
  56611. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  56612. */
  56613. this.startSpriteCellID = 0;
  56614. /**
  56615. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  56616. */
  56617. this.endSpriteCellID = 0;
  56618. /**
  56619. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  56620. */
  56621. this.spriteCellWidth = 0;
  56622. /**
  56623. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  56624. */
  56625. this.spriteCellHeight = 0;
  56626. /**
  56627. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  56628. */
  56629. this.spriteRandomStartCell = false;
  56630. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  56631. this.translationPivot = new BABYLON.Vector2(0, 0);
  56632. /**
  56633. * You can use gravity if you want to give an orientation to your particles.
  56634. */
  56635. this.gravity = BABYLON.Vector3.Zero();
  56636. this._colorGradients = null;
  56637. this._sizeGradients = null;
  56638. this._lifeTimeGradients = null;
  56639. this._angularSpeedGradients = null;
  56640. this._velocityGradients = null;
  56641. this._limitVelocityGradients = null;
  56642. this._dragGradients = null;
  56643. this._emitRateGradients = null;
  56644. this._startSizeGradients = null;
  56645. this._rampGradients = null;
  56646. this._colorRemapGradients = null;
  56647. this._alphaRemapGradients = null;
  56648. /**
  56649. * Defines the delay in milliseconds before starting the system (0 by default)
  56650. */
  56651. this.startDelay = 0;
  56652. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  56653. this.limitVelocityDamping = 0.4;
  56654. /**
  56655. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56656. */
  56657. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56658. /**
  56659. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  56660. */
  56661. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56662. /**
  56663. * Color the particle will have at the end of its lifetime
  56664. */
  56665. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  56666. /**
  56667. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  56668. */
  56669. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56670. /**
  56671. * Gets or sets the billboard mode to use when isBillboardBased = true.
  56672. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  56673. */
  56674. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  56675. this._isBillboardBased = true;
  56676. /**
  56677. * Local cache of defines for image processing.
  56678. */
  56679. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  56680. this.id = name;
  56681. this.name = name;
  56682. }
  56683. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  56684. /**
  56685. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  56686. */
  56687. get: function () {
  56688. return this._isAnimationSheetEnabled;
  56689. },
  56690. set: function (value) {
  56691. if (this._isAnimationSheetEnabled == value) {
  56692. return;
  56693. }
  56694. this._isAnimationSheetEnabled = value;
  56695. this._reset();
  56696. },
  56697. enumerable: true,
  56698. configurable: true
  56699. });
  56700. /**
  56701. * Get hosting scene
  56702. * @returns the scene
  56703. */
  56704. BaseParticleSystem.prototype.getScene = function () {
  56705. return this._scene;
  56706. };
  56707. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  56708. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  56709. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  56710. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  56711. };
  56712. /**
  56713. * Gets the current list of drag gradients.
  56714. * You must use addDragGradient and removeDragGradient to udpate this list
  56715. * @returns the list of drag gradients
  56716. */
  56717. BaseParticleSystem.prototype.getDragGradients = function () {
  56718. return this._dragGradients;
  56719. };
  56720. /**
  56721. * Gets the current list of limit velocity gradients.
  56722. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  56723. * @returns the list of limit velocity gradients
  56724. */
  56725. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  56726. return this._limitVelocityGradients;
  56727. };
  56728. /**
  56729. * Gets the current list of color gradients.
  56730. * You must use addColorGradient and removeColorGradient to udpate this list
  56731. * @returns the list of color gradients
  56732. */
  56733. BaseParticleSystem.prototype.getColorGradients = function () {
  56734. return this._colorGradients;
  56735. };
  56736. /**
  56737. * Gets the current list of size gradients.
  56738. * You must use addSizeGradient and removeSizeGradient to udpate this list
  56739. * @returns the list of size gradients
  56740. */
  56741. BaseParticleSystem.prototype.getSizeGradients = function () {
  56742. return this._sizeGradients;
  56743. };
  56744. /**
  56745. * Gets the current list of color remap gradients.
  56746. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  56747. * @returns the list of color remap gradients
  56748. */
  56749. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  56750. return this._colorRemapGradients;
  56751. };
  56752. /**
  56753. * Gets the current list of alpha remap gradients.
  56754. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  56755. * @returns the list of alpha remap gradients
  56756. */
  56757. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  56758. return this._alphaRemapGradients;
  56759. };
  56760. /**
  56761. * Gets the current list of life time gradients.
  56762. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  56763. * @returns the list of life time gradients
  56764. */
  56765. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  56766. return this._lifeTimeGradients;
  56767. };
  56768. /**
  56769. * Gets the current list of angular speed gradients.
  56770. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  56771. * @returns the list of angular speed gradients
  56772. */
  56773. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  56774. return this._angularSpeedGradients;
  56775. };
  56776. /**
  56777. * Gets the current list of velocity gradients.
  56778. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  56779. * @returns the list of velocity gradients
  56780. */
  56781. BaseParticleSystem.prototype.getVelocityGradients = function () {
  56782. return this._velocityGradients;
  56783. };
  56784. /**
  56785. * Gets the current list of start size gradients.
  56786. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  56787. * @returns the list of start size gradients
  56788. */
  56789. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  56790. return this._startSizeGradients;
  56791. };
  56792. /**
  56793. * Gets the current list of emit rate gradients.
  56794. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  56795. * @returns the list of emit rate gradients
  56796. */
  56797. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  56798. return this._emitRateGradients;
  56799. };
  56800. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  56801. /**
  56802. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56803. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56804. */
  56805. get: function () {
  56806. if (this.particleEmitterType.direction1) {
  56807. return this.particleEmitterType.direction1;
  56808. }
  56809. return BABYLON.Vector3.Zero();
  56810. },
  56811. set: function (value) {
  56812. if (this.particleEmitterType.direction1) {
  56813. this.particleEmitterType.direction1 = value;
  56814. }
  56815. },
  56816. enumerable: true,
  56817. configurable: true
  56818. });
  56819. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  56820. /**
  56821. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56822. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56823. */
  56824. get: function () {
  56825. if (this.particleEmitterType.direction2) {
  56826. return this.particleEmitterType.direction2;
  56827. }
  56828. return BABYLON.Vector3.Zero();
  56829. },
  56830. set: function (value) {
  56831. if (this.particleEmitterType.direction2) {
  56832. this.particleEmitterType.direction2 = value;
  56833. }
  56834. },
  56835. enumerable: true,
  56836. configurable: true
  56837. });
  56838. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  56839. /**
  56840. * 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.
  56841. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56842. */
  56843. get: function () {
  56844. if (this.particleEmitterType.minEmitBox) {
  56845. return this.particleEmitterType.minEmitBox;
  56846. }
  56847. return BABYLON.Vector3.Zero();
  56848. },
  56849. set: function (value) {
  56850. if (this.particleEmitterType.minEmitBox) {
  56851. this.particleEmitterType.minEmitBox = value;
  56852. }
  56853. },
  56854. enumerable: true,
  56855. configurable: true
  56856. });
  56857. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  56858. /**
  56859. * 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.
  56860. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56861. */
  56862. get: function () {
  56863. if (this.particleEmitterType.maxEmitBox) {
  56864. return this.particleEmitterType.maxEmitBox;
  56865. }
  56866. return BABYLON.Vector3.Zero();
  56867. },
  56868. set: function (value) {
  56869. if (this.particleEmitterType.maxEmitBox) {
  56870. this.particleEmitterType.maxEmitBox = value;
  56871. }
  56872. },
  56873. enumerable: true,
  56874. configurable: true
  56875. });
  56876. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  56877. /**
  56878. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  56879. */
  56880. get: function () {
  56881. return this._isBillboardBased;
  56882. },
  56883. set: function (value) {
  56884. if (this._isBillboardBased === value) {
  56885. return;
  56886. }
  56887. this._isBillboardBased = value;
  56888. this._reset();
  56889. },
  56890. enumerable: true,
  56891. configurable: true
  56892. });
  56893. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  56894. /**
  56895. * Gets the image processing configuration used either in this material.
  56896. */
  56897. get: function () {
  56898. return this._imageProcessingConfiguration;
  56899. },
  56900. /**
  56901. * Sets the Default image processing configuration used either in the this material.
  56902. *
  56903. * If sets to null, the scene one is in use.
  56904. */
  56905. set: function (value) {
  56906. this._attachImageProcessingConfiguration(value);
  56907. },
  56908. enumerable: true,
  56909. configurable: true
  56910. });
  56911. /**
  56912. * Attaches a new image processing configuration to the Standard Material.
  56913. * @param configuration
  56914. */
  56915. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  56916. if (configuration === this._imageProcessingConfiguration) {
  56917. return;
  56918. }
  56919. // Pick the scene configuration if needed.
  56920. if (!configuration) {
  56921. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  56922. }
  56923. else {
  56924. this._imageProcessingConfiguration = configuration;
  56925. }
  56926. };
  56927. /** @hidden */
  56928. BaseParticleSystem.prototype._reset = function () {
  56929. };
  56930. /** @hidden */
  56931. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  56932. if (!gradients) {
  56933. return this;
  56934. }
  56935. var index = 0;
  56936. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  56937. var valueGradient = gradients_1[_i];
  56938. if (valueGradient.gradient === gradient) {
  56939. gradients.splice(index, 1);
  56940. break;
  56941. }
  56942. index++;
  56943. }
  56944. if (texture) {
  56945. texture.dispose();
  56946. }
  56947. return this;
  56948. };
  56949. /**
  56950. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  56951. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56952. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56953. * @returns the emitter
  56954. */
  56955. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  56956. var particleEmitter = new BABYLON.PointParticleEmitter();
  56957. particleEmitter.direction1 = direction1;
  56958. particleEmitter.direction2 = direction2;
  56959. this.particleEmitterType = particleEmitter;
  56960. return particleEmitter;
  56961. };
  56962. /**
  56963. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  56964. * @param radius The radius of the hemisphere to emit from
  56965. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56966. * @returns the emitter
  56967. */
  56968. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56969. if (radius === void 0) { radius = 1; }
  56970. if (radiusRange === void 0) { radiusRange = 1; }
  56971. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56972. this.particleEmitterType = particleEmitter;
  56973. return particleEmitter;
  56974. };
  56975. /**
  56976. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56977. * @param radius The radius of the sphere to emit from
  56978. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56979. * @returns the emitter
  56980. */
  56981. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56982. if (radius === void 0) { radius = 1; }
  56983. if (radiusRange === void 0) { radiusRange = 1; }
  56984. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56985. this.particleEmitterType = particleEmitter;
  56986. return particleEmitter;
  56987. };
  56988. /**
  56989. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56990. * @param radius The radius of the sphere to emit from
  56991. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56992. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56993. * @returns the emitter
  56994. */
  56995. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56996. if (radius === void 0) { radius = 1; }
  56997. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56998. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56999. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  57000. this.particleEmitterType = particleEmitter;
  57001. return particleEmitter;
  57002. };
  57003. /**
  57004. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  57005. * @param radius The radius of the emission cylinder
  57006. * @param height The height of the emission cylinder
  57007. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  57008. * @param directionRandomizer How much to randomize the particle direction [0-1]
  57009. * @returns the emitter
  57010. */
  57011. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  57012. if (radius === void 0) { radius = 1; }
  57013. if (height === void 0) { height = 1; }
  57014. if (radiusRange === void 0) { radiusRange = 1; }
  57015. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57016. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  57017. this.particleEmitterType = particleEmitter;
  57018. return particleEmitter;
  57019. };
  57020. /**
  57021. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  57022. * @param radius The radius of the cylinder to emit from
  57023. * @param height The height of the emission cylinder
  57024. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57025. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  57026. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  57027. * @returns the emitter
  57028. */
  57029. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  57030. if (radius === void 0) { radius = 1; }
  57031. if (height === void 0) { height = 1; }
  57032. if (radiusRange === void 0) { radiusRange = 1; }
  57033. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  57034. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  57035. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  57036. this.particleEmitterType = particleEmitter;
  57037. return particleEmitter;
  57038. };
  57039. /**
  57040. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  57041. * @param radius The radius of the cone to emit from
  57042. * @param angle The base angle of the cone
  57043. * @returns the emitter
  57044. */
  57045. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  57046. if (radius === void 0) { radius = 1; }
  57047. if (angle === void 0) { angle = Math.PI / 4; }
  57048. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  57049. this.particleEmitterType = particleEmitter;
  57050. return particleEmitter;
  57051. };
  57052. /**
  57053. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  57054. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  57055. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  57056. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57057. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  57058. * @returns the emitter
  57059. */
  57060. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  57061. var particleEmitter = new BABYLON.BoxParticleEmitter();
  57062. this.particleEmitterType = particleEmitter;
  57063. this.direction1 = direction1;
  57064. this.direction2 = direction2;
  57065. this.minEmitBox = minEmitBox;
  57066. this.maxEmitBox = maxEmitBox;
  57067. return particleEmitter;
  57068. };
  57069. /**
  57070. * Source color is added to the destination color without alpha affecting the result
  57071. */
  57072. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  57073. /**
  57074. * Blend current color and particle color using particle’s alpha
  57075. */
  57076. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  57077. /**
  57078. * Add current color and particle color multiplied by particle’s alpha
  57079. */
  57080. BaseParticleSystem.BLENDMODE_ADD = 2;
  57081. /**
  57082. * Multiply current color with particle color
  57083. */
  57084. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  57085. /**
  57086. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  57087. */
  57088. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  57089. return BaseParticleSystem;
  57090. }());
  57091. BABYLON.BaseParticleSystem = BaseParticleSystem;
  57092. })(BABYLON || (BABYLON = {}));
  57093. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  57094. var BABYLON;
  57095. (function (BABYLON) {
  57096. /**
  57097. * This represents a particle system in Babylon.
  57098. * 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.
  57099. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  57100. * @example https://doc.babylonjs.com/babylon101/particles
  57101. */
  57102. var ParticleSystem = /** @class */ (function (_super) {
  57103. __extends(ParticleSystem, _super);
  57104. /**
  57105. * Instantiates a particle system.
  57106. * 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.
  57107. * @param name The name of the particle system
  57108. * @param capacity The max number of particles alive at the same time
  57109. * @param scene The scene the particle system belongs to
  57110. * @param customEffect a custom effect used to change the way particles are rendered by default
  57111. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57112. * @param epsilon Offset used to render the particles
  57113. */
  57114. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  57115. if (customEffect === void 0) { customEffect = null; }
  57116. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57117. if (epsilon === void 0) { epsilon = 0.01; }
  57118. var _this = _super.call(this, name) || this;
  57119. /**
  57120. * @hidden
  57121. */
  57122. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  57123. /**
  57124. * An event triggered when the system is disposed
  57125. */
  57126. _this.onDisposeObservable = new BABYLON.Observable();
  57127. _this._particles = new Array();
  57128. _this._stockParticles = new Array();
  57129. _this._newPartsExcess = 0;
  57130. _this._vertexBuffers = {};
  57131. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  57132. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  57133. _this._scaledDirection = BABYLON.Vector3.Zero();
  57134. _this._scaledGravity = BABYLON.Vector3.Zero();
  57135. _this._currentRenderId = -1;
  57136. _this._useInstancing = false;
  57137. _this._started = false;
  57138. _this._stopped = false;
  57139. _this._actualFrame = 0;
  57140. /** @hidden */
  57141. _this._currentEmitRate1 = 0;
  57142. /** @hidden */
  57143. _this._currentEmitRate2 = 0;
  57144. /** @hidden */
  57145. _this._currentStartSize1 = 0;
  57146. /** @hidden */
  57147. _this._currentStartSize2 = 0;
  57148. _this._rawTextureWidth = 256;
  57149. _this._useRampGradients = false;
  57150. /**
  57151. * @hidden
  57152. * If the particle systems emitter should be disposed when the particle system is disposed
  57153. */
  57154. _this._disposeEmitterOnDispose = false;
  57155. // start of sub system methods
  57156. /**
  57157. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  57158. * Its lifetime will start back at 0.
  57159. */
  57160. _this.recycleParticle = function (particle) {
  57161. // move particle from activeParticle list to stock particles
  57162. var lastParticle = _this._particles.pop();
  57163. if (lastParticle !== particle) {
  57164. lastParticle.copyTo(particle);
  57165. }
  57166. _this._stockParticles.push(lastParticle);
  57167. };
  57168. _this._createParticle = function () {
  57169. var particle;
  57170. if (_this._stockParticles.length !== 0) {
  57171. particle = _this._stockParticles.pop();
  57172. particle._reset();
  57173. }
  57174. else {
  57175. particle = new BABYLON.Particle(_this);
  57176. }
  57177. // Attach emitters
  57178. if (_this._subEmitters && _this._subEmitters.length > 0) {
  57179. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  57180. particle._attachedSubEmitters = [];
  57181. subEmitters.forEach(function (subEmitter) {
  57182. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  57183. var newEmitter = subEmitter.clone();
  57184. particle._attachedSubEmitters.push(newEmitter);
  57185. newEmitter.particleSystem.start();
  57186. }
  57187. });
  57188. }
  57189. return particle;
  57190. };
  57191. _this._emitFromParticle = function (particle) {
  57192. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  57193. return;
  57194. }
  57195. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  57196. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  57197. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  57198. var subSystem = subEmitter.clone();
  57199. particle._inheritParticleInfoToSubEmitter(subSystem);
  57200. subSystem.particleSystem._rootParticleSystem = _this;
  57201. _this.activeSubSystems.push(subSystem.particleSystem);
  57202. subSystem.particleSystem.start();
  57203. }
  57204. });
  57205. };
  57206. _this._capacity = capacity;
  57207. _this._epsilon = epsilon;
  57208. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57209. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57210. // Setup the default processing configuration to the scene.
  57211. _this._attachImageProcessingConfiguration(null);
  57212. _this._customEffect = customEffect;
  57213. _this._scene.particleSystems.push(_this);
  57214. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  57215. _this._createIndexBuffer();
  57216. _this._createVertexBuffers();
  57217. // Default emitter type
  57218. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57219. // Update
  57220. _this.updateFunction = function (particles) {
  57221. var noiseTextureSize = null;
  57222. var noiseTextureData = null;
  57223. if (_this.noiseTexture) { // We need to get texture data back to CPU
  57224. noiseTextureSize = _this.noiseTexture.getSize();
  57225. noiseTextureData = (_this.noiseTexture.getContent());
  57226. }
  57227. var _loop_1 = function () {
  57228. particle = particles[index];
  57229. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  57230. var previousAge = particle.age;
  57231. particle.age += scaledUpdateSpeed;
  57232. // Evaluate step to death
  57233. if (particle.age > particle.lifeTime) {
  57234. var diff = particle.age - previousAge;
  57235. var oldDiff = particle.lifeTime - previousAge;
  57236. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  57237. particle.age = particle.lifeTime;
  57238. }
  57239. var ratio = particle.age / particle.lifeTime;
  57240. // Color
  57241. if (_this._colorGradients && _this._colorGradients.length > 0) {
  57242. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  57243. if (currentGradient !== particle._currentColorGradient) {
  57244. particle._currentColor1.copyFrom(particle._currentColor2);
  57245. nextGradient.getColorToRef(particle._currentColor2);
  57246. particle._currentColorGradient = currentGradient;
  57247. }
  57248. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  57249. });
  57250. }
  57251. else {
  57252. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  57253. particle.color.addInPlace(_this._scaledColorStep);
  57254. if (particle.color.a < 0) {
  57255. particle.color.a = 0;
  57256. }
  57257. }
  57258. // Angular speed
  57259. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  57260. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  57261. if (currentGradient !== particle._currentAngularSpeedGradient) {
  57262. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  57263. particle._currentAngularSpeed2 = nextGradient.getFactor();
  57264. particle._currentAngularSpeedGradient = currentGradient;
  57265. }
  57266. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  57267. });
  57268. }
  57269. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  57270. // Direction
  57271. var directionScale = scaledUpdateSpeed;
  57272. /// Velocity
  57273. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  57274. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  57275. if (currentGradient !== particle._currentVelocityGradient) {
  57276. particle._currentVelocity1 = particle._currentVelocity2;
  57277. particle._currentVelocity2 = nextGradient.getFactor();
  57278. particle._currentVelocityGradient = currentGradient;
  57279. }
  57280. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  57281. });
  57282. }
  57283. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  57284. /// Limit velocity
  57285. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  57286. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  57287. if (currentGradient !== particle._currentLimitVelocityGradient) {
  57288. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  57289. particle._currentLimitVelocity2 = nextGradient.getFactor();
  57290. particle._currentLimitVelocityGradient = currentGradient;
  57291. }
  57292. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  57293. var currentVelocity = particle.direction.length();
  57294. if (currentVelocity > limitVelocity) {
  57295. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  57296. }
  57297. });
  57298. }
  57299. /// Drag
  57300. if (_this._dragGradients && _this._dragGradients.length > 0) {
  57301. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  57302. if (currentGradient !== particle._currentDragGradient) {
  57303. particle._currentDrag1 = particle._currentDrag2;
  57304. particle._currentDrag2 = nextGradient.getFactor();
  57305. particle._currentDragGradient = currentGradient;
  57306. }
  57307. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  57308. _this._scaledDirection.scaleInPlace(1.0 - drag);
  57309. });
  57310. }
  57311. particle.position.addInPlace(_this._scaledDirection);
  57312. // Noise
  57313. if (noiseTextureData && noiseTextureSize) {
  57314. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57315. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57316. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  57317. var force = BABYLON.Tmp.Vector3[0];
  57318. var scaledForce = BABYLON.Tmp.Vector3[1];
  57319. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  57320. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  57321. particle.direction.addInPlace(scaledForce);
  57322. }
  57323. // Gravity
  57324. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  57325. particle.direction.addInPlace(_this._scaledGravity);
  57326. // Size
  57327. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  57328. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57329. if (currentGradient !== particle._currentSizeGradient) {
  57330. particle._currentSize1 = particle._currentSize2;
  57331. particle._currentSize2 = nextGradient.getFactor();
  57332. particle._currentSizeGradient = currentGradient;
  57333. }
  57334. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  57335. });
  57336. }
  57337. // Remap data
  57338. if (_this._useRampGradients) {
  57339. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  57340. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  57341. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57342. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57343. particle.remapData.x = min;
  57344. particle.remapData.y = max - min;
  57345. });
  57346. }
  57347. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  57348. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  57349. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57350. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  57351. particle.remapData.z = min;
  57352. particle.remapData.w = max - min;
  57353. });
  57354. }
  57355. }
  57356. if (_this._isAnimationSheetEnabled) {
  57357. particle.updateCellIndex();
  57358. }
  57359. // Update the position of the attached sub-emitters to match their attached particle
  57360. particle._inheritParticleInfoToSubEmitters();
  57361. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  57362. _this._emitFromParticle(particle);
  57363. if (particle._attachedSubEmitters) {
  57364. particle._attachedSubEmitters.forEach(function (subEmitter) {
  57365. subEmitter.particleSystem.disposeOnStop = true;
  57366. subEmitter.particleSystem.stop();
  57367. });
  57368. particle._attachedSubEmitters = null;
  57369. }
  57370. _this.recycleParticle(particle);
  57371. index--;
  57372. return "continue";
  57373. }
  57374. };
  57375. var particle;
  57376. for (var index = 0; index < particles.length; index++) {
  57377. _loop_1();
  57378. }
  57379. };
  57380. return _this;
  57381. }
  57382. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  57383. /**
  57384. * Sets a callback that will be triggered when the system is disposed
  57385. */
  57386. set: function (callback) {
  57387. if (this._onDisposeObserver) {
  57388. this.onDisposeObservable.remove(this._onDisposeObserver);
  57389. }
  57390. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  57391. },
  57392. enumerable: true,
  57393. configurable: true
  57394. });
  57395. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  57396. /** Gets or sets a boolean indicating that ramp gradients must be used
  57397. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  57398. */
  57399. get: function () {
  57400. return this._useRampGradients;
  57401. },
  57402. set: function (value) {
  57403. if (this._useRampGradients === value) {
  57404. return;
  57405. }
  57406. this._useRampGradients = value;
  57407. this._resetEffect();
  57408. },
  57409. enumerable: true,
  57410. configurable: true
  57411. });
  57412. Object.defineProperty(ParticleSystem.prototype, "particles", {
  57413. //end of Sub-emitter
  57414. /**
  57415. * Gets the current list of active particles
  57416. */
  57417. get: function () {
  57418. return this._particles;
  57419. },
  57420. enumerable: true,
  57421. configurable: true
  57422. });
  57423. /**
  57424. * Returns the string "ParticleSystem"
  57425. * @returns a string containing the class name
  57426. */
  57427. ParticleSystem.prototype.getClassName = function () {
  57428. return "ParticleSystem";
  57429. };
  57430. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  57431. var newGradient = new BABYLON.FactorGradient();
  57432. newGradient.gradient = gradient;
  57433. newGradient.factor1 = factor;
  57434. newGradient.factor2 = factor2;
  57435. factorGradients.push(newGradient);
  57436. factorGradients.sort(function (a, b) {
  57437. if (a.gradient < b.gradient) {
  57438. return -1;
  57439. }
  57440. else if (a.gradient > b.gradient) {
  57441. return 1;
  57442. }
  57443. return 0;
  57444. });
  57445. };
  57446. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  57447. if (!factorGradients) {
  57448. return;
  57449. }
  57450. var index = 0;
  57451. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  57452. var factorGradient = factorGradients_1[_i];
  57453. if (factorGradient.gradient === gradient) {
  57454. factorGradients.splice(index, 1);
  57455. break;
  57456. }
  57457. index++;
  57458. }
  57459. };
  57460. /**
  57461. * Adds a new life time gradient
  57462. * @param gradient defines the gradient to use (between 0 and 1)
  57463. * @param factor defines the life time factor to affect to the specified gradient
  57464. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57465. * @returns the current particle system
  57466. */
  57467. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  57468. if (!this._lifeTimeGradients) {
  57469. this._lifeTimeGradients = [];
  57470. }
  57471. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  57472. return this;
  57473. };
  57474. /**
  57475. * Remove a specific life time gradient
  57476. * @param gradient defines the gradient to remove
  57477. * @returns the current particle system
  57478. */
  57479. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  57480. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  57481. return this;
  57482. };
  57483. /**
  57484. * Adds a new size gradient
  57485. * @param gradient defines the gradient to use (between 0 and 1)
  57486. * @param factor defines the size factor to affect to the specified gradient
  57487. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57488. * @returns the current particle system
  57489. */
  57490. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  57491. if (!this._sizeGradients) {
  57492. this._sizeGradients = [];
  57493. }
  57494. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  57495. return this;
  57496. };
  57497. /**
  57498. * Remove a specific size gradient
  57499. * @param gradient defines the gradient to remove
  57500. * @returns the current particle system
  57501. */
  57502. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57503. this._removeFactorGradient(this._sizeGradients, gradient);
  57504. return this;
  57505. };
  57506. /**
  57507. * Adds a new color remap gradient
  57508. * @param gradient defines the gradient to use (between 0 and 1)
  57509. * @param min defines the color remap minimal range
  57510. * @param max defines the color remap maximal range
  57511. * @returns the current particle system
  57512. */
  57513. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  57514. if (!this._colorRemapGradients) {
  57515. this._colorRemapGradients = [];
  57516. }
  57517. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  57518. return this;
  57519. };
  57520. /**
  57521. * Remove a specific color remap gradient
  57522. * @param gradient defines the gradient to remove
  57523. * @returns the current particle system
  57524. */
  57525. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  57526. this._removeFactorGradient(this._colorRemapGradients, gradient);
  57527. return this;
  57528. };
  57529. /**
  57530. * Adds a new alpha remap gradient
  57531. * @param gradient defines the gradient to use (between 0 and 1)
  57532. * @param min defines the alpha remap minimal range
  57533. * @param max defines the alpha remap maximal range
  57534. * @returns the current particle system
  57535. */
  57536. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  57537. if (!this._alphaRemapGradients) {
  57538. this._alphaRemapGradients = [];
  57539. }
  57540. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  57541. return this;
  57542. };
  57543. /**
  57544. * Remove a specific alpha remap gradient
  57545. * @param gradient defines the gradient to remove
  57546. * @returns the current particle system
  57547. */
  57548. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  57549. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  57550. return this;
  57551. };
  57552. /**
  57553. * Adds a new angular speed gradient
  57554. * @param gradient defines the gradient to use (between 0 and 1)
  57555. * @param factor defines the angular speed to affect to the specified gradient
  57556. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57557. * @returns the current particle system
  57558. */
  57559. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  57560. if (!this._angularSpeedGradients) {
  57561. this._angularSpeedGradients = [];
  57562. }
  57563. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  57564. return this;
  57565. };
  57566. /**
  57567. * Remove a specific angular speed gradient
  57568. * @param gradient defines the gradient to remove
  57569. * @returns the current particle system
  57570. */
  57571. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57572. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  57573. return this;
  57574. };
  57575. /**
  57576. * Adds a new velocity gradient
  57577. * @param gradient defines the gradient to use (between 0 and 1)
  57578. * @param factor defines the velocity to affect to the specified gradient
  57579. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57580. * @returns the current particle system
  57581. */
  57582. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  57583. if (!this._velocityGradients) {
  57584. this._velocityGradients = [];
  57585. }
  57586. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  57587. return this;
  57588. };
  57589. /**
  57590. * Remove a specific velocity gradient
  57591. * @param gradient defines the gradient to remove
  57592. * @returns the current particle system
  57593. */
  57594. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57595. this._removeFactorGradient(this._velocityGradients, gradient);
  57596. return this;
  57597. };
  57598. /**
  57599. * Adds a new limit velocity gradient
  57600. * @param gradient defines the gradient to use (between 0 and 1)
  57601. * @param factor defines the limit velocity value to affect to the specified gradient
  57602. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57603. * @returns the current particle system
  57604. */
  57605. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  57606. if (!this._limitVelocityGradients) {
  57607. this._limitVelocityGradients = [];
  57608. }
  57609. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  57610. return this;
  57611. };
  57612. /**
  57613. * Remove a specific limit velocity gradient
  57614. * @param gradient defines the gradient to remove
  57615. * @returns the current particle system
  57616. */
  57617. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  57618. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  57619. return this;
  57620. };
  57621. /**
  57622. * Adds a new drag gradient
  57623. * @param gradient defines the gradient to use (between 0 and 1)
  57624. * @param factor defines the drag value to affect to the specified gradient
  57625. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57626. * @returns the current particle system
  57627. */
  57628. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  57629. if (!this._dragGradients) {
  57630. this._dragGradients = [];
  57631. }
  57632. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  57633. return this;
  57634. };
  57635. /**
  57636. * Remove a specific drag gradient
  57637. * @param gradient defines the gradient to remove
  57638. * @returns the current particle system
  57639. */
  57640. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  57641. this._removeFactorGradient(this._dragGradients, gradient);
  57642. return this;
  57643. };
  57644. /**
  57645. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  57646. * @param gradient defines the gradient to use (between 0 and 1)
  57647. * @param factor defines the emit rate value to affect to the specified gradient
  57648. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57649. * @returns the current particle system
  57650. */
  57651. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  57652. if (!this._emitRateGradients) {
  57653. this._emitRateGradients = [];
  57654. }
  57655. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  57656. if (!this._currentEmitRateGradient) {
  57657. this._currentEmitRateGradient = this._emitRateGradients[0];
  57658. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  57659. this._currentEmitRate2 = this._currentEmitRate1;
  57660. }
  57661. if (this._emitRateGradients.length === 2) {
  57662. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  57663. }
  57664. return this;
  57665. };
  57666. /**
  57667. * Remove a specific emit rate gradient
  57668. * @param gradient defines the gradient to remove
  57669. * @returns the current particle system
  57670. */
  57671. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  57672. this._removeFactorGradient(this._emitRateGradients, gradient);
  57673. return this;
  57674. };
  57675. /**
  57676. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  57677. * @param gradient defines the gradient to use (between 0 and 1)
  57678. * @param factor defines the start size value to affect to the specified gradient
  57679. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  57680. * @returns the current particle system
  57681. */
  57682. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  57683. if (!this._startSizeGradients) {
  57684. this._startSizeGradients = [];
  57685. }
  57686. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  57687. if (!this._currentStartSizeGradient) {
  57688. this._currentStartSizeGradient = this._startSizeGradients[0];
  57689. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  57690. this._currentStartSize2 = this._currentStartSize1;
  57691. }
  57692. if (this._startSizeGradients.length === 2) {
  57693. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  57694. }
  57695. return this;
  57696. };
  57697. /**
  57698. * Remove a specific start size gradient
  57699. * @param gradient defines the gradient to remove
  57700. * @returns the current particle system
  57701. */
  57702. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  57703. this._removeFactorGradient(this._emitRateGradients, gradient);
  57704. return this;
  57705. };
  57706. ParticleSystem.prototype._createRampGradientTexture = function () {
  57707. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  57708. return;
  57709. }
  57710. var data = new Uint8Array(this._rawTextureWidth * 4);
  57711. var tmpColor = BABYLON.Tmp.Color3[0];
  57712. for (var x = 0; x < this._rawTextureWidth; x++) {
  57713. var ratio = x / this._rawTextureWidth;
  57714. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  57715. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57716. data[x * 4] = tmpColor.r * 255;
  57717. data[x * 4 + 1] = tmpColor.g * 255;
  57718. data[x * 4 + 2] = tmpColor.b * 255;
  57719. data[x * 4 + 3] = 255;
  57720. });
  57721. }
  57722. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57723. };
  57724. /**
  57725. * Gets the current list of ramp gradients.
  57726. * You must use addRampGradient and removeRampGradient to udpate this list
  57727. * @returns the list of ramp gradients
  57728. */
  57729. ParticleSystem.prototype.getRampGradients = function () {
  57730. return this._rampGradients;
  57731. };
  57732. /**
  57733. * Adds a new ramp gradient used to remap particle colors
  57734. * @param gradient defines the gradient to use (between 0 and 1)
  57735. * @param color defines the color to affect to the specified gradient
  57736. * @returns the current particle system
  57737. */
  57738. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  57739. if (!this._rampGradients) {
  57740. this._rampGradients = [];
  57741. }
  57742. var rampGradient = new BABYLON.Color3Gradient();
  57743. rampGradient.gradient = gradient;
  57744. rampGradient.color = color;
  57745. this._rampGradients.push(rampGradient);
  57746. this._rampGradients.sort(function (a, b) {
  57747. if (a.gradient < b.gradient) {
  57748. return -1;
  57749. }
  57750. else if (a.gradient > b.gradient) {
  57751. return 1;
  57752. }
  57753. return 0;
  57754. });
  57755. if (this._rampGradientsTexture) {
  57756. this._rampGradientsTexture.dispose();
  57757. this._rampGradientsTexture = null;
  57758. }
  57759. this._createRampGradientTexture();
  57760. return this;
  57761. };
  57762. /**
  57763. * Remove a specific ramp gradient
  57764. * @param gradient defines the gradient to remove
  57765. * @returns the current particle system
  57766. */
  57767. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  57768. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  57769. this._rampGradientsTexture = null;
  57770. if (this._rampGradients && this._rampGradients.length > 0) {
  57771. this._createRampGradientTexture();
  57772. }
  57773. return this;
  57774. };
  57775. /**
  57776. * Adds a new color gradient
  57777. * @param gradient defines the gradient to use (between 0 and 1)
  57778. * @param color1 defines the color to affect to the specified gradient
  57779. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57780. */
  57781. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57782. if (!this._colorGradients) {
  57783. this._colorGradients = [];
  57784. }
  57785. var colorGradient = new BABYLON.ColorGradient();
  57786. colorGradient.gradient = gradient;
  57787. colorGradient.color1 = color1;
  57788. colorGradient.color2 = color2;
  57789. this._colorGradients.push(colorGradient);
  57790. this._colorGradients.sort(function (a, b) {
  57791. if (a.gradient < b.gradient) {
  57792. return -1;
  57793. }
  57794. else if (a.gradient > b.gradient) {
  57795. return 1;
  57796. }
  57797. return 0;
  57798. });
  57799. return this;
  57800. };
  57801. /**
  57802. * Remove a specific color gradient
  57803. * @param gradient defines the gradient to remove
  57804. */
  57805. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  57806. if (!this._colorGradients) {
  57807. return this;
  57808. }
  57809. var index = 0;
  57810. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57811. var colorGradient = _a[_i];
  57812. if (colorGradient.gradient === gradient) {
  57813. this._colorGradients.splice(index, 1);
  57814. break;
  57815. }
  57816. index++;
  57817. }
  57818. return this;
  57819. };
  57820. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  57821. u = Math.abs(u) * 0.5 + 0.5;
  57822. v = Math.abs(v) * 0.5 + 0.5;
  57823. var wrappedU = ((u * width) % width) | 0;
  57824. var wrappedV = ((v * height) % height) | 0;
  57825. var position = (wrappedU + wrappedV * width) * 4;
  57826. return pixels[position] / 255;
  57827. };
  57828. ParticleSystem.prototype._reset = function () {
  57829. this._resetEffect();
  57830. };
  57831. ParticleSystem.prototype._resetEffect = function () {
  57832. if (this._vertexBuffer) {
  57833. this._vertexBuffer.dispose();
  57834. this._vertexBuffer = null;
  57835. }
  57836. if (this._spriteBuffer) {
  57837. this._spriteBuffer.dispose();
  57838. this._spriteBuffer = null;
  57839. }
  57840. this._createVertexBuffers();
  57841. };
  57842. ParticleSystem.prototype._createVertexBuffers = function () {
  57843. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  57844. if (this._isAnimationSheetEnabled) {
  57845. this._vertexBufferSize += 1;
  57846. }
  57847. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57848. this._vertexBufferSize += 3;
  57849. }
  57850. if (this._useRampGradients) {
  57851. this._vertexBufferSize += 4;
  57852. }
  57853. var engine = this._scene.getEngine();
  57854. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  57855. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  57856. var dataOffset = 0;
  57857. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57858. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  57859. dataOffset += 3;
  57860. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57861. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  57862. dataOffset += 4;
  57863. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57864. this._vertexBuffers["angle"] = options;
  57865. dataOffset += 1;
  57866. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57867. this._vertexBuffers["size"] = size;
  57868. dataOffset += 2;
  57869. if (this._isAnimationSheetEnabled) {
  57870. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  57871. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  57872. dataOffset += 1;
  57873. }
  57874. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  57875. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  57876. this._vertexBuffers["direction"] = directionBuffer;
  57877. dataOffset += 3;
  57878. }
  57879. if (this._useRampGradients) {
  57880. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  57881. this._vertexBuffers["remapData"] = rampDataBuffer;
  57882. dataOffset += 4;
  57883. }
  57884. var offsets;
  57885. if (this._useInstancing) {
  57886. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  57887. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  57888. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  57889. }
  57890. else {
  57891. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  57892. dataOffset += 2;
  57893. }
  57894. this._vertexBuffers["offset"] = offsets;
  57895. };
  57896. ParticleSystem.prototype._createIndexBuffer = function () {
  57897. if (this._useInstancing) {
  57898. return;
  57899. }
  57900. var indices = [];
  57901. var index = 0;
  57902. for (var count = 0; count < this._capacity; count++) {
  57903. indices.push(index);
  57904. indices.push(index + 1);
  57905. indices.push(index + 2);
  57906. indices.push(index);
  57907. indices.push(index + 2);
  57908. indices.push(index + 3);
  57909. index += 4;
  57910. }
  57911. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  57912. };
  57913. /**
  57914. * Gets the maximum number of particles active at the same time.
  57915. * @returns The max number of active particles.
  57916. */
  57917. ParticleSystem.prototype.getCapacity = function () {
  57918. return this._capacity;
  57919. };
  57920. /**
  57921. * Gets whether there are still active particles in the system.
  57922. * @returns True if it is alive, otherwise false.
  57923. */
  57924. ParticleSystem.prototype.isAlive = function () {
  57925. return this._alive;
  57926. };
  57927. /**
  57928. * Gets if the system has been started. (Note: this will still be true after stop is called)
  57929. * @returns True if it has been started, otherwise false.
  57930. */
  57931. ParticleSystem.prototype.isStarted = function () {
  57932. return this._started;
  57933. };
  57934. /**
  57935. * Starts the particle system and begins to emit
  57936. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  57937. */
  57938. ParticleSystem.prototype.start = function (delay) {
  57939. var _this = this;
  57940. if (delay === void 0) { delay = this.startDelay; }
  57941. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  57942. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  57943. }
  57944. if (delay) {
  57945. setTimeout(function () {
  57946. _this.start(0);
  57947. }, delay);
  57948. return;
  57949. }
  57950. // Convert the subEmitters field to the constant type field _subEmitters
  57951. this._subEmitters = new Array();
  57952. if (this.subEmitters) {
  57953. this.subEmitters.forEach(function (subEmitter) {
  57954. if (subEmitter instanceof ParticleSystem) {
  57955. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  57956. }
  57957. else if (subEmitter instanceof BABYLON.SubEmitter) {
  57958. _this._subEmitters.push([subEmitter]);
  57959. }
  57960. else if (subEmitter instanceof Array) {
  57961. _this._subEmitters.push(subEmitter);
  57962. }
  57963. _this._subEmitters[_this._subEmitters.length - 1].forEach(function (se) {
  57964. if (!(se.particleSystem.emitter instanceof BABYLON.AbstractMesh) && se.inheritDirection) {
  57965. BABYLON.Tools.Warn("subEmitter.inheritDirection is not supported with non-mesh emitter type");
  57966. }
  57967. });
  57968. });
  57969. }
  57970. this._started = true;
  57971. this._stopped = false;
  57972. this._actualFrame = 0;
  57973. if (this._subEmitters && this._subEmitters.length != 0) {
  57974. this.activeSubSystems = new Array();
  57975. }
  57976. if (this.preWarmCycles) {
  57977. if (this.emitter instanceof BABYLON.AbstractMesh) {
  57978. this.emitter.computeWorldMatrix(true);
  57979. }
  57980. var noiseTextureAsProcedural_1 = this.noiseTexture;
  57981. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  57982. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  57983. setTimeout(function () {
  57984. for (var index = 0; index < _this.preWarmCycles; index++) {
  57985. _this.animate(true);
  57986. noiseTextureAsProcedural_1.render();
  57987. }
  57988. });
  57989. });
  57990. }
  57991. else {
  57992. for (var index = 0; index < this.preWarmCycles; index++) {
  57993. this.animate(true);
  57994. }
  57995. }
  57996. }
  57997. };
  57998. /**
  57999. * Stops the particle system.
  58000. * @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.
  58001. */
  58002. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  58003. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  58004. this._stopped = true;
  58005. if (stopSubEmitters) {
  58006. this._stopSubEmitters();
  58007. }
  58008. };
  58009. // animation sheet
  58010. /**
  58011. * Remove all active particles
  58012. */
  58013. ParticleSystem.prototype.reset = function () {
  58014. this._stockParticles = [];
  58015. this._particles = [];
  58016. };
  58017. /**
  58018. * @hidden (for internal use only)
  58019. */
  58020. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  58021. var offset = index * this._vertexBufferSize;
  58022. this._vertexData[offset++] = particle.position.x;
  58023. this._vertexData[offset++] = particle.position.y;
  58024. this._vertexData[offset++] = particle.position.z;
  58025. this._vertexData[offset++] = particle.color.r;
  58026. this._vertexData[offset++] = particle.color.g;
  58027. this._vertexData[offset++] = particle.color.b;
  58028. this._vertexData[offset++] = particle.color.a;
  58029. this._vertexData[offset++] = particle.angle;
  58030. this._vertexData[offset++] = particle.scale.x * particle.size;
  58031. this._vertexData[offset++] = particle.scale.y * particle.size;
  58032. if (this._isAnimationSheetEnabled) {
  58033. this._vertexData[offset++] = particle.cellIndex;
  58034. }
  58035. if (!this._isBillboardBased) {
  58036. if (particle._initialDirection) {
  58037. this._vertexData[offset++] = particle._initialDirection.x;
  58038. this._vertexData[offset++] = particle._initialDirection.y;
  58039. this._vertexData[offset++] = particle._initialDirection.z;
  58040. }
  58041. else {
  58042. this._vertexData[offset++] = particle.direction.x;
  58043. this._vertexData[offset++] = particle.direction.y;
  58044. this._vertexData[offset++] = particle.direction.z;
  58045. }
  58046. }
  58047. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  58048. this._vertexData[offset++] = particle.direction.x;
  58049. this._vertexData[offset++] = particle.direction.y;
  58050. this._vertexData[offset++] = particle.direction.z;
  58051. }
  58052. if (this._useRampGradients) {
  58053. this._vertexData[offset++] = particle.remapData.x;
  58054. this._vertexData[offset++] = particle.remapData.y;
  58055. this._vertexData[offset++] = particle.remapData.z;
  58056. this._vertexData[offset++] = particle.remapData.w;
  58057. }
  58058. if (!this._useInstancing) {
  58059. if (this._isAnimationSheetEnabled) {
  58060. if (offsetX === 0)
  58061. offsetX = this._epsilon;
  58062. else if (offsetX === 1)
  58063. offsetX = 1 - this._epsilon;
  58064. if (offsetY === 0)
  58065. offsetY = this._epsilon;
  58066. else if (offsetY === 1)
  58067. offsetY = 1 - this._epsilon;
  58068. }
  58069. this._vertexData[offset++] = offsetX;
  58070. this._vertexData[offset++] = offsetY;
  58071. }
  58072. };
  58073. ParticleSystem.prototype._stopSubEmitters = function () {
  58074. if (!this.activeSubSystems) {
  58075. return;
  58076. }
  58077. this.activeSubSystems.forEach(function (subSystem) {
  58078. subSystem.stop(true);
  58079. });
  58080. this.activeSubSystems = new Array();
  58081. };
  58082. ParticleSystem.prototype._removeFromRoot = function () {
  58083. if (!this._rootParticleSystem) {
  58084. return;
  58085. }
  58086. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  58087. if (index !== -1) {
  58088. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  58089. }
  58090. this._rootParticleSystem = null;
  58091. };
  58092. // End of sub system methods
  58093. ParticleSystem.prototype._update = function (newParticles) {
  58094. var _this = this;
  58095. // Update current
  58096. this._alive = this._particles.length > 0;
  58097. if (this.emitter.position) {
  58098. var emitterMesh = this.emitter;
  58099. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  58100. }
  58101. else {
  58102. var emitterPosition = this.emitter;
  58103. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58104. }
  58105. this.updateFunction(this._particles);
  58106. // Add new ones
  58107. var particle;
  58108. var _loop_2 = function () {
  58109. if (this_1._particles.length === this_1._capacity) {
  58110. return "break";
  58111. }
  58112. particle = this_1._createParticle();
  58113. this_1._particles.push(particle);
  58114. // Emitter
  58115. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  58116. if (this_1.startPositionFunction) {
  58117. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58118. }
  58119. else {
  58120. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  58121. }
  58122. if (this_1.startDirectionFunction) {
  58123. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58124. }
  58125. else {
  58126. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  58127. }
  58128. if (emitPower === 0) {
  58129. if (!particle._initialDirection) {
  58130. particle._initialDirection = particle.direction.clone();
  58131. }
  58132. else {
  58133. particle._initialDirection.copyFrom(particle.direction);
  58134. }
  58135. }
  58136. else {
  58137. particle._initialDirection = null;
  58138. }
  58139. particle.direction.scaleInPlace(emitPower);
  58140. // Life time
  58141. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  58142. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  58143. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  58144. var factorGradient1 = currentGradient;
  58145. var factorGradient2 = nextGradient;
  58146. var lifeTime1 = factorGradient1.getFactor();
  58147. var lifeTime2 = factorGradient2.getFactor();
  58148. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  58149. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  58150. });
  58151. }
  58152. else {
  58153. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  58154. }
  58155. // Size
  58156. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  58157. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  58158. }
  58159. else {
  58160. particle._currentSizeGradient = this_1._sizeGradients[0];
  58161. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  58162. particle.size = particle._currentSize1;
  58163. if (this_1._sizeGradients.length > 1) {
  58164. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  58165. }
  58166. else {
  58167. particle._currentSize2 = particle._currentSize1;
  58168. }
  58169. }
  58170. // Size and scale
  58171. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  58172. // Adjust scale by start size
  58173. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  58174. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  58175. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  58176. if (currentGradient !== _this._currentStartSizeGradient) {
  58177. _this._currentStartSize1 = _this._currentStartSize2;
  58178. _this._currentStartSize2 = nextGradient.getFactor();
  58179. _this._currentStartSizeGradient = currentGradient;
  58180. }
  58181. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  58182. particle.scale.scaleInPlace(value);
  58183. });
  58184. }
  58185. // Angle
  58186. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  58187. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  58188. }
  58189. else {
  58190. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  58191. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  58192. particle._currentAngularSpeed1 = particle.angularSpeed;
  58193. if (this_1._angularSpeedGradients.length > 1) {
  58194. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  58195. }
  58196. else {
  58197. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  58198. }
  58199. }
  58200. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  58201. // Velocity
  58202. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  58203. particle._currentVelocityGradient = this_1._velocityGradients[0];
  58204. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  58205. if (this_1._velocityGradients.length > 1) {
  58206. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  58207. }
  58208. else {
  58209. particle._currentVelocity2 = particle._currentVelocity1;
  58210. }
  58211. }
  58212. // Limit velocity
  58213. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  58214. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  58215. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  58216. if (this_1._limitVelocityGradients.length > 1) {
  58217. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  58218. }
  58219. else {
  58220. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  58221. }
  58222. }
  58223. // Drag
  58224. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  58225. particle._currentDragGradient = this_1._dragGradients[0];
  58226. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  58227. if (this_1._dragGradients.length > 1) {
  58228. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  58229. }
  58230. else {
  58231. particle._currentDrag2 = particle._currentDrag1;
  58232. }
  58233. }
  58234. // Color
  58235. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  58236. step = BABYLON.Scalar.RandomRange(0, 1.0);
  58237. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  58238. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  58239. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  58240. }
  58241. else {
  58242. particle._currentColorGradient = this_1._colorGradients[0];
  58243. particle._currentColorGradient.getColorToRef(particle.color);
  58244. particle._currentColor1.copyFrom(particle.color);
  58245. if (this_1._colorGradients.length > 1) {
  58246. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  58247. }
  58248. else {
  58249. particle._currentColor2.copyFrom(particle.color);
  58250. }
  58251. }
  58252. // Sheet
  58253. if (this_1._isAnimationSheetEnabled) {
  58254. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  58255. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  58256. }
  58257. // Inherited Velocity
  58258. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  58259. // Ramp
  58260. if (this_1._useRampGradients) {
  58261. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  58262. }
  58263. // Noise texture coordinates
  58264. if (this_1.noiseTexture) {
  58265. if (particle._randomNoiseCoordinates1) {
  58266. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  58267. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  58268. }
  58269. else {
  58270. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58271. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  58272. }
  58273. }
  58274. // Update the position of the attached sub-emitters to match their attached particle
  58275. particle._inheritParticleInfoToSubEmitters();
  58276. };
  58277. var this_1 = this, step;
  58278. for (var index = 0; index < newParticles; index++) {
  58279. var state_1 = _loop_2();
  58280. if (state_1 === "break")
  58281. break;
  58282. }
  58283. };
  58284. /** @hidden */
  58285. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  58286. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58287. if (isBillboardBased === void 0) { isBillboardBased = false; }
  58288. if (useRampGradients === void 0) { useRampGradients = false; }
  58289. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  58290. if (isAnimationSheetEnabled) {
  58291. attributeNamesOrOptions.push("cellIndex");
  58292. }
  58293. if (!isBillboardBased) {
  58294. attributeNamesOrOptions.push("direction");
  58295. }
  58296. if (useRampGradients) {
  58297. attributeNamesOrOptions.push("remapData");
  58298. }
  58299. return attributeNamesOrOptions;
  58300. };
  58301. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  58302. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58303. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  58304. if (isAnimationSheetEnabled) {
  58305. effectCreationOption.push("particlesInfos");
  58306. }
  58307. return effectCreationOption;
  58308. };
  58309. ParticleSystem.prototype._getEffect = function (blendMode) {
  58310. if (this._customEffect) {
  58311. return this._customEffect;
  58312. }
  58313. ;
  58314. var defines = [];
  58315. if (this._scene.clipPlane) {
  58316. defines.push("#define CLIPPLANE");
  58317. }
  58318. if (this._scene.clipPlane2) {
  58319. defines.push("#define CLIPPLANE2");
  58320. }
  58321. if (this._scene.clipPlane3) {
  58322. defines.push("#define CLIPPLANE3");
  58323. }
  58324. if (this._scene.clipPlane4) {
  58325. defines.push("#define CLIPPLANE4");
  58326. }
  58327. if (this._isAnimationSheetEnabled) {
  58328. defines.push("#define ANIMATESHEET");
  58329. }
  58330. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  58331. defines.push("#define BLENDMULTIPLYMODE");
  58332. }
  58333. if (this._useRampGradients) {
  58334. defines.push("#define RAMPGRADIENT");
  58335. }
  58336. if (this._isBillboardBased) {
  58337. defines.push("#define BILLBOARD");
  58338. switch (this.billboardMode) {
  58339. case ParticleSystem.BILLBOARDMODE_Y:
  58340. defines.push("#define BILLBOARDY");
  58341. break;
  58342. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  58343. defines.push("#define BILLBOARDSTRETCHED");
  58344. break;
  58345. case ParticleSystem.BILLBOARDMODE_ALL:
  58346. default:
  58347. break;
  58348. }
  58349. }
  58350. if (this._imageProcessingConfiguration) {
  58351. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  58352. defines.push(this._imageProcessingConfigurationDefines.toString());
  58353. }
  58354. // Effect
  58355. var join = defines.join("\n");
  58356. if (this._cachedDefines !== join) {
  58357. this._cachedDefines = join;
  58358. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  58359. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  58360. var samplers = ["diffuseSampler", "rampSampler"];
  58361. if (BABYLON.ImageProcessingConfiguration) {
  58362. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  58363. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  58364. }
  58365. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  58366. }
  58367. return this._effect;
  58368. };
  58369. /**
  58370. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  58371. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  58372. */
  58373. ParticleSystem.prototype.animate = function (preWarmOnly) {
  58374. var _this = this;
  58375. if (preWarmOnly === void 0) { preWarmOnly = false; }
  58376. if (!this._started)
  58377. return;
  58378. if (!preWarmOnly) {
  58379. // Check
  58380. if (!this.isReady())
  58381. return;
  58382. if (this._currentRenderId === this._scene.getRenderId()) {
  58383. return;
  58384. }
  58385. this._currentRenderId = this._scene.getRenderId();
  58386. }
  58387. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  58388. // Determine the number of particles we need to create
  58389. var newParticles;
  58390. if (this.manualEmitCount > -1) {
  58391. newParticles = this.manualEmitCount;
  58392. this._newPartsExcess = 0;
  58393. this.manualEmitCount = 0;
  58394. }
  58395. else {
  58396. var rate_1 = this.emitRate;
  58397. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  58398. var ratio = this._actualFrame / this.targetStopDuration;
  58399. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  58400. if (currentGradient !== _this._currentEmitRateGradient) {
  58401. _this._currentEmitRate1 = _this._currentEmitRate2;
  58402. _this._currentEmitRate2 = nextGradient.getFactor();
  58403. _this._currentEmitRateGradient = currentGradient;
  58404. }
  58405. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  58406. });
  58407. }
  58408. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  58409. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  58410. }
  58411. if (this._newPartsExcess > 1.0) {
  58412. newParticles += this._newPartsExcess >> 0;
  58413. this._newPartsExcess -= this._newPartsExcess >> 0;
  58414. }
  58415. this._alive = false;
  58416. if (!this._stopped) {
  58417. this._actualFrame += this._scaledUpdateSpeed;
  58418. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  58419. this.stop();
  58420. }
  58421. else {
  58422. newParticles = 0;
  58423. }
  58424. this._update(newParticles);
  58425. // Stopped?
  58426. if (this._stopped) {
  58427. if (!this._alive) {
  58428. this._started = false;
  58429. if (this.onAnimationEnd) {
  58430. this.onAnimationEnd();
  58431. }
  58432. if (this.disposeOnStop) {
  58433. this._scene._toBeDisposed.push(this);
  58434. }
  58435. }
  58436. }
  58437. if (!preWarmOnly) {
  58438. // Update VBO
  58439. var offset = 0;
  58440. for (var index = 0; index < this._particles.length; index++) {
  58441. var particle = this._particles[index];
  58442. this._appendParticleVertices(offset, particle);
  58443. offset += this._useInstancing ? 1 : 4;
  58444. }
  58445. if (this._vertexBuffer) {
  58446. this._vertexBuffer.update(this._vertexData);
  58447. }
  58448. }
  58449. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  58450. this.stop();
  58451. }
  58452. };
  58453. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  58454. this._appendParticleVertex(offset++, particle, 0, 0);
  58455. if (!this._useInstancing) {
  58456. this._appendParticleVertex(offset++, particle, 1, 0);
  58457. this._appendParticleVertex(offset++, particle, 1, 1);
  58458. this._appendParticleVertex(offset++, particle, 0, 1);
  58459. }
  58460. };
  58461. /**
  58462. * Rebuilds the particle system.
  58463. */
  58464. ParticleSystem.prototype.rebuild = function () {
  58465. this._createIndexBuffer();
  58466. if (this._vertexBuffer) {
  58467. this._vertexBuffer._rebuild();
  58468. }
  58469. };
  58470. /**
  58471. * Is this system ready to be used/rendered
  58472. * @return true if the system is ready
  58473. */
  58474. ParticleSystem.prototype.isReady = function () {
  58475. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  58476. return false;
  58477. }
  58478. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58479. if (!this._getEffect(this.blendMode).isReady()) {
  58480. return false;
  58481. }
  58482. }
  58483. else {
  58484. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  58485. return false;
  58486. }
  58487. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  58488. return false;
  58489. }
  58490. }
  58491. return true;
  58492. };
  58493. ParticleSystem.prototype._render = function (blendMode) {
  58494. var effect = this._getEffect(blendMode);
  58495. var engine = this._scene.getEngine();
  58496. // Render
  58497. engine.enableEffect(effect);
  58498. var viewMatrix = this._scene.getViewMatrix();
  58499. effect.setTexture("diffuseSampler", this.particleTexture);
  58500. effect.setMatrix("view", viewMatrix);
  58501. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  58502. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58503. var baseSize = this.particleTexture.getBaseSize();
  58504. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58505. }
  58506. effect.setVector2("translationPivot", this.translationPivot);
  58507. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  58508. if (this._isBillboardBased) {
  58509. var camera = this._scene.activeCamera;
  58510. effect.setVector3("eyePosition", camera.globalPosition);
  58511. }
  58512. if (this._rampGradientsTexture) {
  58513. effect.setTexture("rampSampler", this._rampGradientsTexture);
  58514. }
  58515. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  58516. var invView = viewMatrix.clone();
  58517. invView.invert();
  58518. effect.setMatrix("invView", invView);
  58519. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  58520. }
  58521. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  58522. // image processing
  58523. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  58524. this._imageProcessingConfiguration.bind(effect);
  58525. }
  58526. // Draw order
  58527. switch (blendMode) {
  58528. case ParticleSystem.BLENDMODE_ADD:
  58529. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58530. break;
  58531. case ParticleSystem.BLENDMODE_ONEONE:
  58532. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58533. break;
  58534. case ParticleSystem.BLENDMODE_STANDARD:
  58535. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58536. break;
  58537. case ParticleSystem.BLENDMODE_MULTIPLY:
  58538. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  58539. break;
  58540. }
  58541. if (this._useInstancing) {
  58542. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  58543. }
  58544. else {
  58545. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  58546. }
  58547. return this._particles.length;
  58548. };
  58549. /**
  58550. * Renders the particle system in its current state.
  58551. * @returns the current number of particles
  58552. */
  58553. ParticleSystem.prototype.render = function () {
  58554. // Check
  58555. if (!this.isReady() || !this._particles.length) {
  58556. return 0;
  58557. }
  58558. var engine = this._scene.getEngine();
  58559. engine.setState(false);
  58560. if (this.forceDepthWrite) {
  58561. engine.setDepthWrite(true);
  58562. }
  58563. var outparticles = 0;
  58564. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  58565. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  58566. }
  58567. outparticles = this._render(this.blendMode);
  58568. engine.unbindInstanceAttributes();
  58569. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58570. return outparticles;
  58571. };
  58572. /**
  58573. * Disposes the particle system and free the associated resources
  58574. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58575. */
  58576. ParticleSystem.prototype.dispose = function (disposeTexture) {
  58577. if (disposeTexture === void 0) { disposeTexture = true; }
  58578. if (this._vertexBuffer) {
  58579. this._vertexBuffer.dispose();
  58580. this._vertexBuffer = null;
  58581. }
  58582. if (this._spriteBuffer) {
  58583. this._spriteBuffer.dispose();
  58584. this._spriteBuffer = null;
  58585. }
  58586. if (this._indexBuffer) {
  58587. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  58588. this._indexBuffer = null;
  58589. }
  58590. if (disposeTexture && this.particleTexture) {
  58591. this.particleTexture.dispose();
  58592. this.particleTexture = null;
  58593. }
  58594. if (disposeTexture && this.noiseTexture) {
  58595. this.noiseTexture.dispose();
  58596. this.noiseTexture = null;
  58597. }
  58598. if (this._rampGradientsTexture) {
  58599. this._rampGradientsTexture.dispose();
  58600. this._rampGradientsTexture = null;
  58601. }
  58602. this._removeFromRoot();
  58603. if (this._subEmitters && this._subEmitters.length) {
  58604. for (var index = 0; index < this._subEmitters.length; index++) {
  58605. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  58606. var subEmitter = _a[_i];
  58607. subEmitter.dispose();
  58608. }
  58609. }
  58610. this._subEmitters = [];
  58611. this.subEmitters = [];
  58612. }
  58613. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  58614. this.emitter.dispose(true);
  58615. }
  58616. // Remove from scene
  58617. var index = this._scene.particleSystems.indexOf(this);
  58618. if (index > -1) {
  58619. this._scene.particleSystems.splice(index, 1);
  58620. }
  58621. this._scene._activeParticleSystems.dispose();
  58622. // Callback
  58623. this.onDisposeObservable.notifyObservers(this);
  58624. this.onDisposeObservable.clear();
  58625. this.reset();
  58626. };
  58627. // Clone
  58628. /**
  58629. * Clones the particle system.
  58630. * @param name The name of the cloned object
  58631. * @param newEmitter The new emitter to use
  58632. * @returns the cloned particle system
  58633. */
  58634. ParticleSystem.prototype.clone = function (name, newEmitter) {
  58635. var custom = null;
  58636. var program = null;
  58637. if (this.customShader != null) {
  58638. program = this.customShader;
  58639. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  58640. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  58641. }
  58642. else if (this._customEffect) {
  58643. custom = this._customEffect;
  58644. }
  58645. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  58646. result.customShader = program;
  58647. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  58648. if (newEmitter === undefined) {
  58649. newEmitter = this.emitter;
  58650. }
  58651. result.noiseTexture = this.noiseTexture;
  58652. result.emitter = newEmitter;
  58653. if (this.particleTexture) {
  58654. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58655. }
  58656. // Clone gradients
  58657. if (this._colorGradients) {
  58658. this._colorGradients.forEach(function (v) {
  58659. result.addColorGradient(v.gradient, v.color1, v.color2);
  58660. });
  58661. }
  58662. if (this._dragGradients) {
  58663. this._dragGradients.forEach(function (v) {
  58664. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  58665. });
  58666. }
  58667. if (this._angularSpeedGradients) {
  58668. this._angularSpeedGradients.forEach(function (v) {
  58669. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  58670. });
  58671. }
  58672. if (this._emitRateGradients) {
  58673. this._emitRateGradients.forEach(function (v) {
  58674. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  58675. });
  58676. }
  58677. if (this._lifeTimeGradients) {
  58678. this._lifeTimeGradients.forEach(function (v) {
  58679. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  58680. });
  58681. }
  58682. if (this._limitVelocityGradients) {
  58683. this._limitVelocityGradients.forEach(function (v) {
  58684. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  58685. });
  58686. }
  58687. if (this._sizeGradients) {
  58688. this._sizeGradients.forEach(function (v) {
  58689. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  58690. });
  58691. }
  58692. if (this._startSizeGradients) {
  58693. this._startSizeGradients.forEach(function (v) {
  58694. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  58695. });
  58696. }
  58697. if (this._velocityGradients) {
  58698. this._velocityGradients.forEach(function (v) {
  58699. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  58700. });
  58701. }
  58702. if (this._rampGradients) {
  58703. this._rampGradients.forEach(function (v) {
  58704. result.addRampGradient(v.gradient, v.color);
  58705. });
  58706. }
  58707. if (this._colorRemapGradients) {
  58708. this._colorRemapGradients.forEach(function (v) {
  58709. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  58710. });
  58711. }
  58712. if (this._alphaRemapGradients) {
  58713. this._alphaRemapGradients.forEach(function (v) {
  58714. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  58715. });
  58716. }
  58717. if (!this.preventAutoStart) {
  58718. result.start();
  58719. }
  58720. return result;
  58721. };
  58722. /**
  58723. * Serializes the particle system to a JSON object.
  58724. * @returns the JSON object
  58725. */
  58726. ParticleSystem.prototype.serialize = function () {
  58727. var serializationObject = {};
  58728. ParticleSystem._Serialize(serializationObject, this);
  58729. serializationObject.textureMask = this.textureMask.asArray();
  58730. serializationObject.customShader = this.customShader;
  58731. serializationObject.preventAutoStart = this.preventAutoStart;
  58732. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  58733. return serializationObject;
  58734. };
  58735. /** @hidden */
  58736. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  58737. serializationObject.name = particleSystem.name;
  58738. serializationObject.id = particleSystem.id;
  58739. serializationObject.capacity = particleSystem.getCapacity();
  58740. // Emitter
  58741. if (particleSystem.emitter.position) {
  58742. var emitterMesh = particleSystem.emitter;
  58743. serializationObject.emitterId = emitterMesh.id;
  58744. }
  58745. else {
  58746. var emitterPosition = particleSystem.emitter;
  58747. serializationObject.emitter = emitterPosition.asArray();
  58748. }
  58749. // Emitter
  58750. if (particleSystem.particleEmitterType) {
  58751. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  58752. }
  58753. if (particleSystem.particleTexture) {
  58754. serializationObject.textureName = particleSystem.particleTexture.name;
  58755. }
  58756. // Animations
  58757. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  58758. // Particle system
  58759. serializationObject.startDelay = particleSystem.startDelay;
  58760. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  58761. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  58762. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  58763. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  58764. serializationObject.minSize = particleSystem.minSize;
  58765. serializationObject.maxSize = particleSystem.maxSize;
  58766. serializationObject.minScaleX = particleSystem.minScaleX;
  58767. serializationObject.maxScaleX = particleSystem.maxScaleX;
  58768. serializationObject.minScaleY = particleSystem.minScaleY;
  58769. serializationObject.maxScaleY = particleSystem.maxScaleY;
  58770. serializationObject.minEmitPower = particleSystem.minEmitPower;
  58771. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  58772. serializationObject.minLifeTime = particleSystem.minLifeTime;
  58773. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  58774. serializationObject.emitRate = particleSystem.emitRate;
  58775. serializationObject.gravity = particleSystem.gravity.asArray();
  58776. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  58777. serializationObject.color1 = particleSystem.color1.asArray();
  58778. serializationObject.color2 = particleSystem.color2.asArray();
  58779. serializationObject.colorDead = particleSystem.colorDead.asArray();
  58780. serializationObject.updateSpeed = particleSystem.updateSpeed;
  58781. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  58782. serializationObject.blendMode = particleSystem.blendMode;
  58783. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  58784. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  58785. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  58786. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  58787. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  58788. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  58789. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  58790. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  58791. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  58792. var colorGradients = particleSystem.getColorGradients();
  58793. if (colorGradients) {
  58794. serializationObject.colorGradients = [];
  58795. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  58796. var colorGradient = colorGradients_1[_i];
  58797. var serializedGradient = {
  58798. gradient: colorGradient.gradient,
  58799. color1: colorGradient.color1.asArray()
  58800. };
  58801. if (colorGradient.color2) {
  58802. serializedGradient.color2 = colorGradient.color2.asArray();
  58803. }
  58804. serializationObject.colorGradients.push(serializedGradient);
  58805. }
  58806. }
  58807. var rampGradients = particleSystem.getRampGradients();
  58808. if (rampGradients) {
  58809. serializationObject.rampGradients = [];
  58810. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  58811. var rampGradient = rampGradients_1[_a];
  58812. var serializedGradient = {
  58813. gradient: rampGradient.gradient,
  58814. color: rampGradient.color.asArray()
  58815. };
  58816. serializationObject.rampGradients.push(serializedGradient);
  58817. }
  58818. }
  58819. var colorRemapGradients = particleSystem.getColorRemapGradients();
  58820. if (colorRemapGradients) {
  58821. serializationObject.colorRemapGradients = [];
  58822. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  58823. var colorRemapGradient = colorRemapGradients_1[_b];
  58824. var serializedGradient = {
  58825. gradient: colorRemapGradient.gradient,
  58826. factor1: colorRemapGradient.factor1
  58827. };
  58828. if (colorRemapGradient.factor2 !== undefined) {
  58829. serializedGradient.factor2 = colorRemapGradient.factor2;
  58830. }
  58831. serializationObject.colorRemapGradients.push(serializedGradient);
  58832. }
  58833. }
  58834. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  58835. if (alphaRemapGradients) {
  58836. serializationObject.alphaRemapGradients = [];
  58837. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  58838. var alphaRemapGradient = alphaRemapGradients_1[_c];
  58839. var serializedGradient = {
  58840. gradient: alphaRemapGradient.gradient,
  58841. factor1: alphaRemapGradient.factor1
  58842. };
  58843. if (alphaRemapGradient.factor2 !== undefined) {
  58844. serializedGradient.factor2 = alphaRemapGradient.factor2;
  58845. }
  58846. serializationObject.alphaRemapGradients.push(serializedGradient);
  58847. }
  58848. }
  58849. var sizeGradients = particleSystem.getSizeGradients();
  58850. if (sizeGradients) {
  58851. serializationObject.sizeGradients = [];
  58852. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  58853. var sizeGradient = sizeGradients_1[_d];
  58854. var serializedGradient = {
  58855. gradient: sizeGradient.gradient,
  58856. factor1: sizeGradient.factor1
  58857. };
  58858. if (sizeGradient.factor2 !== undefined) {
  58859. serializedGradient.factor2 = sizeGradient.factor2;
  58860. }
  58861. serializationObject.sizeGradients.push(serializedGradient);
  58862. }
  58863. }
  58864. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  58865. if (angularSpeedGradients) {
  58866. serializationObject.angularSpeedGradients = [];
  58867. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  58868. var angularSpeedGradient = angularSpeedGradients_1[_e];
  58869. var serializedGradient = {
  58870. gradient: angularSpeedGradient.gradient,
  58871. factor1: angularSpeedGradient.factor1
  58872. };
  58873. if (angularSpeedGradient.factor2 !== undefined) {
  58874. serializedGradient.factor2 = angularSpeedGradient.factor2;
  58875. }
  58876. serializationObject.angularSpeedGradients.push(serializedGradient);
  58877. }
  58878. }
  58879. var velocityGradients = particleSystem.getVelocityGradients();
  58880. if (velocityGradients) {
  58881. serializationObject.velocityGradients = [];
  58882. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  58883. var velocityGradient = velocityGradients_1[_f];
  58884. var serializedGradient = {
  58885. gradient: velocityGradient.gradient,
  58886. factor1: velocityGradient.factor1
  58887. };
  58888. if (velocityGradient.factor2 !== undefined) {
  58889. serializedGradient.factor2 = velocityGradient.factor2;
  58890. }
  58891. serializationObject.velocityGradients.push(serializedGradient);
  58892. }
  58893. }
  58894. var dragGradients = particleSystem.getDragGradients();
  58895. if (dragGradients) {
  58896. serializationObject.dragyGradients = [];
  58897. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  58898. var dragGradient = dragGradients_1[_g];
  58899. var serializedGradient = {
  58900. gradient: dragGradient.gradient,
  58901. factor1: dragGradient.factor1
  58902. };
  58903. if (dragGradient.factor2 !== undefined) {
  58904. serializedGradient.factor2 = dragGradient.factor2;
  58905. }
  58906. serializationObject.dragGradients.push(serializedGradient);
  58907. }
  58908. }
  58909. var emitRateGradients = particleSystem.getEmitRateGradients();
  58910. if (emitRateGradients) {
  58911. serializationObject.emitRateGradients = [];
  58912. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  58913. var emitRateGradient = emitRateGradients_1[_h];
  58914. var serializedGradient = {
  58915. gradient: emitRateGradient.gradient,
  58916. factor1: emitRateGradient.factor1
  58917. };
  58918. if (emitRateGradient.factor2 !== undefined) {
  58919. serializedGradient.factor2 = emitRateGradient.factor2;
  58920. }
  58921. serializationObject.emitRateGradients.push(serializedGradient);
  58922. }
  58923. }
  58924. var startSizeGradients = particleSystem.getStartSizeGradients();
  58925. if (startSizeGradients) {
  58926. serializationObject.startSizeGradients = [];
  58927. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  58928. var startSizeGradient = startSizeGradients_1[_j];
  58929. var serializedGradient = {
  58930. gradient: startSizeGradient.gradient,
  58931. factor1: startSizeGradient.factor1
  58932. };
  58933. if (startSizeGradient.factor2 !== undefined) {
  58934. serializedGradient.factor2 = startSizeGradient.factor2;
  58935. }
  58936. serializationObject.startSizeGradients.push(serializedGradient);
  58937. }
  58938. }
  58939. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  58940. if (limitVelocityGradients) {
  58941. serializationObject.limitVelocityGradients = [];
  58942. for (var _k = 0, limitVelocityGradients_1 = limitVelocityGradients; _k < limitVelocityGradients_1.length; _k++) {
  58943. var limitVelocityGradient = limitVelocityGradients_1[_k];
  58944. var serializedGradient = {
  58945. gradient: limitVelocityGradient.gradient,
  58946. factor1: limitVelocityGradient.factor1
  58947. };
  58948. if (limitVelocityGradient.factor2 !== undefined) {
  58949. serializedGradient.factor2 = limitVelocityGradient.factor2;
  58950. }
  58951. serializationObject.limitVelocityGradients.push(serializedGradient);
  58952. }
  58953. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  58954. }
  58955. if (particleSystem.noiseTexture) {
  58956. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  58957. }
  58958. };
  58959. /** @hidden */
  58960. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  58961. // Texture
  58962. if (parsedParticleSystem.textureName) {
  58963. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  58964. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  58965. }
  58966. // Emitter
  58967. if (parsedParticleSystem.emitterId === undefined) {
  58968. particleSystem.emitter = BABYLON.Vector3.Zero();
  58969. }
  58970. else if (parsedParticleSystem.emitterId) {
  58971. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  58972. }
  58973. else {
  58974. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  58975. }
  58976. // Misc.
  58977. if (parsedParticleSystem.renderingGroupId !== undefined) {
  58978. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  58979. }
  58980. if (parsedParticleSystem.isBillboardBased !== undefined) {
  58981. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  58982. }
  58983. // Animations
  58984. if (parsedParticleSystem.animations) {
  58985. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  58986. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  58987. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58988. }
  58989. }
  58990. if (parsedParticleSystem.autoAnimate) {
  58991. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  58992. }
  58993. // Particle system
  58994. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  58995. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  58996. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  58997. particleSystem.minSize = parsedParticleSystem.minSize;
  58998. particleSystem.maxSize = parsedParticleSystem.maxSize;
  58999. if (parsedParticleSystem.minScaleX) {
  59000. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  59001. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  59002. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  59003. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  59004. }
  59005. if (parsedParticleSystem.preWarmCycles !== undefined) {
  59006. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  59007. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  59008. }
  59009. if (parsedParticleSystem.minInitialRotation !== undefined) {
  59010. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  59011. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  59012. }
  59013. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  59014. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  59015. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  59016. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  59017. particleSystem.emitRate = parsedParticleSystem.emitRate;
  59018. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  59019. if (parsedParticleSystem.noiseStrength) {
  59020. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  59021. }
  59022. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  59023. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  59024. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  59025. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  59026. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  59027. particleSystem.blendMode = parsedParticleSystem.blendMode;
  59028. if (parsedParticleSystem.colorGradients) {
  59029. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  59030. var colorGradient = _a[_i];
  59031. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  59032. }
  59033. }
  59034. if (parsedParticleSystem.rampGradients) {
  59035. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  59036. var rampGradient = _c[_b];
  59037. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color1));
  59038. }
  59039. }
  59040. if (parsedParticleSystem.colorRemapGradients) {
  59041. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  59042. var colorRemapGradient = _e[_d];
  59043. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  59044. }
  59045. }
  59046. if (parsedParticleSystem.alphaRemapGradients) {
  59047. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  59048. var alphaRemapGradient = _g[_f];
  59049. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  59050. }
  59051. }
  59052. if (parsedParticleSystem.sizeGradients) {
  59053. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  59054. var sizeGradient = _j[_h];
  59055. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59056. }
  59057. }
  59058. if (parsedParticleSystem.sizeGradients) {
  59059. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  59060. var sizeGradient = _l[_k];
  59061. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  59062. }
  59063. }
  59064. if (parsedParticleSystem.angularSpeedGradients) {
  59065. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  59066. var angularSpeedGradient = _o[_m];
  59067. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  59068. }
  59069. }
  59070. if (parsedParticleSystem.velocityGradients) {
  59071. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  59072. var velocityGradient = _q[_p];
  59073. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  59074. }
  59075. }
  59076. if (parsedParticleSystem.dragGradients) {
  59077. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  59078. var dragGradient = _s[_r];
  59079. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  59080. }
  59081. }
  59082. if (parsedParticleSystem.emitRateGradients) {
  59083. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  59084. var emitRateGradient = _u[_t];
  59085. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  59086. }
  59087. }
  59088. if (parsedParticleSystem.startSizeGradients) {
  59089. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  59090. var startSizeGradient = _w[_v];
  59091. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  59092. }
  59093. }
  59094. if (parsedParticleSystem.limitVelocityGradients) {
  59095. for (var _x = 0, _y = parsedParticleSystem.limitVelocityGradients; _x < _y.length; _x++) {
  59096. var limitVelocityGradient = _y[_x];
  59097. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  59098. }
  59099. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  59100. }
  59101. if (parsedParticleSystem.noiseTexture) {
  59102. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  59103. }
  59104. // Emitter
  59105. var emitterType;
  59106. if (parsedParticleSystem.particleEmitterType) {
  59107. switch (parsedParticleSystem.particleEmitterType.type) {
  59108. case "SphereParticleEmitter":
  59109. emitterType = new BABYLON.SphereParticleEmitter();
  59110. break;
  59111. case "SphereDirectedParticleEmitter":
  59112. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  59113. break;
  59114. case "ConeEmitter":
  59115. case "ConeParticleEmitter":
  59116. emitterType = new BABYLON.ConeParticleEmitter();
  59117. break;
  59118. case "BoxEmitter":
  59119. case "BoxParticleEmitter":
  59120. default:
  59121. emitterType = new BABYLON.BoxParticleEmitter();
  59122. break;
  59123. }
  59124. emitterType.parse(parsedParticleSystem.particleEmitterType);
  59125. }
  59126. else {
  59127. emitterType = new BABYLON.BoxParticleEmitter();
  59128. emitterType.parse(parsedParticleSystem);
  59129. }
  59130. particleSystem.particleEmitterType = emitterType;
  59131. // Animation sheet
  59132. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  59133. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  59134. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  59135. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  59136. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  59137. };
  59138. /**
  59139. * Parses a JSON object to create a particle system.
  59140. * @param parsedParticleSystem The JSON object to parse
  59141. * @param scene The scene to create the particle system in
  59142. * @param rootUrl The root url to use to load external dependencies like texture
  59143. * @returns the Parsed particle system
  59144. */
  59145. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  59146. var name = parsedParticleSystem.name;
  59147. var custom = null;
  59148. var program = null;
  59149. if (parsedParticleSystem.customShader) {
  59150. program = parsedParticleSystem.customShader;
  59151. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  59152. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  59153. }
  59154. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  59155. particleSystem.customShader = program;
  59156. if (parsedParticleSystem.id) {
  59157. particleSystem.id = parsedParticleSystem.id;
  59158. }
  59159. // Auto start
  59160. if (parsedParticleSystem.preventAutoStart) {
  59161. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  59162. }
  59163. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  59164. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  59165. if (!particleSystem.preventAutoStart) {
  59166. particleSystem.start();
  59167. }
  59168. return particleSystem;
  59169. };
  59170. /**
  59171. * Billboard mode will only apply to Y axis
  59172. */
  59173. ParticleSystem.BILLBOARDMODE_Y = 2;
  59174. /**
  59175. * Billboard mode will apply to all axes
  59176. */
  59177. ParticleSystem.BILLBOARDMODE_ALL = 7;
  59178. /**
  59179. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  59180. */
  59181. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  59182. return ParticleSystem;
  59183. }(BABYLON.BaseParticleSystem));
  59184. BABYLON.ParticleSystem = ParticleSystem;
  59185. })(BABYLON || (BABYLON = {}));
  59186. //# sourceMappingURL=babylon.particleSystem.js.map
  59187. var BABYLON;
  59188. (function (BABYLON) {
  59189. /**
  59190. * Particle emitter emitting particles from the inside of a box.
  59191. * It emits the particles randomly between 2 given directions.
  59192. */
  59193. var BoxParticleEmitter = /** @class */ (function () {
  59194. /**
  59195. * Creates a new instance BoxParticleEmitter
  59196. */
  59197. function BoxParticleEmitter() {
  59198. /**
  59199. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59200. */
  59201. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  59202. /**
  59203. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  59204. */
  59205. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  59206. /**
  59207. * 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.
  59208. */
  59209. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  59210. /**
  59211. * 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.
  59212. */
  59213. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  59214. }
  59215. /**
  59216. * Called by the particle System when the direction is computed for the created particle.
  59217. * @param worldMatrix is the world matrix of the particle system
  59218. * @param directionToUpdate is the direction vector to update with the result
  59219. * @param particle is the particle we are computed the direction for
  59220. */
  59221. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59222. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59223. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59224. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59225. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59226. };
  59227. /**
  59228. * Called by the particle System when the position is computed for the created particle.
  59229. * @param worldMatrix is the world matrix of the particle system
  59230. * @param positionToUpdate is the position vector to update with the result
  59231. * @param particle is the particle we are computed the position for
  59232. */
  59233. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59234. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  59235. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  59236. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  59237. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59238. };
  59239. /**
  59240. * Clones the current emitter and returns a copy of it
  59241. * @returns the new emitter
  59242. */
  59243. BoxParticleEmitter.prototype.clone = function () {
  59244. var newOne = new BoxParticleEmitter();
  59245. BABYLON.Tools.DeepCopy(this, newOne);
  59246. return newOne;
  59247. };
  59248. /**
  59249. * Called by the GPUParticleSystem to setup the update shader
  59250. * @param effect defines the update shader
  59251. */
  59252. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  59253. effect.setVector3("direction1", this.direction1);
  59254. effect.setVector3("direction2", this.direction2);
  59255. effect.setVector3("minEmitBox", this.minEmitBox);
  59256. effect.setVector3("maxEmitBox", this.maxEmitBox);
  59257. };
  59258. /**
  59259. * Returns a string to use to update the GPU particles update shader
  59260. * @returns a string containng the defines string
  59261. */
  59262. BoxParticleEmitter.prototype.getEffectDefines = function () {
  59263. return "#define BOXEMITTER";
  59264. };
  59265. /**
  59266. * Returns the string "BoxParticleEmitter"
  59267. * @returns a string containing the class name
  59268. */
  59269. BoxParticleEmitter.prototype.getClassName = function () {
  59270. return "BoxParticleEmitter";
  59271. };
  59272. /**
  59273. * Serializes the particle system to a JSON object.
  59274. * @returns the JSON object
  59275. */
  59276. BoxParticleEmitter.prototype.serialize = function () {
  59277. var serializationObject = {};
  59278. serializationObject.type = this.getClassName();
  59279. serializationObject.direction1 = this.direction1.asArray();
  59280. serializationObject.direction2 = this.direction2.asArray();
  59281. serializationObject.minEmitBox = this.minEmitBox.asArray();
  59282. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  59283. return serializationObject;
  59284. };
  59285. /**
  59286. * Parse properties from a JSON object
  59287. * @param serializationObject defines the JSON object
  59288. */
  59289. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  59290. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  59291. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  59292. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  59293. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  59294. };
  59295. return BoxParticleEmitter;
  59296. }());
  59297. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  59298. })(BABYLON || (BABYLON = {}));
  59299. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  59300. var BABYLON;
  59301. (function (BABYLON) {
  59302. /**
  59303. * Particle emitter emitting particles from the inside of a cylinder.
  59304. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  59305. */
  59306. var CylinderParticleEmitter = /** @class */ (function () {
  59307. /**
  59308. * Creates a new instance CylinderParticleEmitter
  59309. * @param radius the radius of the emission cylinder (1 by default)
  59310. * @param height the height of the emission cylinder (1 by default)
  59311. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59312. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59313. */
  59314. function CylinderParticleEmitter(
  59315. /**
  59316. * The radius of the emission cylinder.
  59317. */
  59318. radius,
  59319. /**
  59320. * The height of the emission cylinder.
  59321. */
  59322. height,
  59323. /**
  59324. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59325. */
  59326. radiusRange,
  59327. /**
  59328. * How much to randomize the particle direction [0-1].
  59329. */
  59330. directionRandomizer) {
  59331. if (radius === void 0) { radius = 1; }
  59332. if (height === void 0) { height = 1; }
  59333. if (radiusRange === void 0) { radiusRange = 1; }
  59334. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59335. this.radius = radius;
  59336. this.height = height;
  59337. this.radiusRange = radiusRange;
  59338. this.directionRandomizer = directionRandomizer;
  59339. }
  59340. /**
  59341. * Called by the particle System when the direction is computed for the created particle.
  59342. * @param worldMatrix is the world matrix of the particle system
  59343. * @param directionToUpdate is the direction vector to update with the result
  59344. * @param particle is the particle we are computed the direction for
  59345. */
  59346. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59347. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59348. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  59349. var angle = Math.atan2(direction.x, direction.z);
  59350. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  59351. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  59352. direction.x = Math.sin(angle);
  59353. direction.z = Math.cos(angle);
  59354. direction.normalize();
  59355. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59356. };
  59357. /**
  59358. * Called by the particle System when the position is computed for the created particle.
  59359. * @param worldMatrix is the world matrix of the particle system
  59360. * @param positionToUpdate is the position vector to update with the result
  59361. * @param particle is the particle we are computed the position for
  59362. */
  59363. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59364. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  59365. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59366. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  59367. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  59368. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  59369. var xPos = positionRadius * Math.cos(angle);
  59370. var zPos = positionRadius * Math.sin(angle);
  59371. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  59372. };
  59373. /**
  59374. * Clones the current emitter and returns a copy of it
  59375. * @returns the new emitter
  59376. */
  59377. CylinderParticleEmitter.prototype.clone = function () {
  59378. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  59379. BABYLON.Tools.DeepCopy(this, newOne);
  59380. return newOne;
  59381. };
  59382. /**
  59383. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59384. * @param effect defines the update shader
  59385. */
  59386. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  59387. effect.setFloat("radius", this.radius);
  59388. effect.setFloat("height", this.height);
  59389. effect.setFloat("radiusRange", this.radiusRange);
  59390. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59391. };
  59392. /**
  59393. * Returns a string to use to update the GPU particles update shader
  59394. * @returns a string containng the defines string
  59395. */
  59396. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  59397. return "#define CYLINDEREMITTER";
  59398. };
  59399. /**
  59400. * Returns the string "CylinderParticleEmitter"
  59401. * @returns a string containing the class name
  59402. */
  59403. CylinderParticleEmitter.prototype.getClassName = function () {
  59404. return "CylinderParticleEmitter";
  59405. };
  59406. /**
  59407. * Serializes the particle system to a JSON object.
  59408. * @returns the JSON object
  59409. */
  59410. CylinderParticleEmitter.prototype.serialize = function () {
  59411. var serializationObject = {};
  59412. serializationObject.type = this.getClassName();
  59413. serializationObject.radius = this.radius;
  59414. serializationObject.height = this.height;
  59415. serializationObject.radiusRange = this.radiusRange;
  59416. serializationObject.directionRandomizer = this.directionRandomizer;
  59417. return serializationObject;
  59418. };
  59419. /**
  59420. * Parse properties from a JSON object
  59421. * @param serializationObject defines the JSON object
  59422. */
  59423. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  59424. this.radius = serializationObject.radius;
  59425. this.height = serializationObject.height;
  59426. this.radiusRange = serializationObject.radiusRange;
  59427. this.directionRandomizer = serializationObject.directionRandomizer;
  59428. };
  59429. return CylinderParticleEmitter;
  59430. }());
  59431. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  59432. /**
  59433. * Particle emitter emitting particles from the inside of a cylinder.
  59434. * It emits the particles randomly between two vectors.
  59435. */
  59436. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  59437. __extends(CylinderDirectedParticleEmitter, _super);
  59438. /**
  59439. * Creates a new instance CylinderDirectedParticleEmitter
  59440. * @param radius the radius of the emission cylinder (1 by default)
  59441. * @param height the height of the emission cylinder (1 by default)
  59442. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59443. * @param direction1 the min limit of the emission direction (up vector by default)
  59444. * @param direction2 the max limit of the emission direction (up vector by default)
  59445. */
  59446. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  59447. /**
  59448. * The min limit of the emission direction.
  59449. */
  59450. direction1,
  59451. /**
  59452. * The max limit of the emission direction.
  59453. */
  59454. direction2) {
  59455. if (radius === void 0) { radius = 1; }
  59456. if (height === void 0) { height = 1; }
  59457. if (radiusRange === void 0) { radiusRange = 1; }
  59458. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59459. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59460. var _this = _super.call(this, radius, height, radiusRange) || this;
  59461. _this.direction1 = direction1;
  59462. _this.direction2 = direction2;
  59463. return _this;
  59464. }
  59465. /**
  59466. * Called by the particle System when the direction is computed for the created particle.
  59467. * @param worldMatrix is the world matrix of the particle system
  59468. * @param directionToUpdate is the direction vector to update with the result
  59469. * @param particle is the particle we are computed the direction for
  59470. */
  59471. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59472. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59473. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59474. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59475. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59476. };
  59477. /**
  59478. * Clones the current emitter and returns a copy of it
  59479. * @returns the new emitter
  59480. */
  59481. CylinderDirectedParticleEmitter.prototype.clone = function () {
  59482. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  59483. BABYLON.Tools.DeepCopy(this, newOne);
  59484. return newOne;
  59485. };
  59486. /**
  59487. * Called by the GPUParticleSystem to setup the update shader
  59488. * @param effect defines the update shader
  59489. */
  59490. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59491. effect.setFloat("radius", this.radius);
  59492. effect.setFloat("height", this.height);
  59493. effect.setFloat("radiusRange", this.radiusRange);
  59494. effect.setVector3("direction1", this.direction1);
  59495. effect.setVector3("direction2", this.direction2);
  59496. };
  59497. /**
  59498. * Returns a string to use to update the GPU particles update shader
  59499. * @returns a string containng the defines string
  59500. */
  59501. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59502. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  59503. };
  59504. /**
  59505. * Returns the string "CylinderDirectedParticleEmitter"
  59506. * @returns a string containing the class name
  59507. */
  59508. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  59509. return "CylinderDirectedParticleEmitter";
  59510. };
  59511. /**
  59512. * Serializes the particle system to a JSON object.
  59513. * @returns the JSON object
  59514. */
  59515. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  59516. var serializationObject = _super.prototype.serialize.call(this);
  59517. serializationObject.direction1 = this.direction1.asArray();
  59518. serializationObject.direction2 = this.direction2.asArray();
  59519. return serializationObject;
  59520. };
  59521. /**
  59522. * Parse properties from a JSON object
  59523. * @param serializationObject defines the JSON object
  59524. */
  59525. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59526. _super.prototype.parse.call(this, serializationObject);
  59527. this.direction1.copyFrom(serializationObject.direction1);
  59528. this.direction2.copyFrom(serializationObject.direction2);
  59529. };
  59530. return CylinderDirectedParticleEmitter;
  59531. }(CylinderParticleEmitter));
  59532. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  59533. })(BABYLON || (BABYLON = {}));
  59534. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  59535. var BABYLON;
  59536. (function (BABYLON) {
  59537. /**
  59538. * Particle emitter emitting particles from the inside of a cone.
  59539. * It emits the particles alongside the cone volume from the base to the particle.
  59540. * The emission direction might be randomized.
  59541. */
  59542. var ConeParticleEmitter = /** @class */ (function () {
  59543. /**
  59544. * Creates a new instance ConeParticleEmitter
  59545. * @param radius the radius of the emission cone (1 by default)
  59546. * @param angles the cone base angle (PI by default)
  59547. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  59548. */
  59549. function ConeParticleEmitter(radius, angle,
  59550. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  59551. directionRandomizer) {
  59552. if (radius === void 0) { radius = 1; }
  59553. if (angle === void 0) { angle = Math.PI; }
  59554. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59555. this.directionRandomizer = directionRandomizer;
  59556. /**
  59557. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  59558. */
  59559. this.radiusRange = 1;
  59560. /**
  59561. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  59562. */
  59563. this.heightRange = 1;
  59564. /**
  59565. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  59566. */
  59567. this.emitFromSpawnPointOnly = false;
  59568. this.angle = angle;
  59569. this.radius = radius;
  59570. }
  59571. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  59572. /**
  59573. * Gets or sets the radius of the emission cone
  59574. */
  59575. get: function () {
  59576. return this._radius;
  59577. },
  59578. set: function (value) {
  59579. this._radius = value;
  59580. this._buildHeight();
  59581. },
  59582. enumerable: true,
  59583. configurable: true
  59584. });
  59585. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  59586. /**
  59587. * Gets or sets the angle of the emission cone
  59588. */
  59589. get: function () {
  59590. return this._angle;
  59591. },
  59592. set: function (value) {
  59593. this._angle = value;
  59594. this._buildHeight();
  59595. },
  59596. enumerable: true,
  59597. configurable: true
  59598. });
  59599. ConeParticleEmitter.prototype._buildHeight = function () {
  59600. if (this._angle !== 0) {
  59601. this._height = this._radius / Math.tan(this._angle / 2);
  59602. }
  59603. else {
  59604. this._height = 1;
  59605. }
  59606. };
  59607. /**
  59608. * Called by the particle System when the direction is computed for the created particle.
  59609. * @param worldMatrix is the world matrix of the particle system
  59610. * @param directionToUpdate is the direction vector to update with the result
  59611. * @param particle is the particle we are computed the direction for
  59612. */
  59613. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59614. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  59615. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  59616. }
  59617. else {
  59618. // measure the direction Vector from the emitter to the particle.
  59619. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59620. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59621. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59622. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59623. direction.x += randX;
  59624. direction.y += randY;
  59625. direction.z += randZ;
  59626. direction.normalize();
  59627. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59628. }
  59629. };
  59630. /**
  59631. * Called by the particle System when the position is computed for the created particle.
  59632. * @param worldMatrix is the world matrix of the particle system
  59633. * @param positionToUpdate is the position vector to update with the result
  59634. * @param particle is the particle we are computed the position for
  59635. */
  59636. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59637. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  59638. var h;
  59639. if (!this.emitFromSpawnPointOnly) {
  59640. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  59641. // Better distribution in a cone at normal angles.
  59642. h = 1 - h * h;
  59643. }
  59644. else {
  59645. h = 0.0001;
  59646. }
  59647. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  59648. radius = radius * h;
  59649. var randX = radius * Math.sin(s);
  59650. var randZ = radius * Math.cos(s);
  59651. var randY = h * this._height;
  59652. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59653. };
  59654. /**
  59655. * Clones the current emitter and returns a copy of it
  59656. * @returns the new emitter
  59657. */
  59658. ConeParticleEmitter.prototype.clone = function () {
  59659. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  59660. BABYLON.Tools.DeepCopy(this, newOne);
  59661. return newOne;
  59662. };
  59663. /**
  59664. * Called by the GPUParticleSystem to setup the update shader
  59665. * @param effect defines the update shader
  59666. */
  59667. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  59668. effect.setFloat2("radius", this._radius, this.radiusRange);
  59669. effect.setFloat("coneAngle", this._angle);
  59670. effect.setFloat2("height", this._height, this.heightRange);
  59671. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59672. };
  59673. /**
  59674. * Returns a string to use to update the GPU particles update shader
  59675. * @returns a string containng the defines string
  59676. */
  59677. ConeParticleEmitter.prototype.getEffectDefines = function () {
  59678. var defines = "#define CONEEMITTER";
  59679. if (this.emitFromSpawnPointOnly) {
  59680. defines += "\n#define CONEEMITTERSPAWNPOINT";
  59681. }
  59682. return defines;
  59683. };
  59684. /**
  59685. * Returns the string "ConeParticleEmitter"
  59686. * @returns a string containing the class name
  59687. */
  59688. ConeParticleEmitter.prototype.getClassName = function () {
  59689. return "ConeParticleEmitter";
  59690. };
  59691. /**
  59692. * Serializes the particle system to a JSON object.
  59693. * @returns the JSON object
  59694. */
  59695. ConeParticleEmitter.prototype.serialize = function () {
  59696. var serializationObject = {};
  59697. serializationObject.type = this.getClassName();
  59698. serializationObject.radius = this._radius;
  59699. serializationObject.angle = this._angle;
  59700. serializationObject.directionRandomizer = this.directionRandomizer;
  59701. return serializationObject;
  59702. };
  59703. /**
  59704. * Parse properties from a JSON object
  59705. * @param serializationObject defines the JSON object
  59706. */
  59707. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  59708. this.radius = serializationObject.radius;
  59709. this.angle = serializationObject.angle;
  59710. this.directionRandomizer = serializationObject.directionRandomizer;
  59711. };
  59712. return ConeParticleEmitter;
  59713. }());
  59714. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  59715. })(BABYLON || (BABYLON = {}));
  59716. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  59717. var BABYLON;
  59718. (function (BABYLON) {
  59719. /**
  59720. * Particle emitter emitting particles from the inside of a sphere.
  59721. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  59722. */
  59723. var SphereParticleEmitter = /** @class */ (function () {
  59724. /**
  59725. * Creates a new instance SphereParticleEmitter
  59726. * @param radius the radius of the emission sphere (1 by default)
  59727. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59728. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59729. */
  59730. function SphereParticleEmitter(
  59731. /**
  59732. * The radius of the emission sphere.
  59733. */
  59734. radius,
  59735. /**
  59736. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59737. */
  59738. radiusRange,
  59739. /**
  59740. * How much to randomize the particle direction [0-1].
  59741. */
  59742. directionRandomizer) {
  59743. if (radius === void 0) { radius = 1; }
  59744. if (radiusRange === void 0) { radiusRange = 1; }
  59745. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59746. this.radius = radius;
  59747. this.radiusRange = radiusRange;
  59748. this.directionRandomizer = directionRandomizer;
  59749. }
  59750. /**
  59751. * Called by the particle System when the direction is computed for the created particle.
  59752. * @param worldMatrix is the world matrix of the particle system
  59753. * @param directionToUpdate is the direction vector to update with the result
  59754. * @param particle is the particle we are computed the direction for
  59755. */
  59756. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59757. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59758. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59759. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59760. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59761. direction.x += randX;
  59762. direction.y += randY;
  59763. direction.z += randZ;
  59764. direction.normalize();
  59765. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59766. };
  59767. /**
  59768. * Called by the particle System when the position is computed for the created particle.
  59769. * @param worldMatrix is the world matrix of the particle system
  59770. * @param positionToUpdate is the position vector to update with the result
  59771. * @param particle is the particle we are computed the position for
  59772. */
  59773. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59774. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59775. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59776. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59777. var theta = Math.acos(2 * v - 1);
  59778. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59779. var randY = randRadius * Math.cos(theta);
  59780. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  59781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  59782. };
  59783. /**
  59784. * Clones the current emitter and returns a copy of it
  59785. * @returns the new emitter
  59786. */
  59787. SphereParticleEmitter.prototype.clone = function () {
  59788. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  59789. BABYLON.Tools.DeepCopy(this, newOne);
  59790. return newOne;
  59791. };
  59792. /**
  59793. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  59794. * @param effect defines the update shader
  59795. */
  59796. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  59797. effect.setFloat("radius", this.radius);
  59798. effect.setFloat("radiusRange", this.radiusRange);
  59799. effect.setFloat("directionRandomizer", this.directionRandomizer);
  59800. };
  59801. /**
  59802. * Returns a string to use to update the GPU particles update shader
  59803. * @returns a string containng the defines string
  59804. */
  59805. SphereParticleEmitter.prototype.getEffectDefines = function () {
  59806. return "#define SPHEREEMITTER";
  59807. };
  59808. /**
  59809. * Returns the string "SphereParticleEmitter"
  59810. * @returns a string containing the class name
  59811. */
  59812. SphereParticleEmitter.prototype.getClassName = function () {
  59813. return "SphereParticleEmitter";
  59814. };
  59815. /**
  59816. * Serializes the particle system to a JSON object.
  59817. * @returns the JSON object
  59818. */
  59819. SphereParticleEmitter.prototype.serialize = function () {
  59820. var serializationObject = {};
  59821. serializationObject.type = this.getClassName();
  59822. serializationObject.radius = this.radius;
  59823. serializationObject.radiusRange = this.radiusRange;
  59824. serializationObject.directionRandomizer = this.directionRandomizer;
  59825. return serializationObject;
  59826. };
  59827. /**
  59828. * Parse properties from a JSON object
  59829. * @param serializationObject defines the JSON object
  59830. */
  59831. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  59832. this.radius = serializationObject.radius;
  59833. this.radiusRange = serializationObject.radiusRange;
  59834. this.directionRandomizer = serializationObject.directionRandomizer;
  59835. };
  59836. return SphereParticleEmitter;
  59837. }());
  59838. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  59839. /**
  59840. * Particle emitter emitting particles from the inside of a sphere.
  59841. * It emits the particles randomly between two vectors.
  59842. */
  59843. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  59844. __extends(SphereDirectedParticleEmitter, _super);
  59845. /**
  59846. * Creates a new instance SphereDirectedParticleEmitter
  59847. * @param radius the radius of the emission sphere (1 by default)
  59848. * @param direction1 the min limit of the emission direction (up vector by default)
  59849. * @param direction2 the max limit of the emission direction (up vector by default)
  59850. */
  59851. function SphereDirectedParticleEmitter(radius,
  59852. /**
  59853. * The min limit of the emission direction.
  59854. */
  59855. direction1,
  59856. /**
  59857. * The max limit of the emission direction.
  59858. */
  59859. direction2) {
  59860. if (radius === void 0) { radius = 1; }
  59861. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  59862. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  59863. var _this = _super.call(this, radius) || this;
  59864. _this.direction1 = direction1;
  59865. _this.direction2 = direction2;
  59866. return _this;
  59867. }
  59868. /**
  59869. * Called by the particle System when the direction is computed for the created particle.
  59870. * @param worldMatrix is the world matrix of the particle system
  59871. * @param directionToUpdate is the direction vector to update with the result
  59872. * @param particle is the particle we are computed the direction for
  59873. */
  59874. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59875. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  59876. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  59877. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  59878. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  59879. };
  59880. /**
  59881. * Clones the current emitter and returns a copy of it
  59882. * @returns the new emitter
  59883. */
  59884. SphereDirectedParticleEmitter.prototype.clone = function () {
  59885. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  59886. BABYLON.Tools.DeepCopy(this, newOne);
  59887. return newOne;
  59888. };
  59889. /**
  59890. * Called by the GPUParticleSystem to setup the update shader
  59891. * @param effect defines the update shader
  59892. */
  59893. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  59894. effect.setFloat("radius", this.radius);
  59895. effect.setFloat("radiusRange", this.radiusRange);
  59896. effect.setVector3("direction1", this.direction1);
  59897. effect.setVector3("direction2", this.direction2);
  59898. };
  59899. /**
  59900. * Returns a string to use to update the GPU particles update shader
  59901. * @returns a string containng the defines string
  59902. */
  59903. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  59904. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  59905. };
  59906. /**
  59907. * Returns the string "SphereDirectedParticleEmitter"
  59908. * @returns a string containing the class name
  59909. */
  59910. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  59911. return "SphereDirectedParticleEmitter";
  59912. };
  59913. /**
  59914. * Serializes the particle system to a JSON object.
  59915. * @returns the JSON object
  59916. */
  59917. SphereDirectedParticleEmitter.prototype.serialize = function () {
  59918. var serializationObject = _super.prototype.serialize.call(this);
  59919. serializationObject.direction1 = this.direction1.asArray();
  59920. serializationObject.direction2 = this.direction2.asArray();
  59921. return serializationObject;
  59922. };
  59923. /**
  59924. * Parse properties from a JSON object
  59925. * @param serializationObject defines the JSON object
  59926. */
  59927. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  59928. _super.prototype.parse.call(this, serializationObject);
  59929. this.direction1.copyFrom(serializationObject.direction1);
  59930. this.direction2.copyFrom(serializationObject.direction2);
  59931. };
  59932. return SphereDirectedParticleEmitter;
  59933. }(SphereParticleEmitter));
  59934. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  59935. })(BABYLON || (BABYLON = {}));
  59936. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  59937. var BABYLON;
  59938. (function (BABYLON) {
  59939. /**
  59940. * Particle emitter emitting particles from the inside of a hemisphere.
  59941. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  59942. */
  59943. var HemisphericParticleEmitter = /** @class */ (function () {
  59944. /**
  59945. * Creates a new instance HemisphericParticleEmitter
  59946. * @param radius the radius of the emission hemisphere (1 by default)
  59947. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  59948. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  59949. */
  59950. function HemisphericParticleEmitter(
  59951. /**
  59952. * The radius of the emission hemisphere.
  59953. */
  59954. radius,
  59955. /**
  59956. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  59957. */
  59958. radiusRange,
  59959. /**
  59960. * How much to randomize the particle direction [0-1].
  59961. */
  59962. directionRandomizer) {
  59963. if (radius === void 0) { radius = 1; }
  59964. if (radiusRange === void 0) { radiusRange = 1; }
  59965. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  59966. this.radius = radius;
  59967. this.radiusRange = radiusRange;
  59968. this.directionRandomizer = directionRandomizer;
  59969. }
  59970. /**
  59971. * Called by the particle System when the direction is computed for the created particle.
  59972. * @param worldMatrix is the world matrix of the particle system
  59973. * @param directionToUpdate is the direction vector to update with the result
  59974. * @param particle is the particle we are computed the direction for
  59975. */
  59976. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  59977. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  59978. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59979. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59980. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  59981. direction.x += randX;
  59982. direction.y += randY;
  59983. direction.z += randZ;
  59984. direction.normalize();
  59985. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  59986. };
  59987. /**
  59988. * Called by the particle System when the position is computed for the created particle.
  59989. * @param worldMatrix is the world matrix of the particle system
  59990. * @param positionToUpdate is the position vector to update with the result
  59991. * @param particle is the particle we are computed the position for
  59992. */
  59993. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  59994. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  59995. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  59996. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  59997. var theta = Math.acos(2 * v - 1);
  59998. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  59999. var randY = randRadius * Math.cos(theta);
  60000. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  60001. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  60002. };
  60003. /**
  60004. * Clones the current emitter and returns a copy of it
  60005. * @returns the new emitter
  60006. */
  60007. HemisphericParticleEmitter.prototype.clone = function () {
  60008. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  60009. BABYLON.Tools.DeepCopy(this, newOne);
  60010. return newOne;
  60011. };
  60012. /**
  60013. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  60014. * @param effect defines the update shader
  60015. */
  60016. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  60017. effect.setFloat("radius", this.radius);
  60018. effect.setFloat("radiusRange", this.radiusRange);
  60019. effect.setFloat("directionRandomizer", this.directionRandomizer);
  60020. };
  60021. /**
  60022. * Returns a string to use to update the GPU particles update shader
  60023. * @returns a string containng the defines string
  60024. */
  60025. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  60026. return "#define HEMISPHERICEMITTER";
  60027. };
  60028. /**
  60029. * Returns the string "HemisphericParticleEmitter"
  60030. * @returns a string containing the class name
  60031. */
  60032. HemisphericParticleEmitter.prototype.getClassName = function () {
  60033. return "HemisphericParticleEmitter";
  60034. };
  60035. /**
  60036. * Serializes the particle system to a JSON object.
  60037. * @returns the JSON object
  60038. */
  60039. HemisphericParticleEmitter.prototype.serialize = function () {
  60040. var serializationObject = {};
  60041. serializationObject.type = this.getClassName();
  60042. serializationObject.radius = this.radius;
  60043. serializationObject.radiusRange = this.radiusRange;
  60044. serializationObject.directionRandomizer = this.directionRandomizer;
  60045. return serializationObject;
  60046. };
  60047. /**
  60048. * Parse properties from a JSON object
  60049. * @param serializationObject defines the JSON object
  60050. */
  60051. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  60052. this.radius = serializationObject.radius;
  60053. this.radiusRange = serializationObject.radiusRange;
  60054. this.directionRandomizer = serializationObject.directionRandomizer;
  60055. };
  60056. return HemisphericParticleEmitter;
  60057. }());
  60058. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  60059. })(BABYLON || (BABYLON = {}));
  60060. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  60061. var BABYLON;
  60062. (function (BABYLON) {
  60063. /**
  60064. * Particle emitter emitting particles from a point.
  60065. * It emits the particles randomly between 2 given directions.
  60066. */
  60067. var PointParticleEmitter = /** @class */ (function () {
  60068. /**
  60069. * Creates a new instance PointParticleEmitter
  60070. */
  60071. function PointParticleEmitter() {
  60072. /**
  60073. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60074. */
  60075. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  60076. /**
  60077. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  60078. */
  60079. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  60080. }
  60081. /**
  60082. * Called by the particle System when the direction is computed for the created particle.
  60083. * @param worldMatrix is the world matrix of the particle system
  60084. * @param directionToUpdate is the direction vector to update with the result
  60085. * @param particle is the particle we are computed the direction for
  60086. */
  60087. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  60088. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  60089. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  60090. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  60091. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  60092. };
  60093. /**
  60094. * Called by the particle System when the position is computed for the created particle.
  60095. * @param worldMatrix is the world matrix of the particle system
  60096. * @param positionToUpdate is the position vector to update with the result
  60097. * @param particle is the particle we are computed the position for
  60098. */
  60099. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  60100. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  60101. };
  60102. /**
  60103. * Clones the current emitter and returns a copy of it
  60104. * @returns the new emitter
  60105. */
  60106. PointParticleEmitter.prototype.clone = function () {
  60107. var newOne = new PointParticleEmitter();
  60108. BABYLON.Tools.DeepCopy(this, newOne);
  60109. return newOne;
  60110. };
  60111. /**
  60112. * Called by the GPUParticleSystem to setup the update shader
  60113. * @param effect defines the update shader
  60114. */
  60115. PointParticleEmitter.prototype.applyToShader = function (effect) {
  60116. effect.setVector3("direction1", this.direction1);
  60117. effect.setVector3("direction2", this.direction2);
  60118. };
  60119. /**
  60120. * Returns a string to use to update the GPU particles update shader
  60121. * @returns a string containng the defines string
  60122. */
  60123. PointParticleEmitter.prototype.getEffectDefines = function () {
  60124. return "#define POINTEMITTER";
  60125. };
  60126. /**
  60127. * Returns the string "PointParticleEmitter"
  60128. * @returns a string containing the class name
  60129. */
  60130. PointParticleEmitter.prototype.getClassName = function () {
  60131. return "PointParticleEmitter";
  60132. };
  60133. /**
  60134. * Serializes the particle system to a JSON object.
  60135. * @returns the JSON object
  60136. */
  60137. PointParticleEmitter.prototype.serialize = function () {
  60138. var serializationObject = {};
  60139. serializationObject.type = this.getClassName();
  60140. serializationObject.direction1 = this.direction1.asArray();
  60141. serializationObject.direction2 = this.direction2.asArray();
  60142. return serializationObject;
  60143. };
  60144. /**
  60145. * Parse properties from a JSON object
  60146. * @param serializationObject defines the JSON object
  60147. */
  60148. PointParticleEmitter.prototype.parse = function (serializationObject) {
  60149. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  60150. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  60151. };
  60152. return PointParticleEmitter;
  60153. }());
  60154. BABYLON.PointParticleEmitter = PointParticleEmitter;
  60155. })(BABYLON || (BABYLON = {}));
  60156. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  60157. var BABYLON;
  60158. (function (BABYLON) {
  60159. // Adds the parsers to the scene parsers.
  60160. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  60161. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  60162. if (!individualParser) {
  60163. return;
  60164. }
  60165. // Particles Systems
  60166. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60167. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60168. var parsedParticleSystem = parsedData.particleSystems[index];
  60169. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  60170. }
  60171. }
  60172. });
  60173. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  60174. if (parsedParticleSystem.activeParticleCount) {
  60175. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60176. return ps;
  60177. }
  60178. else {
  60179. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60180. return ps;
  60181. }
  60182. });
  60183. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  60184. if (uniformsNames === void 0) { uniformsNames = []; }
  60185. if (samplers === void 0) { samplers = []; }
  60186. if (defines === void 0) { defines = ""; }
  60187. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  60188. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  60189. if (defines.indexOf(" BILLBOARD") === -1) {
  60190. defines += "\n#define BILLBOARD\n";
  60191. }
  60192. if (samplers.indexOf("diffuseSampler") === -1) {
  60193. samplers.push("diffuseSampler");
  60194. }
  60195. return this.createEffect({
  60196. vertex: "particles",
  60197. fragmentElement: fragmentName
  60198. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  60199. };
  60200. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  60201. var results = new Array();
  60202. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60203. var particleSystem = this.getScene().particleSystems[index];
  60204. if (particleSystem.emitter === this) {
  60205. results.push(particleSystem);
  60206. }
  60207. }
  60208. return results;
  60209. };
  60210. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  60211. var results = new Array();
  60212. var descendants = this.getDescendants();
  60213. descendants.push(this);
  60214. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  60215. var particleSystem = this.getScene().particleSystems[index];
  60216. var emitter = particleSystem.emitter;
  60217. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  60218. results.push(particleSystem);
  60219. }
  60220. }
  60221. return results;
  60222. };
  60223. })(BABYLON || (BABYLON = {}));
  60224. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  60225. var BABYLON;
  60226. (function (BABYLON) {
  60227. /**
  60228. * Type of sub emitter
  60229. */
  60230. var SubEmitterType;
  60231. (function (SubEmitterType) {
  60232. /**
  60233. * Attached to the particle over it's lifetime
  60234. */
  60235. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  60236. /**
  60237. * Created when the particle dies
  60238. */
  60239. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  60240. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  60241. /**
  60242. * Sub emitter class used to emit particles from an existing particle
  60243. */
  60244. var SubEmitter = /** @class */ (function () {
  60245. /**
  60246. * Creates a sub emitter
  60247. * @param particleSystem the particle system to be used by the sub emitter
  60248. */
  60249. function SubEmitter(
  60250. /**
  60251. * the particle system to be used by the sub emitter
  60252. */
  60253. particleSystem) {
  60254. this.particleSystem = particleSystem;
  60255. /**
  60256. * Type of the submitter (Default: END)
  60257. */
  60258. this.type = SubEmitterType.END;
  60259. /**
  60260. * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
  60261. * Note: This only is supported when using an emitter of type Mesh
  60262. */
  60263. this.inheritDirection = false;
  60264. /**
  60265. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  60266. */
  60267. this.inheritedVelocityAmount = 0;
  60268. }
  60269. /**
  60270. * Clones the sub emitter
  60271. * @returns the cloned sub emitter
  60272. */
  60273. SubEmitter.prototype.clone = function () {
  60274. // Clone particle system
  60275. var emitter = this.particleSystem.emitter;
  60276. if (!emitter) {
  60277. emitter = new BABYLON.Vector3();
  60278. }
  60279. else if (emitter instanceof BABYLON.Vector3) {
  60280. emitter = emitter.clone();
  60281. }
  60282. else if (emitter instanceof BABYLON.AbstractMesh) {
  60283. emitter = new BABYLON.Mesh("", emitter.getScene());
  60284. emitter.isVisible = false;
  60285. }
  60286. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  60287. // Clone properties
  60288. clone.type = this.type;
  60289. clone.inheritDirection = this.inheritDirection;
  60290. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  60291. clone.particleSystem._disposeEmitterOnDispose = true;
  60292. clone.particleSystem.disposeOnStop = true;
  60293. return clone;
  60294. };
  60295. /** Release associated resources */
  60296. SubEmitter.prototype.dispose = function () {
  60297. this.particleSystem.dispose();
  60298. };
  60299. return SubEmitter;
  60300. }());
  60301. BABYLON.SubEmitter = SubEmitter;
  60302. })(BABYLON || (BABYLON = {}));
  60303. //# sourceMappingURL=babylon.subEmitter.js.map
  60304. var BABYLON;
  60305. (function (BABYLON) {
  60306. var ShaderMaterial = /** @class */ (function (_super) {
  60307. __extends(ShaderMaterial, _super);
  60308. function ShaderMaterial(name, scene, shaderPath, options) {
  60309. var _this = _super.call(this, name, scene) || this;
  60310. _this._textures = {};
  60311. _this._textureArrays = {};
  60312. _this._floats = {};
  60313. _this._ints = {};
  60314. _this._floatsArrays = {};
  60315. _this._colors3 = {};
  60316. _this._colors3Arrays = {};
  60317. _this._colors4 = {};
  60318. _this._vectors2 = {};
  60319. _this._vectors3 = {};
  60320. _this._vectors4 = {};
  60321. _this._matrices = {};
  60322. _this._matrices3x3 = {};
  60323. _this._matrices2x2 = {};
  60324. _this._vectors2Arrays = {};
  60325. _this._vectors3Arrays = {};
  60326. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  60327. _this._shaderPath = shaderPath;
  60328. options.needAlphaBlending = options.needAlphaBlending || false;
  60329. options.needAlphaTesting = options.needAlphaTesting || false;
  60330. options.attributes = options.attributes || ["position", "normal", "uv"];
  60331. options.uniforms = options.uniforms || ["worldViewProjection"];
  60332. options.uniformBuffers = options.uniformBuffers || [];
  60333. options.samplers = options.samplers || [];
  60334. options.defines = options.defines || [];
  60335. _this._options = options;
  60336. return _this;
  60337. }
  60338. ShaderMaterial.prototype.getClassName = function () {
  60339. return "ShaderMaterial";
  60340. };
  60341. ShaderMaterial.prototype.needAlphaBlending = function () {
  60342. return this._options.needAlphaBlending;
  60343. };
  60344. ShaderMaterial.prototype.needAlphaTesting = function () {
  60345. return this._options.needAlphaTesting;
  60346. };
  60347. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  60348. if (this._options.uniforms.indexOf(uniformName) === -1) {
  60349. this._options.uniforms.push(uniformName);
  60350. }
  60351. };
  60352. ShaderMaterial.prototype.setTexture = function (name, texture) {
  60353. if (this._options.samplers.indexOf(name) === -1) {
  60354. this._options.samplers.push(name);
  60355. }
  60356. this._textures[name] = texture;
  60357. return this;
  60358. };
  60359. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  60360. if (this._options.samplers.indexOf(name) === -1) {
  60361. this._options.samplers.push(name);
  60362. }
  60363. this._checkUniform(name);
  60364. this._textureArrays[name] = textures;
  60365. return this;
  60366. };
  60367. ShaderMaterial.prototype.setFloat = function (name, value) {
  60368. this._checkUniform(name);
  60369. this._floats[name] = value;
  60370. return this;
  60371. };
  60372. ShaderMaterial.prototype.setInt = function (name, value) {
  60373. this._checkUniform(name);
  60374. this._ints[name] = value;
  60375. return this;
  60376. };
  60377. ShaderMaterial.prototype.setFloats = function (name, value) {
  60378. this._checkUniform(name);
  60379. this._floatsArrays[name] = value;
  60380. return this;
  60381. };
  60382. ShaderMaterial.prototype.setColor3 = function (name, value) {
  60383. this._checkUniform(name);
  60384. this._colors3[name] = value;
  60385. return this;
  60386. };
  60387. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  60388. this._checkUniform(name);
  60389. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  60390. color.toArray(arr, arr.length);
  60391. return arr;
  60392. }, []);
  60393. return this;
  60394. };
  60395. ShaderMaterial.prototype.setColor4 = function (name, value) {
  60396. this._checkUniform(name);
  60397. this._colors4[name] = value;
  60398. return this;
  60399. };
  60400. ShaderMaterial.prototype.setVector2 = function (name, value) {
  60401. this._checkUniform(name);
  60402. this._vectors2[name] = value;
  60403. return this;
  60404. };
  60405. ShaderMaterial.prototype.setVector3 = function (name, value) {
  60406. this._checkUniform(name);
  60407. this._vectors3[name] = value;
  60408. return this;
  60409. };
  60410. ShaderMaterial.prototype.setVector4 = function (name, value) {
  60411. this._checkUniform(name);
  60412. this._vectors4[name] = value;
  60413. return this;
  60414. };
  60415. ShaderMaterial.prototype.setMatrix = function (name, value) {
  60416. this._checkUniform(name);
  60417. this._matrices[name] = value;
  60418. return this;
  60419. };
  60420. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  60421. this._checkUniform(name);
  60422. this._matrices3x3[name] = value;
  60423. return this;
  60424. };
  60425. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  60426. this._checkUniform(name);
  60427. this._matrices2x2[name] = value;
  60428. return this;
  60429. };
  60430. ShaderMaterial.prototype.setArray2 = function (name, value) {
  60431. this._checkUniform(name);
  60432. this._vectors2Arrays[name] = value;
  60433. return this;
  60434. };
  60435. ShaderMaterial.prototype.setArray3 = function (name, value) {
  60436. this._checkUniform(name);
  60437. this._vectors3Arrays[name] = value;
  60438. return this;
  60439. };
  60440. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60441. if (!mesh) {
  60442. return true;
  60443. }
  60444. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  60445. return false;
  60446. }
  60447. return false;
  60448. };
  60449. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  60450. var scene = this.getScene();
  60451. var engine = scene.getEngine();
  60452. if (!this.checkReadyOnEveryCall) {
  60453. if (this._renderId === scene.getRenderId()) {
  60454. if (this._checkCache(scene, mesh, useInstances)) {
  60455. return true;
  60456. }
  60457. }
  60458. }
  60459. // Instances
  60460. var defines = [];
  60461. var attribs = [];
  60462. var fallbacks = new BABYLON.EffectFallbacks();
  60463. if (useInstances) {
  60464. defines.push("#define INSTANCES");
  60465. }
  60466. for (var index = 0; index < this._options.defines.length; index++) {
  60467. defines.push(this._options.defines[index]);
  60468. }
  60469. for (var index = 0; index < this._options.attributes.length; index++) {
  60470. attribs.push(this._options.attributes[index]);
  60471. }
  60472. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  60473. attribs.push(BABYLON.VertexBuffer.ColorKind);
  60474. defines.push("#define VERTEXCOLOR");
  60475. }
  60476. // Bones
  60477. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  60478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60480. if (mesh.numBoneInfluencers > 4) {
  60481. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60482. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60483. }
  60484. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60485. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60486. fallbacks.addCPUSkinningFallback(0, mesh);
  60487. if (this._options.uniforms.indexOf("mBones") === -1) {
  60488. this._options.uniforms.push("mBones");
  60489. }
  60490. }
  60491. else {
  60492. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60493. }
  60494. // Textures
  60495. for (var name in this._textures) {
  60496. if (!this._textures[name].isReady()) {
  60497. return false;
  60498. }
  60499. }
  60500. // Alpha test
  60501. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  60502. defines.push("#define ALPHATEST");
  60503. }
  60504. var previousEffect = this._effect;
  60505. var join = defines.join("\n");
  60506. this._effect = engine.createEffect(this._shaderPath, {
  60507. attributes: attribs,
  60508. uniformsNames: this._options.uniforms,
  60509. uniformBuffersNames: this._options.uniformBuffers,
  60510. samplers: this._options.samplers,
  60511. defines: join,
  60512. fallbacks: fallbacks,
  60513. onCompiled: this.onCompiled,
  60514. onError: this.onError
  60515. }, engine);
  60516. if (!this._effect.isReady()) {
  60517. return false;
  60518. }
  60519. if (previousEffect !== this._effect) {
  60520. scene.resetCachedMaterial();
  60521. }
  60522. this._renderId = scene.getRenderId();
  60523. return true;
  60524. };
  60525. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  60526. var scene = this.getScene();
  60527. if (!this._effect) {
  60528. return;
  60529. }
  60530. if (this._options.uniforms.indexOf("world") !== -1) {
  60531. this._effect.setMatrix("world", world);
  60532. }
  60533. if (this._options.uniforms.indexOf("worldView") !== -1) {
  60534. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  60535. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  60536. }
  60537. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  60538. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  60539. }
  60540. };
  60541. ShaderMaterial.prototype.bind = function (world, mesh) {
  60542. // Std values
  60543. this.bindOnlyWorldMatrix(world);
  60544. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  60545. if (this._options.uniforms.indexOf("view") !== -1) {
  60546. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  60547. }
  60548. if (this._options.uniforms.indexOf("projection") !== -1) {
  60549. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  60550. }
  60551. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  60552. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  60553. }
  60554. // Bones
  60555. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  60556. var name;
  60557. // Texture
  60558. for (name in this._textures) {
  60559. this._effect.setTexture(name, this._textures[name]);
  60560. }
  60561. // Texture arrays
  60562. for (name in this._textureArrays) {
  60563. this._effect.setTextureArray(name, this._textureArrays[name]);
  60564. }
  60565. // Int
  60566. for (name in this._ints) {
  60567. this._effect.setInt(name, this._ints[name]);
  60568. }
  60569. // Float
  60570. for (name in this._floats) {
  60571. this._effect.setFloat(name, this._floats[name]);
  60572. }
  60573. // Floats
  60574. for (name in this._floatsArrays) {
  60575. this._effect.setArray(name, this._floatsArrays[name]);
  60576. }
  60577. // Color3
  60578. for (name in this._colors3) {
  60579. this._effect.setColor3(name, this._colors3[name]);
  60580. }
  60581. for (name in this._colors3Arrays) {
  60582. this._effect.setArray3(name, this._colors3Arrays[name]);
  60583. }
  60584. // Color4
  60585. for (name in this._colors4) {
  60586. var color = this._colors4[name];
  60587. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60588. }
  60589. // Vector2
  60590. for (name in this._vectors2) {
  60591. this._effect.setVector2(name, this._vectors2[name]);
  60592. }
  60593. // Vector3
  60594. for (name in this._vectors3) {
  60595. this._effect.setVector3(name, this._vectors3[name]);
  60596. }
  60597. // Vector4
  60598. for (name in this._vectors4) {
  60599. this._effect.setVector4(name, this._vectors4[name]);
  60600. }
  60601. // Matrix
  60602. for (name in this._matrices) {
  60603. this._effect.setMatrix(name, this._matrices[name]);
  60604. }
  60605. // Matrix 3x3
  60606. for (name in this._matrices3x3) {
  60607. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60608. }
  60609. // Matrix 2x2
  60610. for (name in this._matrices2x2) {
  60611. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60612. }
  60613. // Vector2Array
  60614. for (name in this._vectors2Arrays) {
  60615. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60616. }
  60617. // Vector3Array
  60618. for (name in this._vectors3Arrays) {
  60619. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60620. }
  60621. }
  60622. this._afterBind(mesh);
  60623. };
  60624. ShaderMaterial.prototype.getActiveTextures = function () {
  60625. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60626. for (var name in this._textures) {
  60627. activeTextures.push(this._textures[name]);
  60628. }
  60629. for (var name in this._textureArrays) {
  60630. var array = this._textureArrays[name];
  60631. for (var index = 0; index < array.length; index++) {
  60632. activeTextures.push(array[index]);
  60633. }
  60634. }
  60635. return activeTextures;
  60636. };
  60637. ShaderMaterial.prototype.hasTexture = function (texture) {
  60638. if (_super.prototype.hasTexture.call(this, texture)) {
  60639. return true;
  60640. }
  60641. for (var name in this._textures) {
  60642. if (this._textures[name] === texture) {
  60643. return true;
  60644. }
  60645. }
  60646. for (var name in this._textureArrays) {
  60647. var array = this._textureArrays[name];
  60648. for (var index = 0; index < array.length; index++) {
  60649. if (array[index] === texture) {
  60650. return true;
  60651. }
  60652. }
  60653. }
  60654. return false;
  60655. };
  60656. ShaderMaterial.prototype.clone = function (name) {
  60657. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60658. return newShaderMaterial;
  60659. };
  60660. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60661. if (forceDisposeTextures) {
  60662. var name;
  60663. for (name in this._textures) {
  60664. this._textures[name].dispose();
  60665. }
  60666. for (name in this._textureArrays) {
  60667. var array = this._textureArrays[name];
  60668. for (var index = 0; index < array.length; index++) {
  60669. array[index].dispose();
  60670. }
  60671. }
  60672. }
  60673. this._textures = {};
  60674. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60675. };
  60676. ShaderMaterial.prototype.serialize = function () {
  60677. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60678. serializationObject.customType = "BABYLON.ShaderMaterial";
  60679. serializationObject.options = this._options;
  60680. serializationObject.shaderPath = this._shaderPath;
  60681. var name;
  60682. // Texture
  60683. serializationObject.textures = {};
  60684. for (name in this._textures) {
  60685. serializationObject.textures[name] = this._textures[name].serialize();
  60686. }
  60687. // Texture arrays
  60688. serializationObject.textureArrays = {};
  60689. for (name in this._textureArrays) {
  60690. serializationObject.textureArrays[name] = [];
  60691. var array = this._textureArrays[name];
  60692. for (var index = 0; index < array.length; index++) {
  60693. serializationObject.textureArrays[name].push(array[index].serialize());
  60694. }
  60695. }
  60696. // Float
  60697. serializationObject.floats = {};
  60698. for (name in this._floats) {
  60699. serializationObject.floats[name] = this._floats[name];
  60700. }
  60701. // Float s
  60702. serializationObject.FloatArrays = {};
  60703. for (name in this._floatsArrays) {
  60704. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60705. }
  60706. // Color3
  60707. serializationObject.colors3 = {};
  60708. for (name in this._colors3) {
  60709. serializationObject.colors3[name] = this._colors3[name].asArray();
  60710. }
  60711. // Color3 array
  60712. serializationObject.colors3Arrays = {};
  60713. for (name in this._colors3Arrays) {
  60714. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60715. }
  60716. // Color4
  60717. serializationObject.colors4 = {};
  60718. for (name in this._colors4) {
  60719. serializationObject.colors4[name] = this._colors4[name].asArray();
  60720. }
  60721. // Vector2
  60722. serializationObject.vectors2 = {};
  60723. for (name in this._vectors2) {
  60724. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60725. }
  60726. // Vector3
  60727. serializationObject.vectors3 = {};
  60728. for (name in this._vectors3) {
  60729. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60730. }
  60731. // Vector4
  60732. serializationObject.vectors4 = {};
  60733. for (name in this._vectors4) {
  60734. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60735. }
  60736. // Matrix
  60737. serializationObject.matrices = {};
  60738. for (name in this._matrices) {
  60739. serializationObject.matrices[name] = this._matrices[name].asArray();
  60740. }
  60741. // Matrix 3x3
  60742. serializationObject.matrices3x3 = {};
  60743. for (name in this._matrices3x3) {
  60744. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60745. }
  60746. // Matrix 2x2
  60747. serializationObject.matrices2x2 = {};
  60748. for (name in this._matrices2x2) {
  60749. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60750. }
  60751. // Vector2Array
  60752. serializationObject.vectors2Arrays = {};
  60753. for (name in this._vectors2Arrays) {
  60754. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60755. }
  60756. // Vector3Array
  60757. serializationObject.vectors3Arrays = {};
  60758. for (name in this._vectors3Arrays) {
  60759. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60760. }
  60761. return serializationObject;
  60762. };
  60763. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60764. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60765. var name;
  60766. // Texture
  60767. for (name in source.textures) {
  60768. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60769. }
  60770. // Texture arrays
  60771. for (name in source.textureArrays) {
  60772. var array = source.textureArrays[name];
  60773. var textureArray = new Array();
  60774. for (var index = 0; index < array.length; index++) {
  60775. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60776. }
  60777. material.setTextureArray(name, textureArray);
  60778. }
  60779. // Float
  60780. for (name in source.floats) {
  60781. material.setFloat(name, source.floats[name]);
  60782. }
  60783. // Float s
  60784. for (name in source.floatsArrays) {
  60785. material.setFloats(name, source.floatsArrays[name]);
  60786. }
  60787. // Color3
  60788. for (name in source.colors3) {
  60789. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60790. }
  60791. // Color3 arrays
  60792. for (name in source.colors3Arrays) {
  60793. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60794. if (i % 3 === 0) {
  60795. arr.push([num]);
  60796. }
  60797. else {
  60798. arr[arr.length - 1].push(num);
  60799. }
  60800. return arr;
  60801. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60802. material.setColor3Array(name, colors);
  60803. }
  60804. // Color4
  60805. for (name in source.colors4) {
  60806. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60807. }
  60808. // Vector2
  60809. for (name in source.vectors2) {
  60810. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60811. }
  60812. // Vector3
  60813. for (name in source.vectors3) {
  60814. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60815. }
  60816. // Vector4
  60817. for (name in source.vectors4) {
  60818. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60819. }
  60820. // Matrix
  60821. for (name in source.matrices) {
  60822. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60823. }
  60824. // Matrix 3x3
  60825. for (name in source.matrices3x3) {
  60826. material.setMatrix3x3(name, source.matrices3x3[name]);
  60827. }
  60828. // Matrix 2x2
  60829. for (name in source.matrices2x2) {
  60830. material.setMatrix2x2(name, source.matrices2x2[name]);
  60831. }
  60832. // Vector2Array
  60833. for (name in source.vectors2Arrays) {
  60834. material.setArray2(name, source.vectors2Arrays[name]);
  60835. }
  60836. // Vector3Array
  60837. for (name in source.vectors3Arrays) {
  60838. material.setArray3(name, source.vectors3Arrays[name]);
  60839. }
  60840. return material;
  60841. };
  60842. return ShaderMaterial;
  60843. }(BABYLON.Material));
  60844. BABYLON.ShaderMaterial = ShaderMaterial;
  60845. })(BABYLON || (BABYLON = {}));
  60846. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60847. var BABYLON;
  60848. (function (BABYLON) {
  60849. var GroundMesh = /** @class */ (function (_super) {
  60850. __extends(GroundMesh, _super);
  60851. function GroundMesh(name, scene) {
  60852. var _this = _super.call(this, name, scene) || this;
  60853. _this.generateOctree = false;
  60854. return _this;
  60855. }
  60856. GroundMesh.prototype.getClassName = function () {
  60857. return "GroundMesh";
  60858. };
  60859. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60860. get: function () {
  60861. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60862. },
  60863. enumerable: true,
  60864. configurable: true
  60865. });
  60866. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60867. get: function () {
  60868. return this._subdivisionsX;
  60869. },
  60870. enumerable: true,
  60871. configurable: true
  60872. });
  60873. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60874. get: function () {
  60875. return this._subdivisionsY;
  60876. },
  60877. enumerable: true,
  60878. configurable: true
  60879. });
  60880. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60881. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60882. this._subdivisionsX = chunksCount;
  60883. this._subdivisionsY = chunksCount;
  60884. this.subdivide(chunksCount);
  60885. // Call the octree system optimization if it is defined.
  60886. var thisAsAny = this;
  60887. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  60888. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60889. }
  60890. };
  60891. /**
  60892. * Returns a height (y) value in the Worl system :
  60893. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60894. * Returns the ground y position if (x, z) are outside the ground surface.
  60895. */
  60896. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60897. var world = this.getWorldMatrix();
  60898. var invMat = BABYLON.Tmp.Matrix[5];
  60899. world.invertToRef(invMat);
  60900. var tmpVect = BABYLON.Tmp.Vector3[8];
  60901. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60902. x = tmpVect.x;
  60903. z = tmpVect.z;
  60904. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60905. return this.position.y;
  60906. }
  60907. if (!this._heightQuads || this._heightQuads.length == 0) {
  60908. this._initHeightQuads();
  60909. this._computeHeightQuads();
  60910. }
  60911. var facet = this._getFacetAt(x, z);
  60912. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60913. // return y in the World system
  60914. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60915. return tmpVect.y;
  60916. };
  60917. /**
  60918. * Returns a normalized vector (Vector3) orthogonal to the ground
  60919. * at the ground coordinates (x, z) expressed in the World system.
  60920. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60921. */
  60922. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60923. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60924. this.getNormalAtCoordinatesToRef(x, z, normal);
  60925. return normal;
  60926. };
  60927. /**
  60928. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60929. * at the ground coordinates (x, z) expressed in the World system.
  60930. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60931. * Returns the GroundMesh.
  60932. */
  60933. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60934. var world = this.getWorldMatrix();
  60935. var tmpMat = BABYLON.Tmp.Matrix[5];
  60936. world.invertToRef(tmpMat);
  60937. var tmpVect = BABYLON.Tmp.Vector3[8];
  60938. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60939. x = tmpVect.x;
  60940. z = tmpVect.z;
  60941. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60942. return this;
  60943. }
  60944. if (!this._heightQuads || this._heightQuads.length == 0) {
  60945. this._initHeightQuads();
  60946. this._computeHeightQuads();
  60947. }
  60948. var facet = this._getFacetAt(x, z);
  60949. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60950. return this;
  60951. };
  60952. /**
  60953. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60954. * if the ground has been updated.
  60955. * This can be used in the render loop.
  60956. * Returns the GroundMesh.
  60957. */
  60958. GroundMesh.prototype.updateCoordinateHeights = function () {
  60959. if (!this._heightQuads || this._heightQuads.length == 0) {
  60960. this._initHeightQuads();
  60961. }
  60962. this._computeHeightQuads();
  60963. return this;
  60964. };
  60965. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60966. GroundMesh.prototype._getFacetAt = function (x, z) {
  60967. // retrieve col and row from x, z coordinates in the ground local system
  60968. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60969. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60970. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60971. var facet;
  60972. if (z < quad.slope.x * x + quad.slope.y) {
  60973. facet = quad.facet1;
  60974. }
  60975. else {
  60976. facet = quad.facet2;
  60977. }
  60978. return facet;
  60979. };
  60980. // Creates and populates the heightMap array with "facet" elements :
  60981. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60982. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60983. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60984. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60985. // Returns the GroundMesh.
  60986. GroundMesh.prototype._initHeightQuads = function () {
  60987. var subdivisionsX = this._subdivisionsX;
  60988. var subdivisionsY = this._subdivisionsY;
  60989. this._heightQuads = new Array();
  60990. for (var row = 0; row < subdivisionsY; row++) {
  60991. for (var col = 0; col < subdivisionsX; col++) {
  60992. 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) };
  60993. this._heightQuads[row * subdivisionsX + col] = quad;
  60994. }
  60995. }
  60996. return this;
  60997. };
  60998. // Compute each quad element values and update the the heightMap array :
  60999. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  61000. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  61001. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  61002. // Returns the GroundMesh.
  61003. GroundMesh.prototype._computeHeightQuads = function () {
  61004. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61005. if (!positions) {
  61006. return this;
  61007. }
  61008. var v1 = BABYLON.Tmp.Vector3[3];
  61009. var v2 = BABYLON.Tmp.Vector3[2];
  61010. var v3 = BABYLON.Tmp.Vector3[1];
  61011. var v4 = BABYLON.Tmp.Vector3[0];
  61012. var v1v2 = BABYLON.Tmp.Vector3[4];
  61013. var v1v3 = BABYLON.Tmp.Vector3[5];
  61014. var v1v4 = BABYLON.Tmp.Vector3[6];
  61015. var norm1 = BABYLON.Tmp.Vector3[7];
  61016. var norm2 = BABYLON.Tmp.Vector3[8];
  61017. var i = 0;
  61018. var j = 0;
  61019. var k = 0;
  61020. var cd = 0; // 2D slope coefficient : z = cd * x + h
  61021. var h = 0;
  61022. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  61023. var d2 = 0;
  61024. var subdivisionsX = this._subdivisionsX;
  61025. var subdivisionsY = this._subdivisionsY;
  61026. for (var row = 0; row < subdivisionsY; row++) {
  61027. for (var col = 0; col < subdivisionsX; col++) {
  61028. i = col * 3;
  61029. j = row * (subdivisionsX + 1) * 3;
  61030. k = (row + 1) * (subdivisionsX + 1) * 3;
  61031. v1.x = positions[j + i];
  61032. v1.y = positions[j + i + 1];
  61033. v1.z = positions[j + i + 2];
  61034. v2.x = positions[j + i + 3];
  61035. v2.y = positions[j + i + 4];
  61036. v2.z = positions[j + i + 5];
  61037. v3.x = positions[k + i];
  61038. v3.y = positions[k + i + 1];
  61039. v3.z = positions[k + i + 2];
  61040. v4.x = positions[k + i + 3];
  61041. v4.y = positions[k + i + 4];
  61042. v4.z = positions[k + i + 5];
  61043. // 2D slope V1V4
  61044. cd = (v4.z - v1.z) / (v4.x - v1.x);
  61045. h = v1.z - cd * v1.x; // v1 belongs to the slope
  61046. // facet equations :
  61047. // we compute each facet normal vector
  61048. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  61049. // we compute the value d by applying the equation to v1 which belongs to the plane
  61050. // then we store the facet equation in a Vector4
  61051. v2.subtractToRef(v1, v1v2);
  61052. v3.subtractToRef(v1, v1v3);
  61053. v4.subtractToRef(v1, v1v4);
  61054. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  61055. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  61056. norm1.normalize();
  61057. norm2.normalize();
  61058. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  61059. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  61060. var quad = this._heightQuads[row * subdivisionsX + col];
  61061. quad.slope.copyFromFloats(cd, h);
  61062. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  61063. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  61064. }
  61065. }
  61066. return this;
  61067. };
  61068. GroundMesh.prototype.serialize = function (serializationObject) {
  61069. _super.prototype.serialize.call(this, serializationObject);
  61070. serializationObject.subdivisionsX = this._subdivisionsX;
  61071. serializationObject.subdivisionsY = this._subdivisionsY;
  61072. serializationObject.minX = this._minX;
  61073. serializationObject.maxX = this._maxX;
  61074. serializationObject.minZ = this._minZ;
  61075. serializationObject.maxZ = this._maxZ;
  61076. serializationObject.width = this._width;
  61077. serializationObject.height = this._height;
  61078. };
  61079. GroundMesh.Parse = function (parsedMesh, scene) {
  61080. var result = new GroundMesh(parsedMesh.name, scene);
  61081. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  61082. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  61083. result._minX = parsedMesh.minX;
  61084. result._maxX = parsedMesh.maxX;
  61085. result._minZ = parsedMesh.minZ;
  61086. result._maxZ = parsedMesh.maxZ;
  61087. result._width = parsedMesh.width;
  61088. result._height = parsedMesh.height;
  61089. return result;
  61090. };
  61091. return GroundMesh;
  61092. }(BABYLON.Mesh));
  61093. BABYLON.GroundMesh = GroundMesh;
  61094. })(BABYLON || (BABYLON = {}));
  61095. //# sourceMappingURL=babylon.groundMesh.js.map
  61096. var BABYLON;
  61097. (function (BABYLON) {
  61098. /**
  61099. * Creates an instance based on a source mesh.
  61100. */
  61101. var InstancedMesh = /** @class */ (function (_super) {
  61102. __extends(InstancedMesh, _super);
  61103. function InstancedMesh(name, source) {
  61104. var _this = _super.call(this, name, source.getScene()) || this;
  61105. source.instances.push(_this);
  61106. _this._sourceMesh = source;
  61107. _this.position.copyFrom(source.position);
  61108. _this.rotation.copyFrom(source.rotation);
  61109. _this.scaling.copyFrom(source.scaling);
  61110. if (source.rotationQuaternion) {
  61111. _this.rotationQuaternion = source.rotationQuaternion.clone();
  61112. }
  61113. _this.infiniteDistance = source.infiniteDistance;
  61114. _this.setPivotMatrix(source.getPivotMatrix());
  61115. _this.refreshBoundingInfo();
  61116. _this._syncSubMeshes();
  61117. return _this;
  61118. }
  61119. /**
  61120. * Returns the string "InstancedMesh".
  61121. */
  61122. InstancedMesh.prototype.getClassName = function () {
  61123. return "InstancedMesh";
  61124. };
  61125. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  61126. // Methods
  61127. get: function () {
  61128. return this._sourceMesh.receiveShadows;
  61129. },
  61130. enumerable: true,
  61131. configurable: true
  61132. });
  61133. Object.defineProperty(InstancedMesh.prototype, "material", {
  61134. get: function () {
  61135. return this._sourceMesh.material;
  61136. },
  61137. enumerable: true,
  61138. configurable: true
  61139. });
  61140. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  61141. get: function () {
  61142. return this._sourceMesh.visibility;
  61143. },
  61144. enumerable: true,
  61145. configurable: true
  61146. });
  61147. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  61148. get: function () {
  61149. return this._sourceMesh.skeleton;
  61150. },
  61151. enumerable: true,
  61152. configurable: true
  61153. });
  61154. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  61155. get: function () {
  61156. return this._sourceMesh.renderingGroupId;
  61157. },
  61158. set: function (value) {
  61159. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  61160. return;
  61161. }
  61162. //no-op with warning
  61163. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  61164. },
  61165. enumerable: true,
  61166. configurable: true
  61167. });
  61168. /**
  61169. * Returns the total number of vertices (integer).
  61170. */
  61171. InstancedMesh.prototype.getTotalVertices = function () {
  61172. return this._sourceMesh.getTotalVertices();
  61173. };
  61174. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  61175. get: function () {
  61176. return this._sourceMesh;
  61177. },
  61178. enumerable: true,
  61179. configurable: true
  61180. });
  61181. /**
  61182. * Is this node ready to be used/rendered
  61183. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  61184. * @return {boolean} is it ready
  61185. */
  61186. InstancedMesh.prototype.isReady = function (completeCheck) {
  61187. if (completeCheck === void 0) { completeCheck = false; }
  61188. return this._sourceMesh.isReady(completeCheck, true);
  61189. };
  61190. /**
  61191. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  61192. */
  61193. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  61194. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  61195. };
  61196. /**
  61197. * Sets the vertex data of the mesh geometry for the requested `kind`.
  61198. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  61199. * The `data` are either a numeric array either a Float32Array.
  61200. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  61201. * 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).
  61202. * Note that a new underlying VertexBuffer object is created each call.
  61203. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  61204. *
  61205. * Possible `kind` values :
  61206. * - BABYLON.VertexBuffer.PositionKind
  61207. * - BABYLON.VertexBuffer.UVKind
  61208. * - BABYLON.VertexBuffer.UV2Kind
  61209. * - BABYLON.VertexBuffer.UV3Kind
  61210. * - BABYLON.VertexBuffer.UV4Kind
  61211. * - BABYLON.VertexBuffer.UV5Kind
  61212. * - BABYLON.VertexBuffer.UV6Kind
  61213. * - BABYLON.VertexBuffer.ColorKind
  61214. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61215. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61216. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61217. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61218. *
  61219. * Returns the Mesh.
  61220. */
  61221. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  61222. if (this.sourceMesh) {
  61223. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  61224. }
  61225. return this.sourceMesh;
  61226. };
  61227. /**
  61228. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  61229. * If the mesh has no geometry, it is simply returned as it is.
  61230. * The `data` are either a numeric array either a Float32Array.
  61231. * No new underlying VertexBuffer object is created.
  61232. * 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.
  61233. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  61234. *
  61235. * Possible `kind` values :
  61236. * - BABYLON.VertexBuffer.PositionKind
  61237. * - BABYLON.VertexBuffer.UVKind
  61238. * - BABYLON.VertexBuffer.UV2Kind
  61239. * - BABYLON.VertexBuffer.UV3Kind
  61240. * - BABYLON.VertexBuffer.UV4Kind
  61241. * - BABYLON.VertexBuffer.UV5Kind
  61242. * - BABYLON.VertexBuffer.UV6Kind
  61243. * - BABYLON.VertexBuffer.ColorKind
  61244. * - BABYLON.VertexBuffer.MatricesIndicesKind
  61245. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  61246. * - BABYLON.VertexBuffer.MatricesWeightsKind
  61247. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  61248. *
  61249. * Returns the Mesh.
  61250. */
  61251. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  61252. if (this.sourceMesh) {
  61253. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  61254. }
  61255. return this.sourceMesh;
  61256. };
  61257. /**
  61258. * Sets the mesh indices.
  61259. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  61260. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  61261. * This method creates a new index buffer each call.
  61262. * Returns the Mesh.
  61263. */
  61264. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  61265. if (totalVertices === void 0) { totalVertices = null; }
  61266. if (this.sourceMesh) {
  61267. this.sourceMesh.setIndices(indices, totalVertices);
  61268. }
  61269. return this.sourceMesh;
  61270. };
  61271. /**
  61272. * Boolean : True if the mesh owns the requested kind of data.
  61273. */
  61274. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  61275. return this._sourceMesh.isVerticesDataPresent(kind);
  61276. };
  61277. /**
  61278. * Returns an array of indices (IndicesArray).
  61279. */
  61280. InstancedMesh.prototype.getIndices = function () {
  61281. return this._sourceMesh.getIndices();
  61282. };
  61283. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  61284. get: function () {
  61285. return this._sourceMesh._positions;
  61286. },
  61287. enumerable: true,
  61288. configurable: true
  61289. });
  61290. /**
  61291. * Sets a new updated BoundingInfo to the mesh.
  61292. * Returns the mesh.
  61293. */
  61294. InstancedMesh.prototype.refreshBoundingInfo = function () {
  61295. var meshBB = this._sourceMesh.getBoundingInfo();
  61296. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  61297. this._updateBoundingInfo();
  61298. return this;
  61299. };
  61300. /** @hidden */
  61301. InstancedMesh.prototype._preActivate = function () {
  61302. if (this._currentLOD) {
  61303. this._currentLOD._preActivate();
  61304. }
  61305. return this;
  61306. };
  61307. /** @hidden */
  61308. InstancedMesh.prototype._activate = function (renderId) {
  61309. if (this._currentLOD) {
  61310. this._currentLOD._registerInstanceForRenderId(this, renderId);
  61311. }
  61312. return this;
  61313. };
  61314. /**
  61315. * Returns the current associated LOD AbstractMesh.
  61316. */
  61317. InstancedMesh.prototype.getLOD = function (camera) {
  61318. if (!camera) {
  61319. return this;
  61320. }
  61321. var boundingInfo = this.getBoundingInfo();
  61322. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  61323. if (this._currentLOD === this.sourceMesh) {
  61324. return this;
  61325. }
  61326. return this._currentLOD;
  61327. };
  61328. /** @hidden */
  61329. InstancedMesh.prototype._syncSubMeshes = function () {
  61330. this.releaseSubMeshes();
  61331. if (this._sourceMesh.subMeshes) {
  61332. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  61333. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  61334. }
  61335. }
  61336. return this;
  61337. };
  61338. /** @hidden */
  61339. InstancedMesh.prototype._generatePointsArray = function () {
  61340. return this._sourceMesh._generatePointsArray();
  61341. };
  61342. /**
  61343. * Creates a new InstancedMesh from the current mesh.
  61344. * - name (string) : the cloned mesh name
  61345. * - newParent (optional Node) : the optional Node to parent the clone to.
  61346. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  61347. *
  61348. * Returns the clone.
  61349. */
  61350. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61351. var result = this._sourceMesh.createInstance(name);
  61352. // Deep copy
  61353. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  61354. // Bounding info
  61355. this.refreshBoundingInfo();
  61356. // Parent
  61357. if (newParent) {
  61358. result.parent = newParent;
  61359. }
  61360. if (!doNotCloneChildren) {
  61361. // Children
  61362. for (var index = 0; index < this.getScene().meshes.length; index++) {
  61363. var mesh = this.getScene().meshes[index];
  61364. if (mesh.parent === this) {
  61365. mesh.clone(mesh.name, result);
  61366. }
  61367. }
  61368. }
  61369. result.computeWorldMatrix(true);
  61370. return result;
  61371. };
  61372. /**
  61373. * Disposes the InstancedMesh.
  61374. * Returns nothing.
  61375. */
  61376. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  61377. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  61378. // Remove from mesh
  61379. var index = this._sourceMesh.instances.indexOf(this);
  61380. this._sourceMesh.instances.splice(index, 1);
  61381. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  61382. };
  61383. return InstancedMesh;
  61384. }(BABYLON.AbstractMesh));
  61385. BABYLON.InstancedMesh = InstancedMesh;
  61386. })(BABYLON || (BABYLON = {}));
  61387. //# sourceMappingURL=babylon.instancedMesh.js.map
  61388. var BABYLON;
  61389. (function (BABYLON) {
  61390. var LinesMesh = /** @class */ (function (_super) {
  61391. __extends(LinesMesh, _super);
  61392. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  61393. if (scene === void 0) { scene = null; }
  61394. if (parent === void 0) { parent = null; }
  61395. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  61396. _this.useVertexColor = useVertexColor;
  61397. _this.useVertexAlpha = useVertexAlpha;
  61398. _this.color = new BABYLON.Color3(1, 1, 1);
  61399. _this.alpha = 1;
  61400. if (source) {
  61401. _this.color = source.color.clone();
  61402. _this.alpha = source.alpha;
  61403. _this.useVertexColor = source.useVertexColor;
  61404. _this.useVertexAlpha = source.useVertexAlpha;
  61405. }
  61406. _this._intersectionThreshold = 0.1;
  61407. var defines = [];
  61408. var options = {
  61409. attributes: [BABYLON.VertexBuffer.PositionKind],
  61410. uniforms: ["world", "viewProjection"],
  61411. needAlphaBlending: true,
  61412. defines: defines
  61413. };
  61414. if (useVertexAlpha === false) {
  61415. options.needAlphaBlending = false;
  61416. }
  61417. if (!useVertexColor) {
  61418. options.uniforms.push("color");
  61419. }
  61420. else {
  61421. options.defines.push("#define VERTEXCOLOR");
  61422. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  61423. }
  61424. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  61425. return _this;
  61426. }
  61427. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  61428. /**
  61429. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61430. * This margin is expressed in world space coordinates, so its value may vary.
  61431. * Default value is 0.1
  61432. * @returns the intersection Threshold value.
  61433. */
  61434. get: function () {
  61435. return this._intersectionThreshold;
  61436. },
  61437. /**
  61438. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  61439. * This margin is expressed in world space coordinates, so its value may vary.
  61440. * @param value the new threshold to apply
  61441. */
  61442. set: function (value) {
  61443. if (this._intersectionThreshold === value) {
  61444. return;
  61445. }
  61446. this._intersectionThreshold = value;
  61447. if (this.geometry) {
  61448. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  61449. }
  61450. },
  61451. enumerable: true,
  61452. configurable: true
  61453. });
  61454. /**
  61455. * Returns the string "LineMesh"
  61456. */
  61457. LinesMesh.prototype.getClassName = function () {
  61458. return "LinesMesh";
  61459. };
  61460. Object.defineProperty(LinesMesh.prototype, "material", {
  61461. /**
  61462. * @hidden
  61463. */
  61464. get: function () {
  61465. return this._colorShader;
  61466. },
  61467. /**
  61468. * @hidden
  61469. */
  61470. set: function (value) {
  61471. // Do nothing
  61472. },
  61473. enumerable: true,
  61474. configurable: true
  61475. });
  61476. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  61477. /**
  61478. * @hidden
  61479. */
  61480. get: function () {
  61481. return false;
  61482. },
  61483. enumerable: true,
  61484. configurable: true
  61485. });
  61486. LinesMesh.prototype.createInstance = function (name) {
  61487. throw new Error("LinesMeshes do not support createInstance.");
  61488. };
  61489. /** @hidden */
  61490. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  61491. if (!this._geometry) {
  61492. return this;
  61493. }
  61494. // VBOs
  61495. this._geometry._bind(this._colorShader.getEffect());
  61496. // Color
  61497. if (!this.useVertexColor) {
  61498. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  61499. }
  61500. return this;
  61501. };
  61502. /** @hidden */
  61503. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  61504. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  61505. return this;
  61506. }
  61507. var engine = this.getScene().getEngine();
  61508. // Draw order
  61509. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  61510. return this;
  61511. };
  61512. LinesMesh.prototype.dispose = function (doNotRecurse) {
  61513. this._colorShader.dispose();
  61514. _super.prototype.dispose.call(this, doNotRecurse);
  61515. };
  61516. /**
  61517. * Returns a new LineMesh object cloned from the current one.
  61518. */
  61519. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  61520. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  61521. };
  61522. return LinesMesh;
  61523. }(BABYLON.Mesh));
  61524. BABYLON.LinesMesh = LinesMesh;
  61525. })(BABYLON || (BABYLON = {}));
  61526. //# sourceMappingURL=babylon.linesMesh.js.map
  61527. var BABYLON;
  61528. (function (BABYLON) {
  61529. /**
  61530. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61531. * The underlying implementation relies on an associative array to ensure the best performances.
  61532. * The value can be anything including 'null' but except 'undefined'
  61533. */
  61534. var StringDictionary = /** @class */ (function () {
  61535. function StringDictionary() {
  61536. this._count = 0;
  61537. this._data = {};
  61538. }
  61539. /**
  61540. * This will clear this dictionary and copy the content from the 'source' one.
  61541. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61542. * @param source the dictionary to take the content from and copy to this dictionary
  61543. */
  61544. StringDictionary.prototype.copyFrom = function (source) {
  61545. var _this = this;
  61546. this.clear();
  61547. source.forEach(function (t, v) { return _this.add(t, v); });
  61548. };
  61549. /**
  61550. * Get a value based from its key
  61551. * @param key the given key to get the matching value from
  61552. * @return the value if found, otherwise undefined is returned
  61553. */
  61554. StringDictionary.prototype.get = function (key) {
  61555. var val = this._data[key];
  61556. if (val !== undefined) {
  61557. return val;
  61558. }
  61559. return undefined;
  61560. };
  61561. /**
  61562. * Get a value from its key or add it if it doesn't exist.
  61563. * This method will ensure you that a given key/data will be present in the dictionary.
  61564. * @param key the given key to get the matching value from
  61565. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61566. * The factory will only be invoked if there's no data for the given key.
  61567. * @return the value corresponding to the key.
  61568. */
  61569. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61570. var val = this.get(key);
  61571. if (val !== undefined) {
  61572. return val;
  61573. }
  61574. val = factory(key);
  61575. if (val) {
  61576. this.add(key, val);
  61577. }
  61578. return val;
  61579. };
  61580. /**
  61581. * Get a value from its key if present in the dictionary otherwise add it
  61582. * @param key the key to get the value from
  61583. * @param val if there's no such key/value pair in the dictionary add it with this value
  61584. * @return the value corresponding to the key
  61585. */
  61586. StringDictionary.prototype.getOrAdd = function (key, val) {
  61587. var curVal = this.get(key);
  61588. if (curVal !== undefined) {
  61589. return curVal;
  61590. }
  61591. this.add(key, val);
  61592. return val;
  61593. };
  61594. /**
  61595. * Check if there's a given key in the dictionary
  61596. * @param key the key to check for
  61597. * @return true if the key is present, false otherwise
  61598. */
  61599. StringDictionary.prototype.contains = function (key) {
  61600. return this._data[key] !== undefined;
  61601. };
  61602. /**
  61603. * Add a new key and its corresponding value
  61604. * @param key the key to add
  61605. * @param value the value corresponding to the key
  61606. * @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
  61607. */
  61608. StringDictionary.prototype.add = function (key, value) {
  61609. if (this._data[key] !== undefined) {
  61610. return false;
  61611. }
  61612. this._data[key] = value;
  61613. ++this._count;
  61614. return true;
  61615. };
  61616. StringDictionary.prototype.set = function (key, value) {
  61617. if (this._data[key] === undefined) {
  61618. return false;
  61619. }
  61620. this._data[key] = value;
  61621. return true;
  61622. };
  61623. /**
  61624. * Get the element of the given key and remove it from the dictionary
  61625. * @param key
  61626. */
  61627. StringDictionary.prototype.getAndRemove = function (key) {
  61628. var val = this.get(key);
  61629. if (val !== undefined) {
  61630. delete this._data[key];
  61631. --this._count;
  61632. return val;
  61633. }
  61634. return null;
  61635. };
  61636. /**
  61637. * Remove a key/value from the dictionary.
  61638. * @param key the key to remove
  61639. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61640. */
  61641. StringDictionary.prototype.remove = function (key) {
  61642. if (this.contains(key)) {
  61643. delete this._data[key];
  61644. --this._count;
  61645. return true;
  61646. }
  61647. return false;
  61648. };
  61649. /**
  61650. * Clear the whole content of the dictionary
  61651. */
  61652. StringDictionary.prototype.clear = function () {
  61653. this._data = {};
  61654. this._count = 0;
  61655. };
  61656. Object.defineProperty(StringDictionary.prototype, "count", {
  61657. get: function () {
  61658. return this._count;
  61659. },
  61660. enumerable: true,
  61661. configurable: true
  61662. });
  61663. /**
  61664. * Execute a callback on each key/val of the dictionary.
  61665. * Note that you can remove any element in this dictionary in the callback implementation
  61666. * @param callback the callback to execute on a given key/value pair
  61667. */
  61668. StringDictionary.prototype.forEach = function (callback) {
  61669. for (var cur in this._data) {
  61670. var val = this._data[cur];
  61671. callback(cur, val);
  61672. }
  61673. };
  61674. /**
  61675. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61676. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61677. * Note that you can remove any element in this dictionary in the callback implementation
  61678. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61679. */
  61680. StringDictionary.prototype.first = function (callback) {
  61681. for (var cur in this._data) {
  61682. var val = this._data[cur];
  61683. var res = callback(cur, val);
  61684. if (res) {
  61685. return res;
  61686. }
  61687. }
  61688. return null;
  61689. };
  61690. return StringDictionary;
  61691. }());
  61692. BABYLON.StringDictionary = StringDictionary;
  61693. })(BABYLON || (BABYLON = {}));
  61694. //# sourceMappingURL=babylon.stringDictionary.js.map
  61695. var BABYLON;
  61696. (function (BABYLON) {
  61697. var Debug;
  61698. (function (Debug) {
  61699. /**
  61700. * Class used to render a debug view of a given skeleton
  61701. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  61702. */
  61703. var SkeletonViewer = /** @class */ (function () {
  61704. /**
  61705. * Creates a new SkeletonViewer
  61706. * @param skeleton defines the skeleton to render
  61707. * @param mesh defines the mesh attached to the skeleton
  61708. * @param scene defines the hosting scene
  61709. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  61710. * @param renderingGroupId defines the rendering group id to use with the viewer
  61711. */
  61712. function SkeletonViewer(
  61713. /** defines the skeleton to render */
  61714. skeleton,
  61715. /** defines the mesh attached to the skeleton */
  61716. mesh, scene,
  61717. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  61718. autoUpdateBonesMatrices,
  61719. /** defines the rendering group id to use with the viewer */
  61720. renderingGroupId) {
  61721. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  61722. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  61723. this.skeleton = skeleton;
  61724. this.mesh = mesh;
  61725. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  61726. this.renderingGroupId = renderingGroupId;
  61727. /** Gets or sets the color used to render the skeleton */
  61728. this.color = BABYLON.Color3.White();
  61729. this._debugLines = new Array();
  61730. this._isEnabled = false;
  61731. this._scene = scene;
  61732. this.update();
  61733. this._renderFunction = this.update.bind(this);
  61734. }
  61735. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  61736. get: function () {
  61737. return this._isEnabled;
  61738. },
  61739. /** Gets or sets a boolean indicating if the viewer is enabled */
  61740. set: function (value) {
  61741. if (this._isEnabled === value) {
  61742. return;
  61743. }
  61744. this._isEnabled = value;
  61745. if (value) {
  61746. this._scene.registerBeforeRender(this._renderFunction);
  61747. }
  61748. else {
  61749. this._scene.unregisterBeforeRender(this._renderFunction);
  61750. }
  61751. },
  61752. enumerable: true,
  61753. configurable: true
  61754. });
  61755. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  61756. if (x === void 0) { x = 0; }
  61757. if (y === void 0) { y = 0; }
  61758. if (z === void 0) { z = 0; }
  61759. var tmat = BABYLON.Tmp.Matrix[0];
  61760. var parentBone = bone.getParent();
  61761. tmat.copyFrom(bone.getLocalMatrix());
  61762. if (x !== 0 || y !== 0 || z !== 0) {
  61763. var tmat2 = BABYLON.Tmp.Matrix[1];
  61764. BABYLON.Matrix.IdentityToRef(tmat2);
  61765. tmat2.m[12] = x;
  61766. tmat2.m[13] = y;
  61767. tmat2.m[14] = z;
  61768. tmat2.multiplyToRef(tmat, tmat);
  61769. }
  61770. if (parentBone) {
  61771. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  61772. }
  61773. tmat.multiplyToRef(meshMat, tmat);
  61774. position.x = tmat.m[12];
  61775. position.y = tmat.m[13];
  61776. position.z = tmat.m[14];
  61777. };
  61778. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  61779. var len = bones.length;
  61780. var meshPos = this.mesh.position;
  61781. for (var i = 0; i < len; i++) {
  61782. var bone = bones[i];
  61783. var points = this._debugLines[i];
  61784. if (!points) {
  61785. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61786. this._debugLines[i] = points;
  61787. }
  61788. this._getBonePosition(points[0], bone, meshMat);
  61789. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  61790. points[0].subtractInPlace(meshPos);
  61791. points[1].subtractInPlace(meshPos);
  61792. }
  61793. };
  61794. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  61795. var len = bones.length;
  61796. var boneNum = 0;
  61797. var meshPos = this.mesh.position;
  61798. for (var i = len - 1; i >= 0; i--) {
  61799. var childBone = bones[i];
  61800. var parentBone = childBone.getParent();
  61801. if (!parentBone) {
  61802. continue;
  61803. }
  61804. var points = this._debugLines[boneNum];
  61805. if (!points) {
  61806. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61807. this._debugLines[boneNum] = points;
  61808. }
  61809. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  61810. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  61811. points[0].subtractInPlace(meshPos);
  61812. points[1].subtractInPlace(meshPos);
  61813. boneNum++;
  61814. }
  61815. };
  61816. /** Update the viewer to sync with current skeleton state */
  61817. SkeletonViewer.prototype.update = function () {
  61818. if (this.autoUpdateBonesMatrices) {
  61819. this.skeleton.computeAbsoluteTransforms();
  61820. }
  61821. if (this.skeleton.bones[0].length === undefined) {
  61822. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61823. }
  61824. else {
  61825. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  61826. }
  61827. if (!this._debugMesh) {
  61828. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  61829. this._debugMesh.renderingGroupId = this.renderingGroupId;
  61830. }
  61831. else {
  61832. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  61833. }
  61834. this._debugMesh.position.copyFrom(this.mesh.position);
  61835. this._debugMesh.color = this.color;
  61836. };
  61837. /** Release associated resources */
  61838. SkeletonViewer.prototype.dispose = function () {
  61839. if (this._debugMesh) {
  61840. this.isEnabled = false;
  61841. this._debugMesh.dispose();
  61842. this._debugMesh = null;
  61843. }
  61844. };
  61845. return SkeletonViewer;
  61846. }());
  61847. Debug.SkeletonViewer = SkeletonViewer;
  61848. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61849. })(BABYLON || (BABYLON = {}));
  61850. //# sourceMappingURL=babylon.skeletonViewer.js.map
  61851. /**
  61852. * Module Debug contains the (visual) components to debug a scene correctly
  61853. */
  61854. var BABYLON;
  61855. (function (BABYLON) {
  61856. var Debug;
  61857. (function (Debug) {
  61858. /**
  61859. * The Axes viewer will show 3 axes in a specific point in space
  61860. */
  61861. var AxesViewer = /** @class */ (function () {
  61862. /**
  61863. * Creates a new AxesViewer
  61864. * @param scene defines the hosting scene
  61865. * @param scaleLines defines a number used to scale line length (1 by default)
  61866. */
  61867. function AxesViewer(scene, scaleLines) {
  61868. if (scaleLines === void 0) { scaleLines = 1; }
  61869. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61870. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61871. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61872. /**
  61873. * Gets or sets a number used to scale line length
  61874. */
  61875. this.scaleLines = 1;
  61876. this.scaleLines = scaleLines;
  61877. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  61878. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  61879. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  61880. this._xmesh.renderingGroupId = 2;
  61881. this._ymesh.renderingGroupId = 2;
  61882. this._zmesh.renderingGroupId = 2;
  61883. this._xmesh.material.checkReadyOnlyOnce = true;
  61884. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  61885. this._ymesh.material.checkReadyOnlyOnce = true;
  61886. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  61887. this._zmesh.material.checkReadyOnlyOnce = true;
  61888. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  61889. this.scene = scene;
  61890. }
  61891. /**
  61892. * Force the viewer to update
  61893. * @param position defines the position of the viewer
  61894. * @param xaxis defines the x axis of the viewer
  61895. * @param yaxis defines the y axis of the viewer
  61896. * @param zaxis defines the z axis of the viewer
  61897. */
  61898. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  61899. var scaleLines = this.scaleLines;
  61900. if (this._xmesh) {
  61901. this._xmesh.position.copyFrom(position);
  61902. }
  61903. if (this._ymesh) {
  61904. this._ymesh.position.copyFrom(position);
  61905. }
  61906. if (this._zmesh) {
  61907. this._zmesh.position.copyFrom(position);
  61908. }
  61909. var point2 = this._xline[1];
  61910. point2.x = xaxis.x * scaleLines;
  61911. point2.y = xaxis.y * scaleLines;
  61912. point2.z = xaxis.z * scaleLines;
  61913. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  61914. point2 = this._yline[1];
  61915. point2.x = yaxis.x * scaleLines;
  61916. point2.y = yaxis.y * scaleLines;
  61917. point2.z = yaxis.z * scaleLines;
  61918. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  61919. point2 = this._zline[1];
  61920. point2.x = zaxis.x * scaleLines;
  61921. point2.y = zaxis.y * scaleLines;
  61922. point2.z = zaxis.z * scaleLines;
  61923. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  61924. };
  61925. /** Releases resources */
  61926. AxesViewer.prototype.dispose = function () {
  61927. if (this._xmesh) {
  61928. this._xmesh.dispose();
  61929. }
  61930. if (this._ymesh) {
  61931. this._ymesh.dispose();
  61932. }
  61933. if (this._zmesh) {
  61934. this._zmesh.dispose();
  61935. }
  61936. this._xmesh = null;
  61937. this._ymesh = null;
  61938. this._zmesh = null;
  61939. this.scene = null;
  61940. };
  61941. return AxesViewer;
  61942. }());
  61943. Debug.AxesViewer = AxesViewer;
  61944. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  61945. })(BABYLON || (BABYLON = {}));
  61946. //# sourceMappingURL=babylon.axesViewer.js.map
  61947. var BABYLON;
  61948. (function (BABYLON) {
  61949. var Debug;
  61950. (function (Debug) {
  61951. /**
  61952. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  61953. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  61954. */
  61955. var BoneAxesViewer = /** @class */ (function (_super) {
  61956. __extends(BoneAxesViewer, _super);
  61957. /**
  61958. * Creates a new BoneAxesViewer
  61959. * @param scene defines the hosting scene
  61960. * @param bone defines the target bone
  61961. * @param mesh defines the target mesh
  61962. * @param scaleLines defines a scaling factor for line length (1 by default)
  61963. */
  61964. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  61965. if (scaleLines === void 0) { scaleLines = 1; }
  61966. var _this = _super.call(this, scene, scaleLines) || this;
  61967. /** Gets current position */
  61968. _this.pos = BABYLON.Vector3.Zero();
  61969. /** Gets direction of X axis */
  61970. _this.xaxis = BABYLON.Vector3.Zero();
  61971. /** Gets direction of Y axis */
  61972. _this.yaxis = BABYLON.Vector3.Zero();
  61973. /** Gets direction of Z axis */
  61974. _this.zaxis = BABYLON.Vector3.Zero();
  61975. _this.mesh = mesh;
  61976. _this.bone = bone;
  61977. return _this;
  61978. }
  61979. /**
  61980. * Force the viewer to update
  61981. */
  61982. BoneAxesViewer.prototype.update = function () {
  61983. if (!this.mesh || !this.bone) {
  61984. return;
  61985. }
  61986. var bone = this.bone;
  61987. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  61988. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  61989. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  61990. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  61991. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  61992. };
  61993. /** Releases resources */
  61994. BoneAxesViewer.prototype.dispose = function () {
  61995. if (this.mesh) {
  61996. this.mesh = null;
  61997. this.bone = null;
  61998. _super.prototype.dispose.call(this);
  61999. }
  62000. };
  62001. return BoneAxesViewer;
  62002. }(Debug.AxesViewer));
  62003. Debug.BoneAxesViewer = BoneAxesViewer;
  62004. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62005. })(BABYLON || (BABYLON = {}));
  62006. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62007. var BABYLON;
  62008. (function (BABYLON) {
  62009. var RayHelper = /** @class */ (function () {
  62010. function RayHelper(ray) {
  62011. this.ray = ray;
  62012. }
  62013. RayHelper.CreateAndShow = function (ray, scene, color) {
  62014. var helper = new RayHelper(ray);
  62015. helper.show(scene, color);
  62016. return helper;
  62017. };
  62018. RayHelper.prototype.show = function (scene, color) {
  62019. if (!this._renderFunction && this.ray) {
  62020. var ray = this.ray;
  62021. this._renderFunction = this._render.bind(this);
  62022. this._scene = scene;
  62023. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62024. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62025. if (this._renderFunction) {
  62026. this._scene.registerBeforeRender(this._renderFunction);
  62027. }
  62028. }
  62029. if (color && this._renderLine) {
  62030. this._renderLine.color.copyFrom(color);
  62031. }
  62032. };
  62033. RayHelper.prototype.hide = function () {
  62034. if (this._renderFunction && this._scene) {
  62035. this._scene.unregisterBeforeRender(this._renderFunction);
  62036. this._scene = null;
  62037. this._renderFunction = null;
  62038. if (this._renderLine) {
  62039. this._renderLine.dispose();
  62040. this._renderLine = null;
  62041. }
  62042. this._renderPoints = [];
  62043. }
  62044. };
  62045. RayHelper.prototype._render = function () {
  62046. var ray = this.ray;
  62047. if (!ray) {
  62048. return;
  62049. }
  62050. var point = this._renderPoints[1];
  62051. var len = Math.min(ray.length, 1000000);
  62052. point.copyFrom(ray.direction);
  62053. point.scaleInPlace(len);
  62054. point.addInPlace(ray.origin);
  62055. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62056. };
  62057. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62058. this._attachedToMesh = mesh;
  62059. var ray = this.ray;
  62060. if (!ray) {
  62061. return;
  62062. }
  62063. if (!ray.direction) {
  62064. ray.direction = BABYLON.Vector3.Zero();
  62065. }
  62066. if (!ray.origin) {
  62067. ray.origin = BABYLON.Vector3.Zero();
  62068. }
  62069. if (length) {
  62070. ray.length = length;
  62071. }
  62072. if (!meshSpaceOrigin) {
  62073. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62074. }
  62075. if (!meshSpaceDirection) {
  62076. // -1 so that this will work with Mesh.lookAt
  62077. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62078. }
  62079. if (!this._meshSpaceDirection) {
  62080. this._meshSpaceDirection = meshSpaceDirection.clone();
  62081. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62082. }
  62083. else {
  62084. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62085. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62086. }
  62087. if (!this._updateToMeshFunction) {
  62088. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62089. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62090. }
  62091. this._updateToMesh();
  62092. };
  62093. RayHelper.prototype.detachFromMesh = function () {
  62094. if (this._attachedToMesh) {
  62095. if (this._updateToMeshFunction) {
  62096. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62097. }
  62098. this._attachedToMesh = null;
  62099. this._updateToMeshFunction = null;
  62100. }
  62101. };
  62102. RayHelper.prototype._updateToMesh = function () {
  62103. var ray = this.ray;
  62104. if (!this._attachedToMesh || !ray) {
  62105. return;
  62106. }
  62107. if (this._attachedToMesh._isDisposed) {
  62108. this.detachFromMesh();
  62109. return;
  62110. }
  62111. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62112. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62113. };
  62114. RayHelper.prototype.dispose = function () {
  62115. this.hide();
  62116. this.detachFromMesh();
  62117. this.ray = null;
  62118. };
  62119. return RayHelper;
  62120. }());
  62121. BABYLON.RayHelper = RayHelper;
  62122. })(BABYLON || (BABYLON = {}));
  62123. //# sourceMappingURL=babylon.rayHelper.js.map
  62124. var BABYLON;
  62125. (function (BABYLON) {
  62126. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  62127. get: function () {
  62128. if (!this._debugLayer) {
  62129. this._debugLayer = new DebugLayer(this);
  62130. }
  62131. return this._debugLayer;
  62132. },
  62133. enumerable: true,
  62134. configurable: true
  62135. });
  62136. var DebugLayer = /** @class */ (function () {
  62137. function DebugLayer(scene) {
  62138. var _this = this;
  62139. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62140. this.onPropertyChangedObservable = new BABYLON.Observable();
  62141. this._scene = scene;
  62142. this._scene.onDisposeObservable.add(function () {
  62143. // Debug layer
  62144. if (_this._scene._debugLayer) {
  62145. _this._scene._debugLayer.hide();
  62146. }
  62147. });
  62148. }
  62149. /** Creates the inspector window. */
  62150. DebugLayer.prototype._createInspector = function (config) {
  62151. if (config === void 0) { config = {}; }
  62152. var popup = config.popup || false;
  62153. var initialTab = config.initialTab || 0;
  62154. var parentElement = config.parentElement || null;
  62155. if (!this._inspector) {
  62156. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  62157. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62158. } // else nothing to do as instance is already created
  62159. };
  62160. DebugLayer.prototype.isVisible = function () {
  62161. if (!this._inspector) {
  62162. return false;
  62163. }
  62164. return true;
  62165. };
  62166. DebugLayer.prototype.hide = function () {
  62167. if (this._inspector) {
  62168. try {
  62169. this._inspector.dispose();
  62170. }
  62171. catch (e) {
  62172. // If the inspector has been removed directly from the inspector tool
  62173. }
  62174. this.onPropertyChangedObservable.clear();
  62175. this._inspector = null;
  62176. }
  62177. };
  62178. /**
  62179. *
  62180. * Launch the debugLayer.
  62181. *
  62182. * initialTab:
  62183. * | Value | Tab Name |
  62184. * | --- | --- |
  62185. * | 0 | Scene |
  62186. * | 1 | Console |
  62187. * | 2 | Stats |
  62188. * | 3 | Textures |
  62189. * | 4 | Mesh |
  62190. * | 5 | Light |
  62191. * | 6 | Material |
  62192. * | 7 | GLTF |
  62193. * | 8 | GUI |
  62194. * | 9 | Physics |
  62195. * | 10 | Camera |
  62196. * | 11 | Audio |
  62197. *
  62198. */
  62199. DebugLayer.prototype.show = function (config) {
  62200. if (config === void 0) { config = {}; }
  62201. if (typeof this.BJSINSPECTOR == 'undefined') {
  62202. // Load inspector and add it to the DOM
  62203. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62204. }
  62205. else {
  62206. // Otherwise creates the inspector
  62207. this._createInspector(config);
  62208. }
  62209. };
  62210. /**
  62211. * Gets the active tab
  62212. * @return the index of the active tab or -1 if the inspector is hidden
  62213. */
  62214. DebugLayer.prototype.getActiveTab = function () {
  62215. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  62216. };
  62217. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62218. return DebugLayer;
  62219. }());
  62220. BABYLON.DebugLayer = DebugLayer;
  62221. })(BABYLON || (BABYLON = {}));
  62222. //# sourceMappingURL=babylon.debugLayer.js.map
  62223. var BABYLON;
  62224. (function (BABYLON) {
  62225. var Debug;
  62226. (function (Debug) {
  62227. /**
  62228. * Used to show the physics impostor around the specific mesh
  62229. */
  62230. var PhysicsViewer = /** @class */ (function () {
  62231. /**
  62232. * Creates a new PhysicsViewer
  62233. * @param scene defines the hosting scene
  62234. */
  62235. function PhysicsViewer(scene) {
  62236. /** @hidden */
  62237. this._impostors = [];
  62238. /** @hidden */
  62239. this._meshes = [];
  62240. /** @hidden */
  62241. this._numMeshes = 0;
  62242. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62243. var physicEngine = this._scene.getPhysicsEngine();
  62244. if (physicEngine) {
  62245. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  62246. }
  62247. }
  62248. /** @hidden */
  62249. PhysicsViewer.prototype._updateDebugMeshes = function () {
  62250. var plugin = this._physicsEnginePlugin;
  62251. for (var i = 0; i < this._numMeshes; i++) {
  62252. var impostor = this._impostors[i];
  62253. if (!impostor) {
  62254. continue;
  62255. }
  62256. if (impostor.isDisposed) {
  62257. this.hideImpostor(this._impostors[i--]);
  62258. }
  62259. else {
  62260. var mesh = this._meshes[i];
  62261. if (mesh && plugin) {
  62262. plugin.syncMeshWithImpostor(mesh, impostor);
  62263. }
  62264. }
  62265. }
  62266. };
  62267. /**
  62268. * Renders a specified physic impostor
  62269. * @param impostor defines the impostor to render
  62270. */
  62271. PhysicsViewer.prototype.showImpostor = function (impostor) {
  62272. if (!this._scene) {
  62273. return;
  62274. }
  62275. for (var i = 0; i < this._numMeshes; i++) {
  62276. if (this._impostors[i] == impostor) {
  62277. return;
  62278. }
  62279. }
  62280. var debugMesh = this._getDebugMesh(impostor, this._scene);
  62281. if (debugMesh) {
  62282. this._impostors[this._numMeshes] = impostor;
  62283. this._meshes[this._numMeshes] = debugMesh;
  62284. if (this._numMeshes === 0) {
  62285. this._renderFunction = this._updateDebugMeshes.bind(this);
  62286. this._scene.registerBeforeRender(this._renderFunction);
  62287. }
  62288. this._numMeshes++;
  62289. }
  62290. };
  62291. /**
  62292. * Hides a specified physic impostor
  62293. * @param impostor defines the impostor to hide
  62294. */
  62295. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  62296. if (!impostor || !this._scene) {
  62297. return;
  62298. }
  62299. var removed = false;
  62300. for (var i = 0; i < this._numMeshes; i++) {
  62301. if (this._impostors[i] == impostor) {
  62302. var mesh = this._meshes[i];
  62303. if (!mesh) {
  62304. continue;
  62305. }
  62306. this._scene.removeMesh(mesh);
  62307. mesh.dispose();
  62308. this._numMeshes--;
  62309. if (this._numMeshes > 0) {
  62310. this._meshes[i] = this._meshes[this._numMeshes];
  62311. this._impostors[i] = this._impostors[this._numMeshes];
  62312. this._meshes[this._numMeshes] = null;
  62313. this._impostors[this._numMeshes] = null;
  62314. }
  62315. else {
  62316. this._meshes[0] = null;
  62317. this._impostors[0] = null;
  62318. }
  62319. removed = true;
  62320. break;
  62321. }
  62322. }
  62323. if (removed && this._numMeshes === 0) {
  62324. this._scene.unregisterBeforeRender(this._renderFunction);
  62325. }
  62326. };
  62327. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  62328. if (!this._debugMaterial) {
  62329. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  62330. this._debugMaterial.wireframe = true;
  62331. }
  62332. return this._debugMaterial;
  62333. };
  62334. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  62335. if (!this._debugBoxMesh) {
  62336. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  62337. this._debugBoxMesh.renderingGroupId = 1;
  62338. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62339. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  62340. scene.removeMesh(this._debugBoxMesh);
  62341. }
  62342. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  62343. };
  62344. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  62345. if (!this._debugSphereMesh) {
  62346. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  62347. this._debugSphereMesh.renderingGroupId = 1;
  62348. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  62349. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  62350. scene.removeMesh(this._debugSphereMesh);
  62351. }
  62352. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  62353. };
  62354. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  62355. var mesh = null;
  62356. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  62357. mesh = this._getDebugBoxMesh(scene);
  62358. impostor.getBoxSizeToRef(mesh.scaling);
  62359. }
  62360. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  62361. mesh = this._getDebugSphereMesh(scene);
  62362. var radius = impostor.getRadius();
  62363. mesh.scaling.x = radius * 2;
  62364. mesh.scaling.y = radius * 2;
  62365. mesh.scaling.z = radius * 2;
  62366. }
  62367. return mesh;
  62368. };
  62369. /** Releases all resources */
  62370. PhysicsViewer.prototype.dispose = function () {
  62371. for (var i = 0; i < this._numMeshes; i++) {
  62372. this.hideImpostor(this._impostors[i]);
  62373. }
  62374. if (this._debugBoxMesh) {
  62375. this._debugBoxMesh.dispose();
  62376. }
  62377. if (this._debugSphereMesh) {
  62378. this._debugSphereMesh.dispose();
  62379. }
  62380. if (this._debugMaterial) {
  62381. this._debugMaterial.dispose();
  62382. }
  62383. this._impostors.length = 0;
  62384. this._scene = null;
  62385. this._physicsEnginePlugin = null;
  62386. };
  62387. return PhysicsViewer;
  62388. }());
  62389. Debug.PhysicsViewer = PhysicsViewer;
  62390. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62391. })(BABYLON || (BABYLON = {}));
  62392. //# sourceMappingURL=babylon.physicsViewer.js.map
  62393. var BABYLON;
  62394. (function (BABYLON) {
  62395. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  62396. get: function () {
  62397. return this._forceShowBoundingBoxes || false;
  62398. },
  62399. set: function (value) {
  62400. this._forceShowBoundingBoxes = value;
  62401. // Lazyly creates a BB renderer if needed.
  62402. if (value) {
  62403. this.getBoundingBoxRenderer();
  62404. }
  62405. },
  62406. enumerable: true,
  62407. configurable: true
  62408. });
  62409. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  62410. if (!this._boundingBoxRenderer) {
  62411. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  62412. }
  62413. return this._boundingBoxRenderer;
  62414. };
  62415. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  62416. get: function () {
  62417. return this._showBoundingBox || false;
  62418. },
  62419. set: function (value) {
  62420. this._showBoundingBox = value;
  62421. // Lazyly creates a BB renderer if needed.
  62422. if (value) {
  62423. this.getScene().getBoundingBoxRenderer();
  62424. }
  62425. },
  62426. enumerable: true,
  62427. configurable: true
  62428. });
  62429. var BoundingBoxRenderer = /** @class */ (function () {
  62430. function BoundingBoxRenderer(scene) {
  62431. /**
  62432. * The component name helpfull to identify the component in the list of scene components.
  62433. */
  62434. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  62435. this.frontColor = new BABYLON.Color3(1, 1, 1);
  62436. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  62437. this.showBackLines = true;
  62438. this.renderList = new BABYLON.SmartArray(32);
  62439. this._vertexBuffers = {};
  62440. this.scene = scene;
  62441. scene._addComponent(this);
  62442. }
  62443. /**
  62444. * Registers the component in a given scene
  62445. */
  62446. BoundingBoxRenderer.prototype.register = function () {
  62447. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  62448. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  62449. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  62450. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  62451. };
  62452. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  62453. if (mesh.showSubMeshesBoundingBox) {
  62454. var boundingInfo = subMesh.getBoundingInfo();
  62455. if (boundingInfo !== null && boundingInfo !== undefined) {
  62456. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62457. this.renderList.push(boundingInfo.boundingBox);
  62458. }
  62459. }
  62460. };
  62461. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  62462. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  62463. var boundingInfo = sourceMesh.getBoundingInfo();
  62464. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  62465. this.renderList.push(boundingInfo.boundingBox);
  62466. }
  62467. };
  62468. BoundingBoxRenderer.prototype._prepareRessources = function () {
  62469. if (this._colorShader) {
  62470. return;
  62471. }
  62472. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  62473. attributes: [BABYLON.VertexBuffer.PositionKind],
  62474. uniforms: ["world", "viewProjection", "color"]
  62475. });
  62476. var engine = this.scene.getEngine();
  62477. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  62478. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  62479. this._createIndexBuffer();
  62480. };
  62481. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  62482. var engine = this.scene.getEngine();
  62483. 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]);
  62484. };
  62485. /**
  62486. * Rebuilds the elements related to this component in case of
  62487. * context lost for instance.
  62488. */
  62489. BoundingBoxRenderer.prototype.rebuild = function () {
  62490. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62491. if (vb) {
  62492. vb._rebuild();
  62493. }
  62494. this._createIndexBuffer();
  62495. };
  62496. BoundingBoxRenderer.prototype.reset = function () {
  62497. this.renderList.reset();
  62498. };
  62499. /**
  62500. * Render the bounding boxes of a specific rendering group
  62501. * @param renderingGroupId defines the rendering group to render
  62502. */
  62503. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  62504. if (this.renderList.length === 0) {
  62505. return;
  62506. }
  62507. this._prepareRessources();
  62508. if (!this._colorShader.isReady()) {
  62509. return;
  62510. }
  62511. var engine = this.scene.getEngine();
  62512. engine.setDepthWrite(false);
  62513. this._colorShader._preBind();
  62514. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  62515. var boundingBox = this.renderList.data[boundingBoxIndex];
  62516. if (boundingBox._tag !== renderingGroupId) {
  62517. continue;
  62518. }
  62519. var min = boundingBox.minimum;
  62520. var max = boundingBox.maximum;
  62521. var diff = max.subtract(min);
  62522. var median = min.add(diff.scale(0.5));
  62523. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62524. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62525. .multiply(boundingBox.getWorldMatrix());
  62526. // VBOs
  62527. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62528. if (this.showBackLines) {
  62529. // Back
  62530. engine.setDepthFunctionToGreaterOrEqual();
  62531. this.scene.resetCachedMaterial();
  62532. this._colorShader.setColor4("color", this.backColor.toColor4());
  62533. this._colorShader.bind(worldMatrix);
  62534. // Draw order
  62535. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62536. }
  62537. // Front
  62538. engine.setDepthFunctionToLess();
  62539. this.scene.resetCachedMaterial();
  62540. this._colorShader.setColor4("color", this.frontColor.toColor4());
  62541. this._colorShader.bind(worldMatrix);
  62542. // Draw order
  62543. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62544. }
  62545. this._colorShader.unbind();
  62546. engine.setDepthFunctionToLessOrEqual();
  62547. engine.setDepthWrite(true);
  62548. };
  62549. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  62550. this._prepareRessources();
  62551. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  62552. return;
  62553. }
  62554. var engine = this.scene.getEngine();
  62555. engine.setDepthWrite(false);
  62556. engine.setColorWrite(false);
  62557. this._colorShader._preBind();
  62558. var boundingBox = mesh._boundingInfo.boundingBox;
  62559. var min = boundingBox.minimum;
  62560. var max = boundingBox.maximum;
  62561. var diff = max.subtract(min);
  62562. var median = min.add(diff.scale(0.5));
  62563. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  62564. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  62565. .multiply(boundingBox.getWorldMatrix());
  62566. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  62567. engine.setDepthFunctionToLess();
  62568. this.scene.resetCachedMaterial();
  62569. this._colorShader.bind(worldMatrix);
  62570. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  62571. this._colorShader.unbind();
  62572. engine.setDepthFunctionToLessOrEqual();
  62573. engine.setDepthWrite(true);
  62574. engine.setColorWrite(true);
  62575. };
  62576. BoundingBoxRenderer.prototype.dispose = function () {
  62577. if (!this._colorShader) {
  62578. return;
  62579. }
  62580. this.renderList.dispose();
  62581. this._colorShader.dispose();
  62582. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62583. if (buffer) {
  62584. buffer.dispose();
  62585. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62586. }
  62587. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  62588. };
  62589. return BoundingBoxRenderer;
  62590. }());
  62591. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  62592. })(BABYLON || (BABYLON = {}));
  62593. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  62594. var BABYLON;
  62595. (function (BABYLON) {
  62596. BABYLON.Engine.prototype.createTransformFeedback = function () {
  62597. return this._gl.createTransformFeedback();
  62598. };
  62599. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  62600. this._gl.deleteTransformFeedback(value);
  62601. };
  62602. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  62603. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  62604. };
  62605. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  62606. if (usePoints === void 0) { usePoints = true; }
  62607. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  62608. };
  62609. BABYLON.Engine.prototype.endTransformFeedback = function () {
  62610. this._gl.endTransformFeedback();
  62611. };
  62612. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  62613. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  62614. };
  62615. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  62616. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  62617. };
  62618. })(BABYLON || (BABYLON = {}));
  62619. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  62620. var BABYLON;
  62621. (function (BABYLON) {
  62622. /**
  62623. * This represents a GPU particle system in Babylon
  62624. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  62625. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  62626. */
  62627. var GPUParticleSystem = /** @class */ (function (_super) {
  62628. __extends(GPUParticleSystem, _super);
  62629. /**
  62630. * Instantiates a GPU particle system.
  62631. * 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.
  62632. * @param name The name of the particle system
  62633. * @param options The options used to create the system
  62634. * @param scene The scene the particle system belongs to
  62635. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  62636. */
  62637. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  62638. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  62639. var _this = _super.call(this, name) || this;
  62640. /**
  62641. * The layer mask we are rendering the particles through.
  62642. */
  62643. _this.layerMask = 0x0FFFFFFF;
  62644. _this._accumulatedCount = 0;
  62645. _this._targetIndex = 0;
  62646. _this._currentRenderId = -1;
  62647. _this._started = false;
  62648. _this._stopped = false;
  62649. _this._timeDelta = 0;
  62650. _this._attributesStrideSize = 21;
  62651. _this._actualFrame = 0;
  62652. _this._rawTextureWidth = 256;
  62653. /**
  62654. * An event triggered when the system is disposed.
  62655. */
  62656. _this.onDisposeObservable = new BABYLON.Observable();
  62657. /**
  62658. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  62659. * to override the particles.
  62660. */
  62661. _this.forceDepthWrite = false;
  62662. _this._preWarmDone = false;
  62663. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62664. // Setup the default processing configuration to the scene.
  62665. _this._attachImageProcessingConfiguration(null);
  62666. _this._engine = _this._scene.getEngine();
  62667. if (!options.randomTextureSize) {
  62668. delete options.randomTextureSize;
  62669. }
  62670. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  62671. var optionsAsNumber = options;
  62672. if (isFinite(optionsAsNumber)) {
  62673. fullOptions.capacity = optionsAsNumber;
  62674. }
  62675. _this._capacity = fullOptions.capacity;
  62676. _this._activeCount = fullOptions.capacity;
  62677. _this._currentActiveCount = 0;
  62678. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  62679. _this._scene.particleSystems.push(_this);
  62680. _this._updateEffectOptions = {
  62681. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  62682. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  62683. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  62684. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  62685. uniformBuffersNames: [],
  62686. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  62687. defines: "",
  62688. fallbacks: null,
  62689. onCompiled: null,
  62690. onError: null,
  62691. indexParameters: null,
  62692. maxSimultaneousLights: 0,
  62693. transformFeedbackVaryings: []
  62694. };
  62695. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  62696. // Random data
  62697. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  62698. var d = [];
  62699. for (var i = 0; i < maxTextureSize; ++i) {
  62700. d.push(Math.random());
  62701. d.push(Math.random());
  62702. d.push(Math.random());
  62703. d.push(Math.random());
  62704. }
  62705. _this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  62706. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62707. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62708. d = [];
  62709. for (var i = 0; i < maxTextureSize; ++i) {
  62710. d.push(Math.random());
  62711. d.push(Math.random());
  62712. d.push(Math.random());
  62713. d.push(Math.random());
  62714. }
  62715. _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  62716. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62717. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62718. _this._randomTextureSize = maxTextureSize;
  62719. return _this;
  62720. }
  62721. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  62722. /**
  62723. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  62724. */
  62725. get: function () {
  62726. if (!BABYLON.Engine.LastCreatedEngine) {
  62727. return false;
  62728. }
  62729. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  62730. },
  62731. enumerable: true,
  62732. configurable: true
  62733. });
  62734. /**
  62735. * Gets the maximum number of particles active at the same time.
  62736. * @returns The max number of active particles.
  62737. */
  62738. GPUParticleSystem.prototype.getCapacity = function () {
  62739. return this._capacity;
  62740. };
  62741. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  62742. /**
  62743. * Gets or set the number of active particles
  62744. */
  62745. get: function () {
  62746. return this._activeCount;
  62747. },
  62748. set: function (value) {
  62749. this._activeCount = Math.min(value, this._capacity);
  62750. },
  62751. enumerable: true,
  62752. configurable: true
  62753. });
  62754. /**
  62755. * Is this system ready to be used/rendered
  62756. * @return true if the system is ready
  62757. */
  62758. GPUParticleSystem.prototype.isReady = function () {
  62759. if (!this._updateEffect) {
  62760. this._recreateUpdateEffect();
  62761. this._recreateRenderEffect();
  62762. return false;
  62763. }
  62764. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  62765. return false;
  62766. }
  62767. return true;
  62768. };
  62769. /**
  62770. * Gets if the system has been started. (Note: this will still be true after stop is called)
  62771. * @returns True if it has been started, otherwise false.
  62772. */
  62773. GPUParticleSystem.prototype.isStarted = function () {
  62774. return this._started;
  62775. };
  62776. /**
  62777. * Starts the particle system and begins to emit
  62778. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  62779. */
  62780. GPUParticleSystem.prototype.start = function (delay) {
  62781. var _this = this;
  62782. if (delay === void 0) { delay = this.startDelay; }
  62783. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  62784. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  62785. }
  62786. if (delay) {
  62787. setTimeout(function () {
  62788. _this.start(0);
  62789. }, delay);
  62790. return;
  62791. }
  62792. this._started = true;
  62793. this._stopped = false;
  62794. this._preWarmDone = false;
  62795. };
  62796. /**
  62797. * Stops the particle system.
  62798. */
  62799. GPUParticleSystem.prototype.stop = function () {
  62800. this._stopped = true;
  62801. };
  62802. /**
  62803. * Remove all active particles
  62804. */
  62805. GPUParticleSystem.prototype.reset = function () {
  62806. this._releaseBuffers();
  62807. this._releaseVAOs();
  62808. this._currentActiveCount = 0;
  62809. this._targetIndex = 0;
  62810. };
  62811. /**
  62812. * Returns the string "GPUParticleSystem"
  62813. * @returns a string containing the class name
  62814. */
  62815. GPUParticleSystem.prototype.getClassName = function () {
  62816. return "GPUParticleSystem";
  62817. };
  62818. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  62819. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  62820. this._releaseBuffers();
  62821. return this;
  62822. };
  62823. /**
  62824. * Adds a new color gradient
  62825. * @param gradient defines the gradient to use (between 0 and 1)
  62826. * @param color1 defines the color to affect to the specified gradient
  62827. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  62828. * @returns the current particle system
  62829. */
  62830. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  62831. if (!this._colorGradients) {
  62832. this._colorGradients = [];
  62833. }
  62834. var colorGradient = new BABYLON.ColorGradient();
  62835. colorGradient.gradient = gradient;
  62836. colorGradient.color1 = color1;
  62837. this._colorGradients.push(colorGradient);
  62838. this._colorGradients.sort(function (a, b) {
  62839. if (a.gradient < b.gradient) {
  62840. return -1;
  62841. }
  62842. else if (a.gradient > b.gradient) {
  62843. return 1;
  62844. }
  62845. return 0;
  62846. });
  62847. if (this._colorGradientsTexture) {
  62848. this._colorGradientsTexture.dispose();
  62849. this._colorGradientsTexture = null;
  62850. }
  62851. this._releaseBuffers();
  62852. return this;
  62853. };
  62854. /**
  62855. * Remove a specific color gradient
  62856. * @param gradient defines the gradient to remove
  62857. * @returns the current particle system
  62858. */
  62859. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  62860. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  62861. this._colorGradientsTexture = null;
  62862. return this;
  62863. };
  62864. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  62865. var valueGradient = new BABYLON.FactorGradient();
  62866. valueGradient.gradient = gradient;
  62867. valueGradient.factor1 = factor;
  62868. factorGradients.push(valueGradient);
  62869. factorGradients.sort(function (a, b) {
  62870. if (a.gradient < b.gradient) {
  62871. return -1;
  62872. }
  62873. else if (a.gradient > b.gradient) {
  62874. return 1;
  62875. }
  62876. return 0;
  62877. });
  62878. this._releaseBuffers();
  62879. };
  62880. /**
  62881. * Adds a new size gradient
  62882. * @param gradient defines the gradient to use (between 0 and 1)
  62883. * @param factor defines the size factor to affect to the specified gradient
  62884. * @returns the current particle system
  62885. */
  62886. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  62887. if (!this._sizeGradients) {
  62888. this._sizeGradients = [];
  62889. }
  62890. this._addFactorGradient(this._sizeGradients, gradient, factor);
  62891. if (this._sizeGradientsTexture) {
  62892. this._sizeGradientsTexture.dispose();
  62893. this._sizeGradientsTexture = null;
  62894. }
  62895. this._releaseBuffers();
  62896. return this;
  62897. };
  62898. /**
  62899. * Remove a specific size gradient
  62900. * @param gradient defines the gradient to remove
  62901. * @returns the current particle system
  62902. */
  62903. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  62904. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  62905. this._sizeGradientsTexture = null;
  62906. return this;
  62907. };
  62908. /**
  62909. * Adds a new angular speed gradient
  62910. * @param gradient defines the gradient to use (between 0 and 1)
  62911. * @param factor defines the angular speed to affect to the specified gradient
  62912. * @returns the current particle system
  62913. */
  62914. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  62915. if (!this._angularSpeedGradients) {
  62916. this._angularSpeedGradients = [];
  62917. }
  62918. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  62919. if (this._angularSpeedGradientsTexture) {
  62920. this._angularSpeedGradientsTexture.dispose();
  62921. this._angularSpeedGradientsTexture = null;
  62922. }
  62923. this._releaseBuffers();
  62924. return this;
  62925. };
  62926. /**
  62927. * Remove a specific angular speed gradient
  62928. * @param gradient defines the gradient to remove
  62929. * @returns the current particle system
  62930. */
  62931. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  62932. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  62933. this._angularSpeedGradientsTexture = null;
  62934. return this;
  62935. };
  62936. /**
  62937. * Adds a new velocity gradient
  62938. * @param gradient defines the gradient to use (between 0 and 1)
  62939. * @param factor defines the velocity to affect to the specified gradient
  62940. * @returns the current particle system
  62941. */
  62942. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  62943. if (!this._velocityGradients) {
  62944. this._velocityGradients = [];
  62945. }
  62946. this._addFactorGradient(this._velocityGradients, gradient, factor);
  62947. if (this._velocityGradientsTexture) {
  62948. this._velocityGradientsTexture.dispose();
  62949. this._velocityGradientsTexture = null;
  62950. }
  62951. this._releaseBuffers();
  62952. return this;
  62953. };
  62954. /**
  62955. * Remove a specific velocity gradient
  62956. * @param gradient defines the gradient to remove
  62957. * @returns the current particle system
  62958. */
  62959. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  62960. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  62961. this._velocityGradientsTexture = null;
  62962. return this;
  62963. };
  62964. /**
  62965. * Adds a new limit velocity gradient
  62966. * @param gradient defines the gradient to use (between 0 and 1)
  62967. * @param factor defines the limit velocity value to affect to the specified gradient
  62968. * @returns the current particle system
  62969. */
  62970. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  62971. if (!this._limitVelocityGradients) {
  62972. this._limitVelocityGradients = [];
  62973. }
  62974. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  62975. if (this._limitVelocityGradientsTexture) {
  62976. this._limitVelocityGradientsTexture.dispose();
  62977. this._limitVelocityGradientsTexture = null;
  62978. }
  62979. this._releaseBuffers();
  62980. return this;
  62981. };
  62982. /**
  62983. * Remove a specific limit velocity gradient
  62984. * @param gradient defines the gradient to remove
  62985. * @returns the current particle system
  62986. */
  62987. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  62988. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  62989. this._limitVelocityGradientsTexture = null;
  62990. return this;
  62991. };
  62992. /**
  62993. * Adds a new drag gradient
  62994. * @param gradient defines the gradient to use (between 0 and 1)
  62995. * @param factor defines the drag value to affect to the specified gradient
  62996. * @returns the current particle system
  62997. */
  62998. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  62999. if (!this._dragGradients) {
  63000. this._dragGradients = [];
  63001. }
  63002. this._addFactorGradient(this._dragGradients, gradient, factor);
  63003. if (this._dragGradientsTexture) {
  63004. this._dragGradientsTexture.dispose();
  63005. this._dragGradientsTexture = null;
  63006. }
  63007. this._releaseBuffers();
  63008. return this;
  63009. };
  63010. /**
  63011. * Remove a specific drag gradient
  63012. * @param gradient defines the gradient to remove
  63013. * @returns the current particle system
  63014. */
  63015. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  63016. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  63017. this._dragGradientsTexture = null;
  63018. return this;
  63019. };
  63020. /**
  63021. * Not supported by GPUParticleSystem
  63022. * @param gradient defines the gradient to use (between 0 and 1)
  63023. * @param factor defines the emit rate value to affect to the specified gradient
  63024. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63025. * @returns the current particle system
  63026. */
  63027. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  63028. // Do nothing as emit rate is not supported by GPUParticleSystem
  63029. return this;
  63030. };
  63031. /**
  63032. * Not supported by GPUParticleSystem
  63033. * @param gradient defines the gradient to remove
  63034. * @returns the current particle system
  63035. */
  63036. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  63037. // Do nothing as emit rate is not supported by GPUParticleSystem
  63038. return this;
  63039. };
  63040. /**
  63041. * Not supported by GPUParticleSystem
  63042. * @param gradient defines the gradient to use (between 0 and 1)
  63043. * @param factor defines the start size value to affect to the specified gradient
  63044. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  63045. * @returns the current particle system
  63046. */
  63047. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  63048. // Do nothing as start size is not supported by GPUParticleSystem
  63049. return this;
  63050. };
  63051. /**
  63052. * Not supported by GPUParticleSystem
  63053. * @param gradient defines the gradient to remove
  63054. * @returns the current particle system
  63055. */
  63056. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  63057. // Do nothing as start size is not supported by GPUParticleSystem
  63058. return this;
  63059. };
  63060. /**
  63061. * Not supported by GPUParticleSystem
  63062. * @param gradient defines the gradient to use (between 0 and 1)
  63063. * @param min defines the color remap minimal range
  63064. * @param max defines the color remap maximal range
  63065. * @returns the current particle system
  63066. */
  63067. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  63068. // Do nothing as start size is not supported by GPUParticleSystem
  63069. return this;
  63070. };
  63071. /**
  63072. * Not supported by GPUParticleSystem
  63073. * @param gradient defines the gradient to remove
  63074. * @returns the current particle system
  63075. */
  63076. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  63077. // Do nothing as start size is not supported by GPUParticleSystem
  63078. return this;
  63079. };
  63080. /**
  63081. * Not supported by GPUParticleSystem
  63082. * @param gradient defines the gradient to use (between 0 and 1)
  63083. * @param min defines the alpha remap minimal range
  63084. * @param max defines the alpha remap maximal range
  63085. * @returns the current particle system
  63086. */
  63087. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  63088. // Do nothing as start size is not supported by GPUParticleSystem
  63089. return this;
  63090. };
  63091. /**
  63092. * Not supported by GPUParticleSystem
  63093. * @param gradient defines the gradient to remove
  63094. * @returns the current particle system
  63095. */
  63096. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  63097. // Do nothing as start size is not supported by GPUParticleSystem
  63098. return this;
  63099. };
  63100. /**
  63101. * Not supported by GPUParticleSystem
  63102. * @param gradient defines the gradient to use (between 0 and 1)
  63103. * @param color defines the color to affect to the specified gradient
  63104. * @returns the current particle system
  63105. */
  63106. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  63107. //Not supported by GPUParticleSystem
  63108. return this;
  63109. };
  63110. /**
  63111. * Not supported by GPUParticleSystem
  63112. * @param gradient defines the gradient to remove
  63113. * @returns the current particle system
  63114. */
  63115. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  63116. //Not supported by GPUParticleSystem
  63117. return this;
  63118. };
  63119. /**
  63120. * Not supported by GPUParticleSystem
  63121. * @returns the list of ramp gradients
  63122. */
  63123. GPUParticleSystem.prototype.getRampGradients = function () {
  63124. return null;
  63125. };
  63126. GPUParticleSystem.prototype._reset = function () {
  63127. this._releaseBuffers();
  63128. };
  63129. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  63130. var updateVertexBuffers = {};
  63131. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  63132. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  63133. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  63134. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  63135. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  63136. var offset = 12;
  63137. if (!this._colorGradientsTexture) {
  63138. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  63139. offset += 4;
  63140. }
  63141. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  63142. offset += 3;
  63143. if (!this._isBillboardBased) {
  63144. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  63145. offset += 3;
  63146. }
  63147. if (this._angularSpeedGradientsTexture) {
  63148. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  63149. offset += 1;
  63150. }
  63151. else {
  63152. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  63153. offset += 2;
  63154. }
  63155. if (this._isAnimationSheetEnabled) {
  63156. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  63157. offset += 1;
  63158. if (this.spriteRandomStartCell) {
  63159. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  63160. offset += 1;
  63161. }
  63162. }
  63163. if (this.noiseTexture) {
  63164. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  63165. offset += 3;
  63166. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  63167. offset += 3;
  63168. }
  63169. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  63170. this._engine.bindArrayBuffer(null);
  63171. return vao;
  63172. };
  63173. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  63174. var renderVertexBuffers = {};
  63175. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  63176. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  63177. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  63178. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  63179. var offset = 12;
  63180. if (!this._colorGradientsTexture) {
  63181. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  63182. offset += 4;
  63183. }
  63184. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  63185. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  63186. }
  63187. offset += 3; // Direction
  63188. if (!this._isBillboardBased) {
  63189. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  63190. offset += 3;
  63191. }
  63192. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  63193. if (this._angularSpeedGradientsTexture) {
  63194. offset++;
  63195. }
  63196. else {
  63197. offset += 2;
  63198. }
  63199. if (this._isAnimationSheetEnabled) {
  63200. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  63201. offset += 1;
  63202. if (this.spriteRandomStartCell) {
  63203. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  63204. offset += 1;
  63205. }
  63206. }
  63207. if (this.noiseTexture) {
  63208. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  63209. offset += 3;
  63210. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  63211. offset += 3;
  63212. }
  63213. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  63214. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  63215. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  63216. this._engine.bindArrayBuffer(null);
  63217. return vao;
  63218. };
  63219. GPUParticleSystem.prototype._initialize = function (force) {
  63220. if (force === void 0) { force = false; }
  63221. if (this._buffer0 && !force) {
  63222. return;
  63223. }
  63224. var engine = this._scene.getEngine();
  63225. var data = new Array();
  63226. if (!this.isBillboardBased) {
  63227. this._attributesStrideSize += 3;
  63228. }
  63229. if (this._colorGradientsTexture) {
  63230. this._attributesStrideSize -= 4;
  63231. }
  63232. if (this._angularSpeedGradientsTexture) {
  63233. this._attributesStrideSize -= 1;
  63234. }
  63235. if (this._isAnimationSheetEnabled) {
  63236. this._attributesStrideSize += 1;
  63237. if (this.spriteRandomStartCell) {
  63238. this._attributesStrideSize += 1;
  63239. }
  63240. }
  63241. if (this.noiseTexture) {
  63242. this._attributesStrideSize += 6;
  63243. }
  63244. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  63245. // position
  63246. data.push(0.0);
  63247. data.push(0.0);
  63248. data.push(0.0);
  63249. // Age and life
  63250. data.push(0.0); // create the particle as a dead one to create a new one at start
  63251. data.push(0.0);
  63252. // Seed
  63253. data.push(Math.random());
  63254. data.push(Math.random());
  63255. data.push(Math.random());
  63256. data.push(Math.random());
  63257. // Size
  63258. data.push(0.0);
  63259. data.push(0.0);
  63260. data.push(0.0);
  63261. if (!this._colorGradientsTexture) {
  63262. // color
  63263. data.push(0.0);
  63264. data.push(0.0);
  63265. data.push(0.0);
  63266. data.push(0.0);
  63267. }
  63268. // direction
  63269. data.push(0.0);
  63270. data.push(0.0);
  63271. data.push(0.0);
  63272. if (!this.isBillboardBased) {
  63273. // initialDirection
  63274. data.push(0.0);
  63275. data.push(0.0);
  63276. data.push(0.0);
  63277. }
  63278. // angle
  63279. data.push(0.0);
  63280. if (!this._angularSpeedGradientsTexture) {
  63281. data.push(0.0);
  63282. }
  63283. if (this._isAnimationSheetEnabled) {
  63284. data.push(0.0);
  63285. if (this.spriteRandomStartCell) {
  63286. data.push(0.0);
  63287. }
  63288. }
  63289. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  63290. data.push(Math.random());
  63291. data.push(Math.random());
  63292. data.push(Math.random());
  63293. data.push(Math.random());
  63294. data.push(Math.random());
  63295. data.push(Math.random());
  63296. }
  63297. }
  63298. // Sprite data
  63299. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  63300. -0.5, 0.5, 0, 1,
  63301. -0.5, -0.5, 0, 0,
  63302. 0.5, -0.5, 1, 0]);
  63303. // Buffers
  63304. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63305. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  63306. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  63307. // Update VAO
  63308. this._updateVAO = [];
  63309. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  63310. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  63311. // Render VAO
  63312. this._renderVAO = [];
  63313. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  63314. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  63315. // Links
  63316. this._sourceBuffer = this._buffer0;
  63317. this._targetBuffer = this._buffer1;
  63318. };
  63319. /** @hidden */
  63320. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  63321. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  63322. if (this._isBillboardBased) {
  63323. defines += "\n#define BILLBOARD";
  63324. }
  63325. if (this._colorGradientsTexture) {
  63326. defines += "\n#define COLORGRADIENTS";
  63327. }
  63328. if (this._sizeGradientsTexture) {
  63329. defines += "\n#define SIZEGRADIENTS";
  63330. }
  63331. if (this._angularSpeedGradientsTexture) {
  63332. defines += "\n#define ANGULARSPEEDGRADIENTS";
  63333. }
  63334. if (this._velocityGradientsTexture) {
  63335. defines += "\n#define VELOCITYGRADIENTS";
  63336. }
  63337. if (this._limitVelocityGradientsTexture) {
  63338. defines += "\n#define LIMITVELOCITYGRADIENTS";
  63339. }
  63340. if (this._dragGradientsTexture) {
  63341. defines += "\n#define DRAGGRADIENTS";
  63342. }
  63343. if (this.isAnimationSheetEnabled) {
  63344. defines += "\n#define ANIMATESHEET";
  63345. if (this.spriteRandomStartCell) {
  63346. defines += "\n#define ANIMATESHEETRANDOMSTART";
  63347. }
  63348. }
  63349. if (this.noiseTexture) {
  63350. defines += "\n#define NOISE";
  63351. }
  63352. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  63353. return;
  63354. }
  63355. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  63356. if (!this._colorGradientsTexture) {
  63357. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  63358. }
  63359. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  63360. if (!this._isBillboardBased) {
  63361. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  63362. }
  63363. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  63364. if (this.isAnimationSheetEnabled) {
  63365. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  63366. if (this.spriteRandomStartCell) {
  63367. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  63368. }
  63369. }
  63370. if (this.noiseTexture) {
  63371. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  63372. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  63373. }
  63374. this._updateEffectOptions.defines = defines;
  63375. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  63376. };
  63377. /** @hidden */
  63378. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  63379. var defines = "";
  63380. if (this._scene.clipPlane) {
  63381. defines = "\n#define CLIPPLANE";
  63382. }
  63383. if (this._scene.clipPlane2) {
  63384. defines = "\n#define CLIPPLANE2";
  63385. }
  63386. if (this._scene.clipPlane3) {
  63387. defines = "\n#define CLIPPLANE3";
  63388. }
  63389. if (this._scene.clipPlane4) {
  63390. defines = "\n#define CLIPPLANE4";
  63391. }
  63392. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  63393. defines = "\n#define BLENDMULTIPLYMODE";
  63394. }
  63395. if (this._isBillboardBased) {
  63396. defines += "\n#define BILLBOARD";
  63397. switch (this.billboardMode) {
  63398. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  63399. defines += "\n#define BILLBOARDY";
  63400. break;
  63401. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  63402. defines += "\n#define BILLBOARDSTRETCHED";
  63403. break;
  63404. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  63405. default:
  63406. break;
  63407. }
  63408. }
  63409. if (this._colorGradientsTexture) {
  63410. defines += "\n#define COLORGRADIENTS";
  63411. }
  63412. if (this.isAnimationSheetEnabled) {
  63413. defines += "\n#define ANIMATESHEET";
  63414. }
  63415. if (this._imageProcessingConfiguration) {
  63416. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  63417. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  63418. }
  63419. if (this._renderEffect && this._renderEffect.defines === defines) {
  63420. return;
  63421. }
  63422. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  63423. var samplers = ["textureSampler", "colorGradientSampler"];
  63424. if (BABYLON.ImageProcessingConfiguration) {
  63425. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  63426. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  63427. }
  63428. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  63429. };
  63430. /**
  63431. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  63432. * @param preWarm defines if we are in the pre-warmimg phase
  63433. */
  63434. GPUParticleSystem.prototype.animate = function (preWarm) {
  63435. if (preWarm === void 0) { preWarm = false; }
  63436. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  63437. this._actualFrame += this._timeDelta;
  63438. if (!this._stopped) {
  63439. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  63440. this.stop();
  63441. }
  63442. }
  63443. };
  63444. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  63445. var texture = this[textureName];
  63446. if (!factorGradients || !factorGradients.length || texture) {
  63447. return;
  63448. }
  63449. var data = new Float32Array(this._rawTextureWidth);
  63450. for (var x = 0; x < this._rawTextureWidth; x++) {
  63451. var ratio = x / this._rawTextureWidth;
  63452. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  63453. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  63454. });
  63455. }
  63456. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63457. };
  63458. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  63459. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  63460. };
  63461. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  63462. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  63463. };
  63464. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  63465. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  63466. };
  63467. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  63468. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  63469. };
  63470. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  63471. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  63472. };
  63473. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  63474. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  63475. return;
  63476. }
  63477. var data = new Uint8Array(this._rawTextureWidth * 4);
  63478. var tmpColor = BABYLON.Tmp.Color4[0];
  63479. for (var x = 0; x < this._rawTextureWidth; x++) {
  63480. var ratio = x / this._rawTextureWidth;
  63481. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  63482. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  63483. data[x * 4] = tmpColor.r * 255;
  63484. data[x * 4 + 1] = tmpColor.g * 255;
  63485. data[x * 4 + 2] = tmpColor.b * 255;
  63486. data[x * 4 + 3] = tmpColor.a * 255;
  63487. });
  63488. }
  63489. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  63490. };
  63491. /**
  63492. * Renders the particle system in its current state
  63493. * @param preWarm defines if the system should only update the particles but not render them
  63494. * @returns the current number of particles
  63495. */
  63496. GPUParticleSystem.prototype.render = function (preWarm) {
  63497. if (preWarm === void 0) { preWarm = false; }
  63498. if (!this._started) {
  63499. return 0;
  63500. }
  63501. this._createColorGradientTexture();
  63502. this._createSizeGradientTexture();
  63503. this._createAngularSpeedGradientTexture();
  63504. this._createVelocityGradientTexture();
  63505. this._createLimitVelocityGradientTexture();
  63506. this._createDragGradientTexture();
  63507. this._recreateUpdateEffect();
  63508. this._recreateRenderEffect();
  63509. if (!this.isReady()) {
  63510. return 0;
  63511. }
  63512. if (!preWarm) {
  63513. if (!this._preWarmDone && this.preWarmCycles) {
  63514. for (var index = 0; index < this.preWarmCycles; index++) {
  63515. this.animate(true);
  63516. this.render(true);
  63517. }
  63518. this._preWarmDone = true;
  63519. }
  63520. if (this._currentRenderId === this._scene.getRenderId()) {
  63521. return 0;
  63522. }
  63523. this._currentRenderId = this._scene.getRenderId();
  63524. }
  63525. // Get everything ready to render
  63526. this._initialize();
  63527. this._accumulatedCount += this.emitRate * this._timeDelta;
  63528. if (this._accumulatedCount > 1) {
  63529. var intPart = this._accumulatedCount | 0;
  63530. this._accumulatedCount -= intPart;
  63531. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  63532. }
  63533. if (!this._currentActiveCount) {
  63534. return 0;
  63535. }
  63536. // Enable update effect
  63537. this._engine.enableEffect(this._updateEffect);
  63538. this._engine.setState(false);
  63539. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  63540. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  63541. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  63542. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  63543. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  63544. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  63545. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  63546. if (!this._colorGradientsTexture) {
  63547. this._updateEffect.setDirectColor4("color1", this.color1);
  63548. this._updateEffect.setDirectColor4("color2", this.color2);
  63549. }
  63550. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  63551. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  63552. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  63553. this._updateEffect.setVector3("gravity", this.gravity);
  63554. if (this._sizeGradientsTexture) {
  63555. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  63556. }
  63557. if (this._angularSpeedGradientsTexture) {
  63558. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  63559. }
  63560. if (this._velocityGradientsTexture) {
  63561. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  63562. }
  63563. if (this._limitVelocityGradientsTexture) {
  63564. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  63565. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  63566. }
  63567. if (this._dragGradientsTexture) {
  63568. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  63569. }
  63570. if (this.particleEmitterType) {
  63571. this.particleEmitterType.applyToShader(this._updateEffect);
  63572. }
  63573. if (this._isAnimationSheetEnabled) {
  63574. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  63575. }
  63576. if (this.noiseTexture) {
  63577. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  63578. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  63579. }
  63580. var emitterWM;
  63581. if (this.emitter.position) {
  63582. var emitterMesh = this.emitter;
  63583. emitterWM = emitterMesh.getWorldMatrix();
  63584. }
  63585. else {
  63586. var emitterPosition = this.emitter;
  63587. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  63588. }
  63589. this._updateEffect.setMatrix("emitterWM", emitterWM);
  63590. // Bind source VAO
  63591. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  63592. // Update
  63593. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  63594. this._engine.setRasterizerState(false);
  63595. this._engine.beginTransformFeedback(true);
  63596. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  63597. this._engine.endTransformFeedback();
  63598. this._engine.setRasterizerState(true);
  63599. this._engine.bindTransformFeedbackBuffer(null);
  63600. if (!preWarm) {
  63601. // Enable render effect
  63602. this._engine.enableEffect(this._renderEffect);
  63603. var viewMatrix = this._scene.getViewMatrix();
  63604. this._renderEffect.setMatrix("view", viewMatrix);
  63605. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  63606. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  63607. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  63608. if (this._colorGradientsTexture) {
  63609. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  63610. }
  63611. else {
  63612. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  63613. }
  63614. if (this._isAnimationSheetEnabled && this.particleTexture) {
  63615. var baseSize = this.particleTexture.getBaseSize();
  63616. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  63617. }
  63618. if (this._isBillboardBased) {
  63619. var camera = this._scene.activeCamera;
  63620. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  63621. }
  63622. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  63623. var invView = viewMatrix.clone();
  63624. invView.invert();
  63625. this._renderEffect.setMatrix("invView", invView);
  63626. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  63627. }
  63628. // image processing
  63629. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  63630. this._imageProcessingConfiguration.bind(this._renderEffect);
  63631. }
  63632. // Draw order
  63633. switch (this.blendMode) {
  63634. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  63635. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  63636. break;
  63637. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  63638. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  63639. break;
  63640. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  63641. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  63642. break;
  63643. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  63644. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  63645. break;
  63646. }
  63647. if (this.forceDepthWrite) {
  63648. this._engine.setDepthWrite(true);
  63649. }
  63650. // Bind source VAO
  63651. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  63652. // Render
  63653. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  63654. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  63655. }
  63656. // Switch VAOs
  63657. this._targetIndex++;
  63658. if (this._targetIndex === 2) {
  63659. this._targetIndex = 0;
  63660. }
  63661. // Switch buffers
  63662. var tmpBuffer = this._sourceBuffer;
  63663. this._sourceBuffer = this._targetBuffer;
  63664. this._targetBuffer = tmpBuffer;
  63665. return this._currentActiveCount;
  63666. };
  63667. /**
  63668. * Rebuilds the particle system
  63669. */
  63670. GPUParticleSystem.prototype.rebuild = function () {
  63671. this._initialize(true);
  63672. };
  63673. GPUParticleSystem.prototype._releaseBuffers = function () {
  63674. if (this._buffer0) {
  63675. this._buffer0.dispose();
  63676. this._buffer0 = null;
  63677. }
  63678. if (this._buffer1) {
  63679. this._buffer1.dispose();
  63680. this._buffer1 = null;
  63681. }
  63682. if (this._spriteBuffer) {
  63683. this._spriteBuffer.dispose();
  63684. this._spriteBuffer = null;
  63685. }
  63686. };
  63687. GPUParticleSystem.prototype._releaseVAOs = function () {
  63688. if (!this._updateVAO) {
  63689. return;
  63690. }
  63691. for (var index = 0; index < this._updateVAO.length; index++) {
  63692. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  63693. }
  63694. this._updateVAO = [];
  63695. for (var index = 0; index < this._renderVAO.length; index++) {
  63696. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  63697. }
  63698. this._renderVAO = [];
  63699. };
  63700. /**
  63701. * Disposes the particle system and free the associated resources
  63702. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  63703. */
  63704. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  63705. if (disposeTexture === void 0) { disposeTexture = true; }
  63706. var index = this._scene.particleSystems.indexOf(this);
  63707. if (index > -1) {
  63708. this._scene.particleSystems.splice(index, 1);
  63709. }
  63710. this._releaseBuffers();
  63711. this._releaseVAOs();
  63712. if (this._colorGradientsTexture) {
  63713. this._colorGradientsTexture.dispose();
  63714. this._colorGradientsTexture = null;
  63715. }
  63716. if (this._sizeGradientsTexture) {
  63717. this._sizeGradientsTexture.dispose();
  63718. this._sizeGradientsTexture = null;
  63719. }
  63720. if (this._angularSpeedGradientsTexture) {
  63721. this._angularSpeedGradientsTexture.dispose();
  63722. this._angularSpeedGradientsTexture = null;
  63723. }
  63724. if (this._velocityGradientsTexture) {
  63725. this._velocityGradientsTexture.dispose();
  63726. this._velocityGradientsTexture = null;
  63727. }
  63728. if (this._limitVelocityGradientsTexture) {
  63729. this._limitVelocityGradientsTexture.dispose();
  63730. this._limitVelocityGradientsTexture = null;
  63731. }
  63732. if (this._dragGradientsTexture) {
  63733. this._dragGradientsTexture.dispose();
  63734. this._dragGradientsTexture = null;
  63735. }
  63736. if (this._randomTexture) {
  63737. this._randomTexture.dispose();
  63738. this._randomTexture = null;
  63739. }
  63740. if (this._randomTexture2) {
  63741. this._randomTexture2.dispose();
  63742. this._randomTexture2 = null;
  63743. }
  63744. if (disposeTexture && this.particleTexture) {
  63745. this.particleTexture.dispose();
  63746. this.particleTexture = null;
  63747. }
  63748. if (disposeTexture && this.noiseTexture) {
  63749. this.noiseTexture.dispose();
  63750. this.noiseTexture = null;
  63751. }
  63752. // Callback
  63753. this.onDisposeObservable.notifyObservers(this);
  63754. this.onDisposeObservable.clear();
  63755. };
  63756. /**
  63757. * Clones the particle system.
  63758. * @param name The name of the cloned object
  63759. * @param newEmitter The new emitter to use
  63760. * @returns the cloned particle system
  63761. */
  63762. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  63763. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  63764. BABYLON.Tools.DeepCopy(this, result);
  63765. if (newEmitter === undefined) {
  63766. newEmitter = this.emitter;
  63767. }
  63768. result.emitter = newEmitter;
  63769. if (this.particleTexture) {
  63770. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  63771. }
  63772. return result;
  63773. };
  63774. /**
  63775. * Serializes the particle system to a JSON object.
  63776. * @returns the JSON object
  63777. */
  63778. GPUParticleSystem.prototype.serialize = function () {
  63779. var serializationObject = {};
  63780. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  63781. serializationObject.activeParticleCount = this.activeParticleCount;
  63782. return serializationObject;
  63783. };
  63784. /**
  63785. * Parses a JSON object to create a GPU particle system.
  63786. * @param parsedParticleSystem The JSON object to parse
  63787. * @param scene The scene to create the particle system in
  63788. * @param rootUrl The root url to use to load external dependencies like texture
  63789. * @returns the parsed GPU particle system
  63790. */
  63791. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  63792. var name = parsedParticleSystem.name;
  63793. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  63794. if (parsedParticleSystem.activeParticleCount) {
  63795. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  63796. }
  63797. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  63798. return particleSystem;
  63799. };
  63800. return GPUParticleSystem;
  63801. }(BABYLON.BaseParticleSystem));
  63802. BABYLON.GPUParticleSystem = GPUParticleSystem;
  63803. })(BABYLON || (BABYLON = {}));
  63804. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  63805. var BABYLON;
  63806. (function (BABYLON) {
  63807. /**
  63808. * Represents one particle of a solid particle system.
  63809. */
  63810. var SolidParticle = /** @class */ (function () {
  63811. /**
  63812. * Creates a Solid Particle object.
  63813. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  63814. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  63815. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  63816. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  63817. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  63818. * @param shapeId (integer) is the model shape identifier in the SPS.
  63819. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  63820. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  63821. */
  63822. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  63823. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  63824. /**
  63825. * particle global index
  63826. */
  63827. this.idx = 0;
  63828. /**
  63829. * The color of the particle
  63830. */
  63831. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  63832. /**
  63833. * The world space position of the particle.
  63834. */
  63835. this.position = BABYLON.Vector3.Zero();
  63836. /**
  63837. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  63838. */
  63839. this.rotation = BABYLON.Vector3.Zero();
  63840. /**
  63841. * The scaling of the particle.
  63842. */
  63843. this.scaling = BABYLON.Vector3.One();
  63844. /**
  63845. * The uvs of the particle.
  63846. */
  63847. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  63848. /**
  63849. * The current speed of the particle.
  63850. */
  63851. this.velocity = BABYLON.Vector3.Zero();
  63852. /**
  63853. * The pivot point in the particle local space.
  63854. */
  63855. this.pivot = BABYLON.Vector3.Zero();
  63856. /**
  63857. * Must the particle be translated from its pivot point in its local space ?
  63858. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  63859. * Default : false
  63860. */
  63861. this.translateFromPivot = false;
  63862. /**
  63863. * Is the particle active or not ?
  63864. */
  63865. this.alive = true;
  63866. /**
  63867. * Is the particle visible or not ?
  63868. */
  63869. this.isVisible = true;
  63870. /**
  63871. * Index of this particle in the global "positions" array (Internal use)
  63872. * @hidden
  63873. */
  63874. this._pos = 0;
  63875. /**
  63876. * @hidden Index of this particle in the global "indices" array (Internal use)
  63877. */
  63878. this._ind = 0;
  63879. /**
  63880. * ModelShape id of this particle
  63881. */
  63882. this.shapeId = 0;
  63883. /**
  63884. * Index of the particle in its shape id (Internal use)
  63885. */
  63886. this.idxInShape = 0;
  63887. /**
  63888. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  63889. */
  63890. this._stillInvisible = false;
  63891. /**
  63892. * @hidden Last computed particle rotation matrix
  63893. */
  63894. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  63895. /**
  63896. * Parent particle Id, if any.
  63897. * Default null.
  63898. */
  63899. this.parentId = null;
  63900. /**
  63901. * @hidden Internal global position in the SPS.
  63902. */
  63903. this._globalPosition = BABYLON.Vector3.Zero();
  63904. this.idx = particleIndex;
  63905. this._pos = positionIndex;
  63906. this._ind = indiceIndex;
  63907. this._model = model;
  63908. this.shapeId = shapeId;
  63909. this.idxInShape = idxInShape;
  63910. this._sps = sps;
  63911. if (modelBoundingInfo) {
  63912. this._modelBoundingInfo = modelBoundingInfo;
  63913. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  63914. }
  63915. }
  63916. Object.defineProperty(SolidParticle.prototype, "scale", {
  63917. /**
  63918. * Legacy support, changed scale to scaling
  63919. */
  63920. get: function () {
  63921. return this.scaling;
  63922. },
  63923. /**
  63924. * Legacy support, changed scale to scaling
  63925. */
  63926. set: function (scale) {
  63927. this.scaling = scale;
  63928. },
  63929. enumerable: true,
  63930. configurable: true
  63931. });
  63932. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  63933. /**
  63934. * Legacy support, changed quaternion to rotationQuaternion
  63935. */
  63936. get: function () {
  63937. return this.rotationQuaternion;
  63938. },
  63939. /**
  63940. * Legacy support, changed quaternion to rotationQuaternion
  63941. */
  63942. set: function (q) {
  63943. this.rotationQuaternion = q;
  63944. },
  63945. enumerable: true,
  63946. configurable: true
  63947. });
  63948. /**
  63949. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  63950. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  63951. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  63952. * @returns true if it intersects
  63953. */
  63954. SolidParticle.prototype.intersectsMesh = function (target) {
  63955. if (!this._boundingInfo || !target._boundingInfo) {
  63956. return false;
  63957. }
  63958. if (this._sps._bSphereOnly) {
  63959. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  63960. }
  63961. return this._boundingInfo.intersects(target._boundingInfo, false);
  63962. };
  63963. return SolidParticle;
  63964. }());
  63965. BABYLON.SolidParticle = SolidParticle;
  63966. /**
  63967. * Represents the shape of the model used by one particle of a solid particle system.
  63968. * SPS internal tool, don't use it manually.
  63969. */
  63970. var ModelShape = /** @class */ (function () {
  63971. /**
  63972. * 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.
  63973. * SPS internal tool, don't use it manually.
  63974. * @hidden
  63975. */
  63976. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  63977. /**
  63978. * length of the shape in the model indices array (internal use)
  63979. * @hidden
  63980. */
  63981. this._indicesLength = 0;
  63982. this.shapeID = id;
  63983. this._shape = shape;
  63984. this._indicesLength = indicesLength;
  63985. this._shapeUV = shapeUV;
  63986. this._positionFunction = posFunction;
  63987. this._vertexFunction = vtxFunction;
  63988. }
  63989. return ModelShape;
  63990. }());
  63991. BABYLON.ModelShape = ModelShape;
  63992. /**
  63993. * Represents a Depth Sorted Particle in the solid particle system.
  63994. */
  63995. var DepthSortedParticle = /** @class */ (function () {
  63996. function DepthSortedParticle() {
  63997. /**
  63998. * Index of the particle in the "indices" array
  63999. */
  64000. this.ind = 0;
  64001. /**
  64002. * Length of the particle shape in the "indices" array
  64003. */
  64004. this.indicesLength = 0;
  64005. /**
  64006. * Squared distance from the particle to the camera
  64007. */
  64008. this.sqDistance = 0.0;
  64009. }
  64010. return DepthSortedParticle;
  64011. }());
  64012. BABYLON.DepthSortedParticle = DepthSortedParticle;
  64013. })(BABYLON || (BABYLON = {}));
  64014. //# sourceMappingURL=babylon.solidParticle.js.map
  64015. var BABYLON;
  64016. (function (BABYLON) {
  64017. /**
  64018. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  64019. *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.
  64020. * The SPS is also a particle system. It provides some methods to manage the particles.
  64021. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  64022. *
  64023. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  64024. */
  64025. var SolidParticleSystem = /** @class */ (function () {
  64026. /**
  64027. * Creates a SPS (Solid Particle System) object.
  64028. * @param name (String) is the SPS name, this will be the underlying mesh name.
  64029. * @param scene (Scene) is the scene in which the SPS is added.
  64030. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  64031. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  64032. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  64033. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  64034. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  64035. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  64036. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  64037. */
  64038. function SolidParticleSystem(name, scene, options) {
  64039. /**
  64040. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  64041. * Example : var p = SPS.particles[i];
  64042. */
  64043. this.particles = new Array();
  64044. /**
  64045. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  64046. */
  64047. this.nbParticles = 0;
  64048. /**
  64049. * If the particles must ever face the camera (default false). Useful for planar particles.
  64050. */
  64051. this.billboard = false;
  64052. /**
  64053. * Recompute normals when adding a shape
  64054. */
  64055. this.recomputeNormals = true;
  64056. /**
  64057. * This a counter ofr your own usage. It's not set by any SPS functions.
  64058. */
  64059. this.counter = 0;
  64060. /**
  64061. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  64062. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  64063. */
  64064. this.vars = {};
  64065. /**
  64066. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  64067. * @hidden
  64068. */
  64069. this._bSphereOnly = false;
  64070. /**
  64071. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  64072. * @hidden
  64073. */
  64074. this._bSphereRadiusFactor = 1.0;
  64075. this._positions = new Array();
  64076. this._indices = new Array();
  64077. this._normals = new Array();
  64078. this._colors = new Array();
  64079. this._uvs = new Array();
  64080. this._index = 0; // indices index
  64081. this._updatable = true;
  64082. this._pickable = false;
  64083. this._isVisibilityBoxLocked = false;
  64084. this._alwaysVisible = false;
  64085. this._depthSort = false;
  64086. this._shapeCounter = 0;
  64087. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  64088. this._color = new BABYLON.Color4(0, 0, 0, 0);
  64089. this._computeParticleColor = true;
  64090. this._computeParticleTexture = true;
  64091. this._computeParticleRotation = true;
  64092. this._computeParticleVertex = false;
  64093. this._computeBoundingBox = false;
  64094. this._depthSortParticles = true;
  64095. this._cam_axisZ = BABYLON.Vector3.Zero();
  64096. this._cam_axisY = BABYLON.Vector3.Zero();
  64097. this._cam_axisX = BABYLON.Vector3.Zero();
  64098. this._axisZ = BABYLON.Axis.Z;
  64099. this._camDir = BABYLON.Vector3.Zero();
  64100. this._camInvertedPosition = BABYLON.Vector3.Zero();
  64101. this._rotMatrix = new BABYLON.Matrix();
  64102. this._invertMatrix = new BABYLON.Matrix();
  64103. this._rotated = BABYLON.Vector3.Zero();
  64104. this._quaternion = new BABYLON.Quaternion();
  64105. this._vertex = BABYLON.Vector3.Zero();
  64106. this._normal = BABYLON.Vector3.Zero();
  64107. this._yaw = 0.0;
  64108. this._pitch = 0.0;
  64109. this._roll = 0.0;
  64110. this._halfroll = 0.0;
  64111. this._halfpitch = 0.0;
  64112. this._halfyaw = 0.0;
  64113. this._sinRoll = 0.0;
  64114. this._cosRoll = 0.0;
  64115. this._sinPitch = 0.0;
  64116. this._cosPitch = 0.0;
  64117. this._sinYaw = 0.0;
  64118. this._cosYaw = 0.0;
  64119. this._mustUnrotateFixedNormals = false;
  64120. this._minimum = BABYLON.Vector3.Zero();
  64121. this._maximum = BABYLON.Vector3.Zero();
  64122. this._minBbox = BABYLON.Vector3.Zero();
  64123. this._maxBbox = BABYLON.Vector3.Zero();
  64124. this._particlesIntersect = false;
  64125. this._depthSortFunction = function (p1, p2) {
  64126. return (p2.sqDistance - p1.sqDistance);
  64127. };
  64128. this._needs32Bits = false;
  64129. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  64130. this._scaledPivot = BABYLON.Vector3.Zero();
  64131. this._particleHasParent = false;
  64132. this.name = name;
  64133. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64134. this._camera = scene.activeCamera;
  64135. this._pickable = options ? options.isPickable : false;
  64136. this._depthSort = options ? options.enableDepthSort : false;
  64137. this._particlesIntersect = options ? options.particleIntersection : false;
  64138. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  64139. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  64140. if (options && options.updatable !== undefined) {
  64141. this._updatable = options.updatable;
  64142. }
  64143. else {
  64144. this._updatable = true;
  64145. }
  64146. if (this._pickable) {
  64147. this.pickedParticles = [];
  64148. }
  64149. if (this._depthSort) {
  64150. this.depthSortedParticles = [];
  64151. }
  64152. }
  64153. /**
  64154. * Builds the SPS underlying mesh. Returns a standard Mesh.
  64155. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  64156. * @returns the created mesh
  64157. */
  64158. SolidParticleSystem.prototype.buildMesh = function () {
  64159. if (this.nbParticles === 0) {
  64160. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  64161. this.addShape(triangle, 1);
  64162. triangle.dispose();
  64163. }
  64164. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  64165. this._positions32 = new Float32Array(this._positions);
  64166. this._uvs32 = new Float32Array(this._uvs);
  64167. this._colors32 = new Float32Array(this._colors);
  64168. if (this.recomputeNormals) {
  64169. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  64170. }
  64171. this._normals32 = new Float32Array(this._normals);
  64172. this._fixedNormal32 = new Float32Array(this._normals);
  64173. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  64174. this._unrotateFixedNormals();
  64175. }
  64176. var vertexData = new BABYLON.VertexData();
  64177. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  64178. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  64179. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  64180. if (this._uvs32.length > 0) {
  64181. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  64182. }
  64183. if (this._colors32.length > 0) {
  64184. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  64185. }
  64186. var mesh = new BABYLON.Mesh(this.name, this._scene);
  64187. vertexData.applyToMesh(mesh, this._updatable);
  64188. this.mesh = mesh;
  64189. this.mesh.isPickable = this._pickable;
  64190. // free memory
  64191. if (!this._depthSort) {
  64192. this._indices = null;
  64193. }
  64194. this._positions = null;
  64195. this._normals = null;
  64196. this._uvs = null;
  64197. this._colors = null;
  64198. if (!this._updatable) {
  64199. this.particles.length = 0;
  64200. }
  64201. return mesh;
  64202. };
  64203. /**
  64204. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  64205. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  64206. * Thus the particles generated from `digest()` have their property `position` set yet.
  64207. * @param mesh ( Mesh ) is the mesh to be digested
  64208. * @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
  64209. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  64210. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  64211. * @returns the current SPS
  64212. */
  64213. SolidParticleSystem.prototype.digest = function (mesh, options) {
  64214. var size = (options && options.facetNb) || 1;
  64215. var number = (options && options.number) || 0;
  64216. var delta = (options && options.delta) || 0;
  64217. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64218. var meshInd = mesh.getIndices();
  64219. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64220. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64221. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64222. var f = 0; // facet counter
  64223. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  64224. // compute size from number
  64225. if (number) {
  64226. number = (number > totalFacets) ? totalFacets : number;
  64227. size = Math.round(totalFacets / number);
  64228. delta = 0;
  64229. }
  64230. else {
  64231. size = (size > totalFacets) ? totalFacets : size;
  64232. }
  64233. var facetPos = []; // submesh positions
  64234. var facetInd = []; // submesh indices
  64235. var facetUV = []; // submesh UV
  64236. var facetCol = []; // submesh colors
  64237. var barycenter = BABYLON.Vector3.Zero();
  64238. var sizeO = size;
  64239. while (f < totalFacets) {
  64240. size = sizeO + Math.floor((1 + delta) * Math.random());
  64241. if (f > totalFacets - size) {
  64242. size = totalFacets - f;
  64243. }
  64244. // reset temp arrays
  64245. facetPos.length = 0;
  64246. facetInd.length = 0;
  64247. facetUV.length = 0;
  64248. facetCol.length = 0;
  64249. // iterate over "size" facets
  64250. var fi = 0;
  64251. for (var j = f * 3; j < (f + size) * 3; j++) {
  64252. facetInd.push(fi);
  64253. var i = meshInd[j];
  64254. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  64255. if (meshUV) {
  64256. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  64257. }
  64258. if (meshCol) {
  64259. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  64260. }
  64261. fi++;
  64262. }
  64263. // create a model shape for each single particle
  64264. var idx = this.nbParticles;
  64265. var shape = this._posToShape(facetPos);
  64266. var shapeUV = this._uvsToShapeUV(facetUV);
  64267. // compute the barycenter of the shape
  64268. var v;
  64269. for (v = 0; v < shape.length; v++) {
  64270. barycenter.addInPlace(shape[v]);
  64271. }
  64272. barycenter.scaleInPlace(1 / shape.length);
  64273. // shift the shape from its barycenter to the origin
  64274. for (v = 0; v < shape.length; v++) {
  64275. shape[v].subtractInPlace(barycenter);
  64276. }
  64277. var bInfo;
  64278. if (this._particlesIntersect) {
  64279. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  64280. }
  64281. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  64282. // add the particle in the SPS
  64283. var currentPos = this._positions.length;
  64284. var currentInd = this._indices.length;
  64285. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  64286. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  64287. // initialize the particle position
  64288. this.particles[this.nbParticles].position.addInPlace(barycenter);
  64289. this._index += shape.length;
  64290. idx++;
  64291. this.nbParticles++;
  64292. this._shapeCounter++;
  64293. f += size;
  64294. }
  64295. return this;
  64296. };
  64297. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  64298. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  64299. var index = 0;
  64300. var idx = 0;
  64301. for (var p = 0; p < this.particles.length; p++) {
  64302. this._particle = this.particles[p];
  64303. this._shape = this._particle._model._shape;
  64304. if (this._particle.rotationQuaternion) {
  64305. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64306. }
  64307. else {
  64308. this._yaw = this._particle.rotation.y;
  64309. this._pitch = this._particle.rotation.x;
  64310. this._roll = this._particle.rotation.z;
  64311. this._quaternionRotationYPR();
  64312. }
  64313. this._quaternionToRotationMatrix();
  64314. this._rotMatrix.invertToRef(this._invertMatrix);
  64315. for (var pt = 0; pt < this._shape.length; pt++) {
  64316. idx = index + pt * 3;
  64317. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  64318. this._fixedNormal32[idx] = this._normal.x;
  64319. this._fixedNormal32[idx + 1] = this._normal.y;
  64320. this._fixedNormal32[idx + 2] = this._normal.z;
  64321. }
  64322. index = idx + 3;
  64323. }
  64324. };
  64325. //reset copy
  64326. SolidParticleSystem.prototype._resetCopy = function () {
  64327. this._copy.position.x = 0;
  64328. this._copy.position.y = 0;
  64329. this._copy.position.z = 0;
  64330. this._copy.rotation.x = 0;
  64331. this._copy.rotation.y = 0;
  64332. this._copy.rotation.z = 0;
  64333. this._copy.rotationQuaternion = null;
  64334. this._copy.scaling.x = 1.0;
  64335. this._copy.scaling.y = 1.0;
  64336. this._copy.scaling.z = 1.0;
  64337. this._copy.uvs.x = 0;
  64338. this._copy.uvs.y = 0;
  64339. this._copy.uvs.z = 1.0;
  64340. this._copy.uvs.w = 1.0;
  64341. this._copy.color = null;
  64342. this._copy.translateFromPivot = false;
  64343. };
  64344. // _meshBuilder : inserts the shape model in the global SPS mesh
  64345. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  64346. var i;
  64347. var u = 0;
  64348. var c = 0;
  64349. var n = 0;
  64350. this._resetCopy();
  64351. if (options && options.positionFunction) { // call to custom positionFunction
  64352. options.positionFunction(this._copy, idx, idxInShape);
  64353. this._mustUnrotateFixedNormals = true;
  64354. }
  64355. if (this._copy.rotationQuaternion) {
  64356. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64357. }
  64358. else {
  64359. this._yaw = this._copy.rotation.y;
  64360. this._pitch = this._copy.rotation.x;
  64361. this._roll = this._copy.rotation.z;
  64362. this._quaternionRotationYPR();
  64363. }
  64364. this._quaternionToRotationMatrix();
  64365. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  64366. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  64367. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  64368. if (this._copy.translateFromPivot) {
  64369. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64370. }
  64371. else {
  64372. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64373. }
  64374. for (i = 0; i < shape.length; i++) {
  64375. this._vertex.x = shape[i].x;
  64376. this._vertex.y = shape[i].y;
  64377. this._vertex.z = shape[i].z;
  64378. if (options && options.vertexFunction) {
  64379. options.vertexFunction(this._copy, this._vertex, i);
  64380. }
  64381. this._vertex.x *= this._copy.scaling.x;
  64382. this._vertex.y *= this._copy.scaling.y;
  64383. this._vertex.z *= this._copy.scaling.z;
  64384. this._vertex.x -= this._scaledPivot.x;
  64385. this._vertex.y -= this._scaledPivot.y;
  64386. this._vertex.z -= this._scaledPivot.z;
  64387. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64388. this._rotated.addInPlace(this._pivotBackTranslation);
  64389. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  64390. if (meshUV) {
  64391. 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);
  64392. u += 2;
  64393. }
  64394. if (this._copy.color) {
  64395. this._color = this._copy.color;
  64396. }
  64397. else if (meshCol && meshCol[c] !== undefined) {
  64398. this._color.r = meshCol[c];
  64399. this._color.g = meshCol[c + 1];
  64400. this._color.b = meshCol[c + 2];
  64401. this._color.a = meshCol[c + 3];
  64402. }
  64403. else {
  64404. this._color.r = 1.0;
  64405. this._color.g = 1.0;
  64406. this._color.b = 1.0;
  64407. this._color.a = 1.0;
  64408. }
  64409. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  64410. c += 4;
  64411. if (!this.recomputeNormals && meshNor) {
  64412. this._normal.x = meshNor[n];
  64413. this._normal.y = meshNor[n + 1];
  64414. this._normal.z = meshNor[n + 2];
  64415. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  64416. normals.push(this._normal.x, this._normal.y, this._normal.z);
  64417. n += 3;
  64418. }
  64419. }
  64420. for (i = 0; i < meshInd.length; i++) {
  64421. var current_ind = p + meshInd[i];
  64422. indices.push(current_ind);
  64423. if (current_ind > 65535) {
  64424. this._needs32Bits = true;
  64425. }
  64426. }
  64427. if (this._pickable) {
  64428. var nbfaces = meshInd.length / 3;
  64429. for (i = 0; i < nbfaces; i++) {
  64430. this.pickedParticles.push({ idx: idx, faceId: i });
  64431. }
  64432. }
  64433. if (this._depthSort) {
  64434. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  64435. }
  64436. return this._copy;
  64437. };
  64438. // returns a shape array from positions array
  64439. SolidParticleSystem.prototype._posToShape = function (positions) {
  64440. var shape = [];
  64441. for (var i = 0; i < positions.length; i += 3) {
  64442. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  64443. }
  64444. return shape;
  64445. };
  64446. // returns a shapeUV array from a Vector4 uvs
  64447. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  64448. var shapeUV = [];
  64449. if (uvs) {
  64450. for (var i = 0; i < uvs.length; i++)
  64451. shapeUV.push(uvs[i]);
  64452. }
  64453. return shapeUV;
  64454. };
  64455. // adds a new particle object in the particles array
  64456. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  64457. if (bInfo === void 0) { bInfo = null; }
  64458. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  64459. this.particles.push(sp);
  64460. return sp;
  64461. };
  64462. /**
  64463. * Adds some particles to the SPS from the model shape. Returns the shape id.
  64464. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  64465. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  64466. * @param nb (positive integer) the number of particles to be created from this model
  64467. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  64468. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  64469. * @returns the number of shapes in the system
  64470. */
  64471. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  64472. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  64473. var meshInd = mesh.getIndices();
  64474. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64475. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  64476. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  64477. var bbInfo;
  64478. if (this._particlesIntersect) {
  64479. bbInfo = mesh.getBoundingInfo();
  64480. }
  64481. var shape = this._posToShape(meshPos);
  64482. var shapeUV = this._uvsToShapeUV(meshUV);
  64483. var posfunc = options ? options.positionFunction : null;
  64484. var vtxfunc = options ? options.vertexFunction : null;
  64485. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  64486. // particles
  64487. var sp;
  64488. var currentCopy;
  64489. var idx = this.nbParticles;
  64490. for (var i = 0; i < nb; i++) {
  64491. var currentPos = this._positions.length;
  64492. var currentInd = this._indices.length;
  64493. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  64494. if (this._updatable) {
  64495. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  64496. sp.position.copyFrom(currentCopy.position);
  64497. sp.rotation.copyFrom(currentCopy.rotation);
  64498. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  64499. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  64500. }
  64501. if (currentCopy.color && sp.color) {
  64502. sp.color.copyFrom(currentCopy.color);
  64503. }
  64504. sp.scaling.copyFrom(currentCopy.scaling);
  64505. sp.uvs.copyFrom(currentCopy.uvs);
  64506. }
  64507. this._index += shape.length;
  64508. idx++;
  64509. }
  64510. this.nbParticles += nb;
  64511. this._shapeCounter++;
  64512. return this._shapeCounter - 1;
  64513. };
  64514. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  64515. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  64516. this._resetCopy();
  64517. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  64518. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  64519. }
  64520. if (this._copy.rotationQuaternion) {
  64521. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  64522. }
  64523. else {
  64524. this._yaw = this._copy.rotation.y;
  64525. this._pitch = this._copy.rotation.x;
  64526. this._roll = this._copy.rotation.z;
  64527. this._quaternionRotationYPR();
  64528. }
  64529. this._quaternionToRotationMatrix();
  64530. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64531. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64532. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64533. if (this._copy.translateFromPivot) {
  64534. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  64535. }
  64536. else {
  64537. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  64538. }
  64539. this._shape = particle._model._shape;
  64540. for (var pt = 0; pt < this._shape.length; pt++) {
  64541. this._vertex.x = this._shape[pt].x;
  64542. this._vertex.y = this._shape[pt].y;
  64543. this._vertex.z = this._shape[pt].z;
  64544. if (particle._model._vertexFunction) {
  64545. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  64546. }
  64547. this._vertex.x *= this._copy.scaling.x;
  64548. this._vertex.y *= this._copy.scaling.y;
  64549. this._vertex.z *= this._copy.scaling.z;
  64550. this._vertex.x -= this._scaledPivot.x;
  64551. this._vertex.y -= this._scaledPivot.y;
  64552. this._vertex.z -= this._scaledPivot.z;
  64553. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  64554. this._rotated.addInPlace(this._pivotBackTranslation);
  64555. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  64556. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  64557. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  64558. }
  64559. particle.position.x = 0.0;
  64560. particle.position.y = 0.0;
  64561. particle.position.z = 0.0;
  64562. particle.rotation.x = 0.0;
  64563. particle.rotation.y = 0.0;
  64564. particle.rotation.z = 0.0;
  64565. particle.rotationQuaternion = null;
  64566. particle.scaling.x = 1.0;
  64567. particle.scaling.y = 1.0;
  64568. particle.scaling.z = 1.0;
  64569. particle.uvs.x = 0.0;
  64570. particle.uvs.y = 0.0;
  64571. particle.uvs.z = 1.0;
  64572. particle.uvs.w = 1.0;
  64573. particle.pivot.x = 0.0;
  64574. particle.pivot.y = 0.0;
  64575. particle.pivot.z = 0.0;
  64576. particle.translateFromPivot = false;
  64577. particle.parentId = null;
  64578. };
  64579. /**
  64580. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  64581. * @returns the SPS.
  64582. */
  64583. SolidParticleSystem.prototype.rebuildMesh = function () {
  64584. for (var p = 0; p < this.particles.length; p++) {
  64585. this._rebuildParticle(this.particles[p]);
  64586. }
  64587. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  64588. return this;
  64589. };
  64590. /**
  64591. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  64592. * This method calls `updateParticle()` for each particle of the SPS.
  64593. * For an animated SPS, it is usually called within the render loop.
  64594. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  64595. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  64596. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  64597. * @returns the SPS.
  64598. */
  64599. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  64600. if (start === void 0) { start = 0; }
  64601. if (end === void 0) { end = this.nbParticles - 1; }
  64602. if (update === void 0) { update = true; }
  64603. if (!this._updatable) {
  64604. return this;
  64605. }
  64606. // custom beforeUpdate
  64607. this.beforeUpdateParticles(start, end, update);
  64608. this._cam_axisX.x = 1.0;
  64609. this._cam_axisX.y = 0.0;
  64610. this._cam_axisX.z = 0.0;
  64611. this._cam_axisY.x = 0.0;
  64612. this._cam_axisY.y = 1.0;
  64613. this._cam_axisY.z = 0.0;
  64614. this._cam_axisZ.x = 0.0;
  64615. this._cam_axisZ.y = 0.0;
  64616. this._cam_axisZ.z = 1.0;
  64617. // cases when the World Matrix is to be computed first
  64618. if (this.billboard || this._depthSort) {
  64619. this.mesh.computeWorldMatrix(true);
  64620. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  64621. }
  64622. // if the particles will always face the camera
  64623. if (this.billboard) {
  64624. // compute the camera position and un-rotate it by the current mesh rotation
  64625. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  64626. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  64627. this._cam_axisZ.normalize();
  64628. // same for camera up vector extracted from the cam view matrix
  64629. var view = this._camera.getViewMatrix(true);
  64630. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  64631. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  64632. this._cam_axisY.normalize();
  64633. this._cam_axisX.normalize();
  64634. }
  64635. // if depthSort, compute the camera global position in the mesh local system
  64636. if (this._depthSort) {
  64637. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  64638. }
  64639. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  64640. var idx = 0; // current position index in the global array positions32
  64641. var index = 0; // position start index in the global array positions32 of the current particle
  64642. var colidx = 0; // current color index in the global array colors32
  64643. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  64644. var uvidx = 0; // current uv index in the global array uvs32
  64645. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  64646. var pt = 0; // current index in the particle model shape
  64647. if (this.mesh.isFacetDataEnabled) {
  64648. this._computeBoundingBox = true;
  64649. }
  64650. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  64651. if (this._computeBoundingBox) {
  64652. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  64653. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  64654. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  64655. }
  64656. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  64657. if (this.mesh._boundingInfo) {
  64658. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  64659. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  64660. }
  64661. }
  64662. }
  64663. // particle loop
  64664. index = this.particles[start]._pos;
  64665. var vpos = (index / 3) | 0;
  64666. colorIndex = vpos * 4;
  64667. uvIndex = vpos * 2;
  64668. for (var p = start; p <= end; p++) {
  64669. this._particle = this.particles[p];
  64670. this._shape = this._particle._model._shape;
  64671. this._shapeUV = this._particle._model._shapeUV;
  64672. // call to custom user function to update the particle properties
  64673. this.updateParticle(this._particle);
  64674. // camera-particle distance for depth sorting
  64675. if (this._depthSort && this._depthSortParticles) {
  64676. var dsp = this.depthSortedParticles[p];
  64677. dsp.ind = this._particle._ind;
  64678. dsp.indicesLength = this._particle._model._indicesLength;
  64679. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  64680. }
  64681. // skip the computations for inactive or already invisible particles
  64682. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  64683. // increment indexes for the next particle
  64684. pt = this._shape.length;
  64685. index += pt * 3;
  64686. colorIndex += pt * 4;
  64687. uvIndex += pt * 2;
  64688. continue;
  64689. }
  64690. if (this._particle.isVisible) {
  64691. this._particle._stillInvisible = false; // un-mark permanent invisibility
  64692. this._particleHasParent = (this._particle.parentId !== null);
  64693. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  64694. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  64695. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  64696. // particle rotation matrix
  64697. if (this.billboard) {
  64698. this._particle.rotation.x = 0.0;
  64699. this._particle.rotation.y = 0.0;
  64700. }
  64701. if (this._computeParticleRotation || this.billboard) {
  64702. if (this._particle.rotationQuaternion) {
  64703. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  64704. }
  64705. else {
  64706. this._yaw = this._particle.rotation.y;
  64707. this._pitch = this._particle.rotation.x;
  64708. this._roll = this._particle.rotation.z;
  64709. this._quaternionRotationYPR();
  64710. }
  64711. this._quaternionToRotationMatrix();
  64712. }
  64713. if (this._particleHasParent) {
  64714. this._parent = this.particles[this._particle.parentId];
  64715. 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];
  64716. 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];
  64717. 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];
  64718. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  64719. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  64720. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  64721. if (this._computeParticleRotation || this.billboard) {
  64722. 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];
  64723. 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];
  64724. 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];
  64725. 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];
  64726. 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];
  64727. 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];
  64728. 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];
  64729. 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];
  64730. 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];
  64731. }
  64732. }
  64733. else {
  64734. this._particle._globalPosition.x = this._particle.position.x;
  64735. this._particle._globalPosition.y = this._particle.position.y;
  64736. this._particle._globalPosition.z = this._particle.position.z;
  64737. if (this._computeParticleRotation || this.billboard) {
  64738. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  64739. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  64740. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  64741. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  64742. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  64743. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  64744. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  64745. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  64746. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  64747. }
  64748. }
  64749. if (this._particle.translateFromPivot) {
  64750. this._pivotBackTranslation.x = 0.0;
  64751. this._pivotBackTranslation.y = 0.0;
  64752. this._pivotBackTranslation.z = 0.0;
  64753. }
  64754. else {
  64755. this._pivotBackTranslation.x = this._scaledPivot.x;
  64756. this._pivotBackTranslation.y = this._scaledPivot.y;
  64757. this._pivotBackTranslation.z = this._scaledPivot.z;
  64758. }
  64759. // particle vertex loop
  64760. for (pt = 0; pt < this._shape.length; pt++) {
  64761. idx = index + pt * 3;
  64762. colidx = colorIndex + pt * 4;
  64763. uvidx = uvIndex + pt * 2;
  64764. this._vertex.x = this._shape[pt].x;
  64765. this._vertex.y = this._shape[pt].y;
  64766. this._vertex.z = this._shape[pt].z;
  64767. if (this._computeParticleVertex) {
  64768. this.updateParticleVertex(this._particle, this._vertex, pt);
  64769. }
  64770. // positions
  64771. this._vertex.x *= this._particle.scaling.x;
  64772. this._vertex.y *= this._particle.scaling.y;
  64773. this._vertex.z *= this._particle.scaling.z;
  64774. this._vertex.x -= this._scaledPivot.x;
  64775. this._vertex.y -= this._scaledPivot.y;
  64776. this._vertex.z -= this._scaledPivot.z;
  64777. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  64778. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  64779. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  64780. this._rotated.x += this._pivotBackTranslation.x;
  64781. this._rotated.y += this._pivotBackTranslation.y;
  64782. this._rotated.z += this._pivotBackTranslation.z;
  64783. 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;
  64784. 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;
  64785. 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;
  64786. if (this._computeBoundingBox) {
  64787. if (this._positions32[idx] < this._minimum.x) {
  64788. this._minimum.x = this._positions32[idx];
  64789. }
  64790. if (this._positions32[idx] > this._maximum.x) {
  64791. this._maximum.x = this._positions32[idx];
  64792. }
  64793. if (this._positions32[idx + 1] < this._minimum.y) {
  64794. this._minimum.y = this._positions32[idx + 1];
  64795. }
  64796. if (this._positions32[idx + 1] > this._maximum.y) {
  64797. this._maximum.y = this._positions32[idx + 1];
  64798. }
  64799. if (this._positions32[idx + 2] < this._minimum.z) {
  64800. this._minimum.z = this._positions32[idx + 2];
  64801. }
  64802. if (this._positions32[idx + 2] > this._maximum.z) {
  64803. this._maximum.z = this._positions32[idx + 2];
  64804. }
  64805. }
  64806. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  64807. if (!this._computeParticleVertex) {
  64808. this._normal.x = this._fixedNormal32[idx];
  64809. this._normal.y = this._fixedNormal32[idx + 1];
  64810. this._normal.z = this._fixedNormal32[idx + 2];
  64811. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  64812. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  64813. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  64814. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  64815. 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;
  64816. 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;
  64817. }
  64818. if (this._computeParticleColor && this._particle.color) {
  64819. this._colors32[colidx] = this._particle.color.r;
  64820. this._colors32[colidx + 1] = this._particle.color.g;
  64821. this._colors32[colidx + 2] = this._particle.color.b;
  64822. this._colors32[colidx + 3] = this._particle.color.a;
  64823. }
  64824. if (this._computeParticleTexture) {
  64825. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  64826. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  64827. }
  64828. }
  64829. }
  64830. // particle just set invisible : scaled to zero and positioned at the origin
  64831. else {
  64832. this._particle._stillInvisible = true; // mark the particle as invisible
  64833. for (pt = 0; pt < this._shape.length; pt++) {
  64834. idx = index + pt * 3;
  64835. colidx = colorIndex + pt * 4;
  64836. uvidx = uvIndex + pt * 2;
  64837. this._positions32[idx] = 0.0;
  64838. this._positions32[idx + 1] = 0.0;
  64839. this._positions32[idx + 2] = 0.0;
  64840. this._normals32[idx] = 0.0;
  64841. this._normals32[idx + 1] = 0.0;
  64842. this._normals32[idx + 2] = 0.0;
  64843. if (this._computeParticleColor && this._particle.color) {
  64844. this._colors32[colidx] = this._particle.color.r;
  64845. this._colors32[colidx + 1] = this._particle.color.g;
  64846. this._colors32[colidx + 2] = this._particle.color.b;
  64847. this._colors32[colidx + 3] = this._particle.color.a;
  64848. }
  64849. if (this._computeParticleTexture) {
  64850. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  64851. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  64852. }
  64853. }
  64854. }
  64855. // if the particle intersections must be computed : update the bbInfo
  64856. if (this._particlesIntersect) {
  64857. var bInfo = this._particle._boundingInfo;
  64858. var bBox = bInfo.boundingBox;
  64859. var bSphere = bInfo.boundingSphere;
  64860. if (!this._bSphereOnly) {
  64861. // place, scale and rotate the particle bbox within the SPS local system, then update it
  64862. for (var b = 0; b < bBox.vectors.length; b++) {
  64863. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  64864. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  64865. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  64866. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  64867. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  64868. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  64869. 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;
  64870. 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;
  64871. 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;
  64872. }
  64873. bBox._update(this.mesh._worldMatrix);
  64874. }
  64875. // place and scale the particle bouding sphere in the SPS local system, then update it
  64876. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  64877. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  64878. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  64879. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  64880. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  64881. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  64882. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  64883. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  64884. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  64885. 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));
  64886. bSphere._update(this.mesh._worldMatrix);
  64887. }
  64888. // increment indexes for the next particle
  64889. index = idx + 3;
  64890. colorIndex = colidx + 4;
  64891. uvIndex = uvidx + 2;
  64892. }
  64893. // if the VBO must be updated
  64894. if (update) {
  64895. if (this._computeParticleColor) {
  64896. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  64897. }
  64898. if (this._computeParticleTexture) {
  64899. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  64900. }
  64901. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  64902. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  64903. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  64904. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  64905. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  64906. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  64907. for (var i = 0; i < this._normals32.length; i++) {
  64908. this._fixedNormal32[i] = this._normals32[i];
  64909. }
  64910. }
  64911. if (!this.mesh.areNormalsFrozen) {
  64912. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  64913. }
  64914. }
  64915. if (this._depthSort && this._depthSortParticles) {
  64916. this.depthSortedParticles.sort(this._depthSortFunction);
  64917. var dspl = this.depthSortedParticles.length;
  64918. var sorted = 0;
  64919. var lind = 0;
  64920. var sind = 0;
  64921. var sid = 0;
  64922. for (sorted = 0; sorted < dspl; sorted++) {
  64923. lind = this.depthSortedParticles[sorted].indicesLength;
  64924. sind = this.depthSortedParticles[sorted].ind;
  64925. for (var i = 0; i < lind; i++) {
  64926. this._indices32[sid] = this._indices[sind + i];
  64927. sid++;
  64928. }
  64929. }
  64930. this.mesh.updateIndices(this._indices32);
  64931. }
  64932. }
  64933. if (this._computeBoundingBox) {
  64934. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  64935. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  64936. }
  64937. this.afterUpdateParticles(start, end, update);
  64938. return this;
  64939. };
  64940. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  64941. this._halfroll = this._roll * 0.5;
  64942. this._halfpitch = this._pitch * 0.5;
  64943. this._halfyaw = this._yaw * 0.5;
  64944. this._sinRoll = Math.sin(this._halfroll);
  64945. this._cosRoll = Math.cos(this._halfroll);
  64946. this._sinPitch = Math.sin(this._halfpitch);
  64947. this._cosPitch = Math.cos(this._halfpitch);
  64948. this._sinYaw = Math.sin(this._halfyaw);
  64949. this._cosYaw = Math.cos(this._halfyaw);
  64950. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  64951. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  64952. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  64953. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  64954. };
  64955. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  64956. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  64957. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  64958. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  64959. this._rotMatrix.m[3] = 0;
  64960. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  64961. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  64962. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  64963. this._rotMatrix.m[7] = 0;
  64964. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  64965. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  64966. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  64967. this._rotMatrix.m[11] = 0;
  64968. this._rotMatrix.m[12] = 0;
  64969. this._rotMatrix.m[13] = 0;
  64970. this._rotMatrix.m[14] = 0;
  64971. this._rotMatrix.m[15] = 1.0;
  64972. };
  64973. /**
  64974. * Disposes the SPS.
  64975. */
  64976. SolidParticleSystem.prototype.dispose = function () {
  64977. this.mesh.dispose();
  64978. this.vars = null;
  64979. // drop references to internal big arrays for the GC
  64980. this._positions = null;
  64981. this._indices = null;
  64982. this._normals = null;
  64983. this._uvs = null;
  64984. this._colors = null;
  64985. this._indices32 = null;
  64986. this._positions32 = null;
  64987. this._normals32 = null;
  64988. this._fixedNormal32 = null;
  64989. this._uvs32 = null;
  64990. this._colors32 = null;
  64991. this.pickedParticles = null;
  64992. };
  64993. /**
  64994. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  64995. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  64996. * @returns the SPS.
  64997. */
  64998. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  64999. if (!this._isVisibilityBoxLocked) {
  65000. this.mesh.refreshBoundingInfo();
  65001. }
  65002. return this;
  65003. };
  65004. /**
  65005. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  65006. * @param size the size (float) of the visibility box
  65007. * note : this doesn't lock the SPS mesh bounding box.
  65008. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65009. */
  65010. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  65011. var vis = size / 2;
  65012. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  65013. };
  65014. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  65015. /**
  65016. * Gets whether the SPS as always visible or not
  65017. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65018. */
  65019. get: function () {
  65020. return this._alwaysVisible;
  65021. },
  65022. /**
  65023. * Sets the SPS as always visible or not
  65024. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65025. */
  65026. set: function (val) {
  65027. this._alwaysVisible = val;
  65028. this.mesh.alwaysSelectAsActiveMesh = val;
  65029. },
  65030. enumerable: true,
  65031. configurable: true
  65032. });
  65033. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  65034. /**
  65035. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65036. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65037. */
  65038. get: function () {
  65039. return this._isVisibilityBoxLocked;
  65040. },
  65041. /**
  65042. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  65043. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  65044. */
  65045. set: function (val) {
  65046. this._isVisibilityBoxLocked = val;
  65047. var boundingInfo = this.mesh.getBoundingInfo();
  65048. boundingInfo.isLocked = val;
  65049. },
  65050. enumerable: true,
  65051. configurable: true
  65052. });
  65053. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  65054. /**
  65055. * Gets if `setParticles()` computes the particle rotations or not.
  65056. * Default value : true. The SPS is faster when it's set to false.
  65057. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65058. */
  65059. get: function () {
  65060. return this._computeParticleRotation;
  65061. },
  65062. /**
  65063. * Tells to `setParticles()` to compute the particle rotations or not.
  65064. * Default value : true. The SPS is faster when it's set to false.
  65065. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  65066. */
  65067. set: function (val) {
  65068. this._computeParticleRotation = val;
  65069. },
  65070. enumerable: true,
  65071. configurable: true
  65072. });
  65073. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  65074. /**
  65075. * Gets if `setParticles()` computes the particle colors or not.
  65076. * Default value : true. The SPS is faster when it's set to false.
  65077. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65078. */
  65079. get: function () {
  65080. return this._computeParticleColor;
  65081. },
  65082. /**
  65083. * Tells to `setParticles()` to compute the particle colors or not.
  65084. * Default value : true. The SPS is faster when it's set to false.
  65085. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  65086. */
  65087. set: function (val) {
  65088. this._computeParticleColor = val;
  65089. },
  65090. enumerable: true,
  65091. configurable: true
  65092. });
  65093. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  65094. /**
  65095. * Gets if `setParticles()` computes the particle textures or not.
  65096. * Default value : true. The SPS is faster when it's set to false.
  65097. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  65098. */
  65099. get: function () {
  65100. return this._computeParticleTexture;
  65101. },
  65102. set: function (val) {
  65103. this._computeParticleTexture = val;
  65104. },
  65105. enumerable: true,
  65106. configurable: true
  65107. });
  65108. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  65109. /**
  65110. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  65111. * Default value : false. The SPS is faster when it's set to false.
  65112. * Note : the particle custom vertex positions aren't stored values.
  65113. */
  65114. get: function () {
  65115. return this._computeParticleVertex;
  65116. },
  65117. /**
  65118. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  65119. * Default value : false. The SPS is faster when it's set to false.
  65120. * Note : the particle custom vertex positions aren't stored values.
  65121. */
  65122. set: function (val) {
  65123. this._computeParticleVertex = val;
  65124. },
  65125. enumerable: true,
  65126. configurable: true
  65127. });
  65128. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  65129. /**
  65130. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  65131. */
  65132. get: function () {
  65133. return this._computeBoundingBox;
  65134. },
  65135. /**
  65136. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  65137. */
  65138. set: function (val) {
  65139. this._computeBoundingBox = val;
  65140. },
  65141. enumerable: true,
  65142. configurable: true
  65143. });
  65144. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  65145. /**
  65146. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  65147. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65148. * Default : `true`
  65149. */
  65150. get: function () {
  65151. return this._depthSortParticles;
  65152. },
  65153. /**
  65154. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  65155. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  65156. * Default : `true`
  65157. */
  65158. set: function (val) {
  65159. this._depthSortParticles = val;
  65160. },
  65161. enumerable: true,
  65162. configurable: true
  65163. });
  65164. // =======================================================================
  65165. // Particle behavior logic
  65166. // these following methods may be overwritten by the user to fit his needs
  65167. /**
  65168. * This function does nothing. It may be overwritten to set all the particle first values.
  65169. * The SPS doesn't call this function, you may have to call it by your own.
  65170. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65171. */
  65172. SolidParticleSystem.prototype.initParticles = function () {
  65173. };
  65174. /**
  65175. * This function does nothing. It may be overwritten to recycle a particle.
  65176. * The SPS doesn't call this function, you may have to call it by your own.
  65177. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65178. * @param particle The particle to recycle
  65179. * @returns the recycled particle
  65180. */
  65181. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  65182. return particle;
  65183. };
  65184. /**
  65185. * Updates a particle : this function should be overwritten by the user.
  65186. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  65187. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  65188. * @example : just set a particle position or velocity and recycle conditions
  65189. * @param particle The particle to update
  65190. * @returns the updated particle
  65191. */
  65192. SolidParticleSystem.prototype.updateParticle = function (particle) {
  65193. return particle;
  65194. };
  65195. /**
  65196. * Updates a vertex of a particle : it can be overwritten by the user.
  65197. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  65198. * @param particle the current particle
  65199. * @param vertex the current index of the current particle
  65200. * @param pt the index of the current vertex in the particle shape
  65201. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  65202. * @example : just set a vertex particle position
  65203. * @returns the updated vertex
  65204. */
  65205. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  65206. return vertex;
  65207. };
  65208. /**
  65209. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  65210. * This does nothing and may be overwritten by the user.
  65211. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65212. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65213. * @param update the boolean update value actually passed to setParticles()
  65214. */
  65215. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  65216. };
  65217. /**
  65218. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  65219. * This will be passed three parameters.
  65220. * This does nothing and may be overwritten by the user.
  65221. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65222. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  65223. * @param update the boolean update value actually passed to setParticles()
  65224. */
  65225. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  65226. };
  65227. return SolidParticleSystem;
  65228. }());
  65229. BABYLON.SolidParticleSystem = SolidParticleSystem;
  65230. })(BABYLON || (BABYLON = {}));
  65231. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  65232. var BABYLON;
  65233. (function (BABYLON) {
  65234. /**
  65235. * Class containing static functions to help procedurally build meshes
  65236. */
  65237. var MeshBuilder = /** @class */ (function () {
  65238. function MeshBuilder() {
  65239. }
  65240. MeshBuilder.updateSideOrientation = function (orientation) {
  65241. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  65242. return BABYLON.Mesh.DOUBLESIDE;
  65243. }
  65244. if (orientation === undefined || orientation === null) {
  65245. return BABYLON.Mesh.FRONTSIDE;
  65246. }
  65247. return orientation;
  65248. };
  65249. /**
  65250. * Creates a box mesh
  65251. * * The parameter `size` sets the size (float) of each box side (default 1)
  65252. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  65253. * * 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)
  65254. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  65255. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65256. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65257. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65258. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  65259. * @param name defines the name of the mesh
  65260. * @param options defines the options used to create the mesh
  65261. * @param scene defines the hosting scene
  65262. * @returns the box mesh
  65263. */
  65264. MeshBuilder.CreateBox = function (name, options, scene) {
  65265. if (scene === void 0) { scene = null; }
  65266. var box = new BABYLON.Mesh(name, scene);
  65267. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65268. box._originalBuilderSideOrientation = options.sideOrientation;
  65269. var vertexData = BABYLON.VertexData.CreateBox(options);
  65270. vertexData.applyToMesh(box, options.updatable);
  65271. return box;
  65272. };
  65273. /**
  65274. * Creates a sphere mesh
  65275. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  65276. * * 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`)
  65277. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  65278. * * 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
  65279. * * 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)
  65280. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65281. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65282. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65283. * @param name defines the name of the mesh
  65284. * @param options defines the options used to create the mesh
  65285. * @param scene defines the hosting scene
  65286. * @returns the sphere mesh
  65287. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  65288. */
  65289. MeshBuilder.CreateSphere = function (name, options, scene) {
  65290. var sphere = new BABYLON.Mesh(name, scene);
  65291. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65292. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65293. var vertexData = BABYLON.VertexData.CreateSphere(options);
  65294. vertexData.applyToMesh(sphere, options.updatable);
  65295. return sphere;
  65296. };
  65297. /**
  65298. * Creates a plane polygonal mesh. By default, this is a disc
  65299. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  65300. * * 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
  65301. * * 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
  65302. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65303. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65304. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65305. * @param name defines the name of the mesh
  65306. * @param options defines the options used to create the mesh
  65307. * @param scene defines the hosting scene
  65308. * @returns the plane polygonal mesh
  65309. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  65310. */
  65311. MeshBuilder.CreateDisc = function (name, options, scene) {
  65312. if (scene === void 0) { scene = null; }
  65313. var disc = new BABYLON.Mesh(name, scene);
  65314. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65315. disc._originalBuilderSideOrientation = options.sideOrientation;
  65316. var vertexData = BABYLON.VertexData.CreateDisc(options);
  65317. vertexData.applyToMesh(disc, options.updatable);
  65318. return disc;
  65319. };
  65320. /**
  65321. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  65322. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  65323. * * 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`)
  65324. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  65325. * * 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
  65326. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65327. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65328. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65329. * @param name defines the name of the mesh
  65330. * @param options defines the options used to create the mesh
  65331. * @param scene defines the hosting scene
  65332. * @returns the icosahedron mesh
  65333. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  65334. */
  65335. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  65336. var sphere = new BABYLON.Mesh(name, scene);
  65337. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65338. sphere._originalBuilderSideOrientation = options.sideOrientation;
  65339. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  65340. vertexData.applyToMesh(sphere, options.updatable);
  65341. return sphere;
  65342. };
  65343. ;
  65344. /**
  65345. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  65346. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  65347. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  65348. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  65349. * * 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
  65350. * * 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
  65351. * * 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
  65352. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65353. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65354. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65355. * * 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
  65356. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  65357. * * 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 if you set `closePath` to `true`, there's one extra vertex per path in the geometry
  65358. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  65359. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65360. * @param name defines the name of the mesh
  65361. * @param options defines the options used to create the mesh
  65362. * @param scene defines the hosting scene
  65363. * @returns the ribbon mesh
  65364. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  65365. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65366. */
  65367. MeshBuilder.CreateRibbon = function (name, options, scene) {
  65368. if (scene === void 0) { scene = null; }
  65369. var pathArray = options.pathArray;
  65370. var closeArray = options.closeArray;
  65371. var closePath = options.closePath;
  65372. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65373. var instance = options.instance;
  65374. var updatable = options.updatable;
  65375. if (instance) { // existing ribbon instance update
  65376. // positionFunction : ribbon case
  65377. // only pathArray and sideOrientation parameters are taken into account for positions update
  65378. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  65379. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  65380. var positionFunction = function (positions) {
  65381. var minlg = pathArray[0].length;
  65382. var i = 0;
  65383. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  65384. for (var si = 1; si <= ns; si++) {
  65385. for (var p = 0; p < pathArray.length; p++) {
  65386. var path = pathArray[p];
  65387. var l = path.length;
  65388. minlg = (minlg < l) ? minlg : l;
  65389. var j = 0;
  65390. while (j < minlg) {
  65391. positions[i] = path[j].x;
  65392. positions[i + 1] = path[j].y;
  65393. positions[i + 2] = path[j].z;
  65394. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  65395. BABYLON.Tmp.Vector3[0].x = path[j].x;
  65396. }
  65397. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  65398. BABYLON.Tmp.Vector3[1].x = path[j].x;
  65399. }
  65400. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  65401. BABYLON.Tmp.Vector3[0].y = path[j].y;
  65402. }
  65403. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  65404. BABYLON.Tmp.Vector3[1].y = path[j].y;
  65405. }
  65406. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  65407. BABYLON.Tmp.Vector3[0].z = path[j].z;
  65408. }
  65409. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  65410. BABYLON.Tmp.Vector3[1].z = path[j].z;
  65411. }
  65412. j++;
  65413. i += 3;
  65414. }
  65415. if (instance._closePath) {
  65416. positions[i] = path[0].x;
  65417. positions[i + 1] = path[0].y;
  65418. positions[i + 2] = path[0].z;
  65419. i += 3;
  65420. }
  65421. }
  65422. }
  65423. };
  65424. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65425. positionFunction(positions);
  65426. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  65427. instance._boundingInfo.update(instance._worldMatrix);
  65428. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65429. if (options.colors) {
  65430. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65431. for (var c = 0; c < options.colors.length; c++) {
  65432. colors[c * 4] = options.colors[c].r;
  65433. colors[c * 4 + 1] = options.colors[c].g;
  65434. colors[c * 4 + 2] = options.colors[c].b;
  65435. colors[c * 4 + 3] = options.colors[c].a;
  65436. }
  65437. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  65438. }
  65439. if (options.uvs) {
  65440. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  65441. for (var i = 0; i < options.uvs.length; i++) {
  65442. uvs[i * 2] = options.uvs[i].x;
  65443. uvs[i * 2 + 1] = options.uvs[i].y;
  65444. }
  65445. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  65446. }
  65447. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  65448. var indices = instance.getIndices();
  65449. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  65450. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  65451. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  65452. if (instance._closePath) {
  65453. var indexFirst = 0;
  65454. var indexLast = 0;
  65455. for (var p = 0; p < pathArray.length; p++) {
  65456. indexFirst = instance._idx[p] * 3;
  65457. if (p + 1 < pathArray.length) {
  65458. indexLast = (instance._idx[p + 1] - 1) * 3;
  65459. }
  65460. else {
  65461. indexLast = normals.length - 3;
  65462. }
  65463. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  65464. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  65465. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  65466. normals[indexLast] = normals[indexFirst];
  65467. normals[indexLast + 1] = normals[indexFirst + 1];
  65468. normals[indexLast + 2] = normals[indexFirst + 2];
  65469. }
  65470. }
  65471. if (!(instance.areNormalsFrozen)) {
  65472. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  65473. }
  65474. }
  65475. return instance;
  65476. }
  65477. else { // new ribbon creation
  65478. var ribbon = new BABYLON.Mesh(name, scene);
  65479. ribbon._originalBuilderSideOrientation = sideOrientation;
  65480. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  65481. if (closePath) {
  65482. ribbon._idx = vertexData._idx;
  65483. }
  65484. ribbon._closePath = closePath;
  65485. ribbon._closeArray = closeArray;
  65486. vertexData.applyToMesh(ribbon, updatable);
  65487. return ribbon;
  65488. }
  65489. };
  65490. /**
  65491. * Creates a cylinder or a cone mesh
  65492. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  65493. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  65494. * * 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.
  65495. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  65496. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  65497. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  65498. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  65499. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  65500. * * 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).
  65501. * * 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
  65502. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  65503. * * 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
  65504. * * 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.
  65505. * * If `enclose` is false, a ring surface is one element.
  65506. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  65507. * * 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
  65508. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65509. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65510. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65511. * @param name defines the name of the mesh
  65512. * @param options defines the options used to create the mesh
  65513. * @param scene defines the hosting scene
  65514. * @returns the cylinder mesh
  65515. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  65516. */
  65517. MeshBuilder.CreateCylinder = function (name, options, scene) {
  65518. var cylinder = new BABYLON.Mesh(name, scene);
  65519. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65520. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  65521. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  65522. vertexData.applyToMesh(cylinder, options.updatable);
  65523. return cylinder;
  65524. };
  65525. /**
  65526. * Creates a torus mesh
  65527. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  65528. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  65529. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  65530. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65531. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65532. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65533. * @param name defines the name of the mesh
  65534. * @param options defines the options used to create the mesh
  65535. * @param scene defines the hosting scene
  65536. * @returns the torus mesh
  65537. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  65538. */
  65539. MeshBuilder.CreateTorus = function (name, options, scene) {
  65540. var torus = new BABYLON.Mesh(name, scene);
  65541. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65542. torus._originalBuilderSideOrientation = options.sideOrientation;
  65543. var vertexData = BABYLON.VertexData.CreateTorus(options);
  65544. vertexData.applyToMesh(torus, options.updatable);
  65545. return torus;
  65546. };
  65547. /**
  65548. * Creates a torus knot mesh
  65549. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  65550. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  65551. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  65552. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  65553. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65554. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65555. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65556. * @param name defines the name of the mesh
  65557. * @param options defines the options used to create the mesh
  65558. * @param scene defines the hosting scene
  65559. * @returns the torus knot mesh
  65560. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  65561. */
  65562. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  65563. var torusKnot = new BABYLON.Mesh(name, scene);
  65564. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65565. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  65566. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  65567. vertexData.applyToMesh(torusKnot, options.updatable);
  65568. return torusKnot;
  65569. };
  65570. /**
  65571. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  65572. * * 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
  65573. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  65574. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  65575. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  65576. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  65577. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  65578. * * 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
  65579. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  65580. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65581. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  65582. * @param name defines the name of the new line system
  65583. * @param options defines the options used to create the line system
  65584. * @param scene defines the hosting scene
  65585. * @returns a new line system mesh
  65586. */
  65587. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  65588. var instance = options.instance;
  65589. var lines = options.lines;
  65590. var colors = options.colors;
  65591. if (instance) { // lines update
  65592. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  65593. var vertexColor;
  65594. var lineColors;
  65595. if (colors) {
  65596. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  65597. }
  65598. var i = 0;
  65599. var c = 0;
  65600. for (var l = 0; l < lines.length; l++) {
  65601. var points = lines[l];
  65602. for (var p = 0; p < points.length; p++) {
  65603. positions[i] = points[p].x;
  65604. positions[i + 1] = points[p].y;
  65605. positions[i + 2] = points[p].z;
  65606. if (colors && vertexColor) {
  65607. lineColors = colors[l];
  65608. vertexColor[c] = lineColors[p].r;
  65609. vertexColor[c + 1] = lineColors[p].g;
  65610. vertexColor[c + 2] = lineColors[p].b;
  65611. vertexColor[c + 3] = lineColors[p].a;
  65612. c += 4;
  65613. }
  65614. i += 3;
  65615. }
  65616. }
  65617. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  65618. if (colors && vertexColor) {
  65619. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  65620. }
  65621. return instance;
  65622. }
  65623. // line system creation
  65624. var useVertexColor = (colors) ? true : false;
  65625. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  65626. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  65627. vertexData.applyToMesh(lineSystem, options.updatable);
  65628. return lineSystem;
  65629. };
  65630. /**
  65631. * Creates a line mesh
  65632. * 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
  65633. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65634. * * The parameter `points` is an array successive Vector3
  65635. * * 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
  65636. * * The optional parameter `colors` is an array of successive Color4, one per line point
  65637. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  65638. * * When updating an instance, remember that only point positions can change, not the number of points
  65639. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65640. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  65641. * @param name defines the name of the new line system
  65642. * @param options defines the options used to create the line system
  65643. * @param scene defines the hosting scene
  65644. * @returns a new line mesh
  65645. */
  65646. MeshBuilder.CreateLines = function (name, options, scene) {
  65647. if (scene === void 0) { scene = null; }
  65648. var colors = (options.colors) ? [options.colors] : null;
  65649. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  65650. return lines;
  65651. };
  65652. /**
  65653. * Creates a dashed line mesh
  65654. * * 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
  65655. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  65656. * * The parameter `points` is an array successive Vector3
  65657. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  65658. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  65659. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  65660. * * 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
  65661. * * When updating an instance, remember that only point positions can change, not the number of points
  65662. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65663. * @param name defines the name of the mesh
  65664. * @param options defines the options used to create the mesh
  65665. * @param scene defines the hosting scene
  65666. * @returns the dashed line mesh
  65667. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  65668. */
  65669. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  65670. if (scene === void 0) { scene = null; }
  65671. var points = options.points;
  65672. var instance = options.instance;
  65673. var gapSize = options.gapSize || 1;
  65674. var dashSize = options.dashSize || 3;
  65675. if (instance) { // dashed lines update
  65676. var positionFunction = function (positions) {
  65677. var curvect = BABYLON.Vector3.Zero();
  65678. var nbSeg = positions.length / 6;
  65679. var lg = 0;
  65680. var nb = 0;
  65681. var shft = 0;
  65682. var dashshft = 0;
  65683. var curshft = 0;
  65684. var p = 0;
  65685. var i = 0;
  65686. var j = 0;
  65687. for (i = 0; i < points.length - 1; i++) {
  65688. points[i + 1].subtractToRef(points[i], curvect);
  65689. lg += curvect.length();
  65690. }
  65691. shft = lg / nbSeg;
  65692. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  65693. for (i = 0; i < points.length - 1; i++) {
  65694. points[i + 1].subtractToRef(points[i], curvect);
  65695. nb = Math.floor(curvect.length() / shft);
  65696. curvect.normalize();
  65697. j = 0;
  65698. while (j < nb && p < positions.length) {
  65699. curshft = shft * j;
  65700. positions[p] = points[i].x + curshft * curvect.x;
  65701. positions[p + 1] = points[i].y + curshft * curvect.y;
  65702. positions[p + 2] = points[i].z + curshft * curvect.z;
  65703. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  65704. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  65705. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  65706. p += 6;
  65707. j++;
  65708. }
  65709. }
  65710. while (p < positions.length) {
  65711. positions[p] = points[i].x;
  65712. positions[p + 1] = points[i].y;
  65713. positions[p + 2] = points[i].z;
  65714. p += 3;
  65715. }
  65716. };
  65717. instance.updateMeshPositions(positionFunction, false);
  65718. return instance;
  65719. }
  65720. // dashed lines creation
  65721. var dashedLines = new BABYLON.LinesMesh(name, scene);
  65722. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  65723. vertexData.applyToMesh(dashedLines, options.updatable);
  65724. dashedLines.dashSize = dashSize;
  65725. dashedLines.gapSize = gapSize;
  65726. return dashedLines;
  65727. };
  65728. /**
  65729. * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  65730. * * 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 extruded along the Z axis.
  65731. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65732. * * 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.
  65733. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  65734. * * 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
  65735. * * 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
  65736. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  65737. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65738. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65739. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  65740. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65741. * @param name defines the name of the mesh
  65742. * @param options defines the options used to create the mesh
  65743. * @param scene defines the hosting scene
  65744. * @returns the extruded shape mesh
  65745. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65746. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65747. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65748. */
  65749. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  65750. if (scene === void 0) { scene = null; }
  65751. var path = options.path;
  65752. var shape = options.shape;
  65753. var scale = options.scale || 1;
  65754. var rotation = options.rotation || 0;
  65755. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  65756. var updatable = options.updatable;
  65757. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65758. var instance = options.instance || null;
  65759. var invertUV = options.invertUV || false;
  65760. 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);
  65761. };
  65762. /**
  65763. * Creates an custom extruded shape mesh.
  65764. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  65765. * * 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 extruded along the Z axis.
  65766. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  65767. * * 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 and the distance of this point from the begining of the path
  65768. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  65769. * * 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 and the distance of this point from the begining of the path
  65770. * * It must returns a float value that will be the scale value applied to the shape on each path point
  65771. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  65772. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  65773. * * 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
  65774. * * 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
  65775. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  65776. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65777. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65778. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65779. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65780. * @param name defines the name of the mesh
  65781. * @param options defines the options used to create the mesh
  65782. * @param scene defines the hosting scene
  65783. * @returns the custom extruded shape mesh
  65784. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  65785. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  65786. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  65787. */
  65788. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  65789. var path = options.path;
  65790. var shape = options.shape;
  65791. var scaleFunction = options.scaleFunction || (function () { return 1; });
  65792. var rotationFunction = options.rotationFunction || (function () { return 0; });
  65793. var ribbonCloseArray = options.ribbonCloseArray || false;
  65794. var ribbonClosePath = options.ribbonClosePath || false;
  65795. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  65796. var updatable = options.updatable;
  65797. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65798. var instance = options.instance;
  65799. var invertUV = options.invertUV || false;
  65800. 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);
  65801. };
  65802. /**
  65803. * Creates lathe mesh.
  65804. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  65805. * * 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  65806. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  65807. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  65808. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  65809. * * 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
  65810. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  65811. * * 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
  65812. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65813. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65814. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  65815. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65816. * @param name defines the name of the mesh
  65817. * @param options defines the options used to create the mesh
  65818. * @param scene defines the hosting scene
  65819. * @returns the lathe mesh
  65820. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  65821. */
  65822. MeshBuilder.CreateLathe = function (name, options, scene) {
  65823. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  65824. var closed = (options.closed === undefined) ? true : options.closed;
  65825. var shape = options.shape;
  65826. var radius = options.radius || 1;
  65827. var tessellation = options.tessellation || 64;
  65828. var clip = options.clip || 0;
  65829. var updatable = options.updatable;
  65830. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65831. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  65832. var pi2 = Math.PI * 2;
  65833. var paths = new Array();
  65834. var invertUV = options.invertUV || false;
  65835. var i = 0;
  65836. var p = 0;
  65837. var step = pi2 / tessellation * arc;
  65838. var rotated;
  65839. var path = new Array();
  65840. for (i = 0; i <= tessellation - clip; i++) {
  65841. var path = [];
  65842. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  65843. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  65844. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  65845. }
  65846. for (p = 0; p < shape.length; p++) {
  65847. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  65848. path.push(rotated);
  65849. }
  65850. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  65851. 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));
  65852. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  65853. }
  65854. paths.push(path);
  65855. }
  65856. // lathe ribbon
  65857. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  65858. return lathe;
  65859. };
  65860. /**
  65861. * Creates a plane mesh
  65862. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  65863. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  65864. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  65865. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  65866. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  65867. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65868. * @param name defines the name of the mesh
  65869. * @param options defines the options used to create the mesh
  65870. * @param scene defines the hosting scene
  65871. * @returns the plane mesh
  65872. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  65873. */
  65874. MeshBuilder.CreatePlane = function (name, options, scene) {
  65875. var plane = new BABYLON.Mesh(name, scene);
  65876. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  65877. plane._originalBuilderSideOrientation = options.sideOrientation;
  65878. var vertexData = BABYLON.VertexData.CreatePlane(options);
  65879. vertexData.applyToMesh(plane, options.updatable);
  65880. if (options.sourcePlane) {
  65881. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  65882. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  65883. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  65884. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  65885. plane.rotate(vectorProduct, product);
  65886. }
  65887. }
  65888. return plane;
  65889. };
  65890. /**
  65891. * Creates a ground mesh
  65892. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  65893. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  65894. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  65895. * @param name defines the name of the mesh
  65896. * @param options defines the options used to create the mesh
  65897. * @param scene defines the hosting scene
  65898. * @returns the ground mesh
  65899. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  65900. */
  65901. MeshBuilder.CreateGround = function (name, options, scene) {
  65902. var ground = new BABYLON.GroundMesh(name, scene);
  65903. ground._setReady(false);
  65904. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  65905. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  65906. ground._width = options.width || 1;
  65907. ground._height = options.height || 1;
  65908. ground._maxX = ground._width / 2;
  65909. ground._maxZ = ground._height / 2;
  65910. ground._minX = -ground._maxX;
  65911. ground._minZ = -ground._maxZ;
  65912. var vertexData = BABYLON.VertexData.CreateGround(options);
  65913. vertexData.applyToMesh(ground, options.updatable);
  65914. ground._setReady(true);
  65915. return ground;
  65916. };
  65917. /**
  65918. * Creates a tiled ground mesh
  65919. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  65920. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  65921. * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  65922. * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  65923. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65924. * @param name defines the name of the mesh
  65925. * @param options defines the options used to create the mesh
  65926. * @param scene defines the hosting scene
  65927. * @returns the tiled ground mesh
  65928. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  65929. */
  65930. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  65931. var tiledGround = new BABYLON.Mesh(name, scene);
  65932. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  65933. vertexData.applyToMesh(tiledGround, options.updatable);
  65934. return tiledGround;
  65935. };
  65936. /**
  65937. * Creates a ground mesh from a height map
  65938. * * The parameter `url` sets the URL of the height map image resource.
  65939. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  65940. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  65941. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  65942. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  65943. * * 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.
  65944. * * 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).
  65945. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  65946. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  65947. * @param name defines the name of the mesh
  65948. * @param url defines the url to the height map
  65949. * @param options defines the options used to create the mesh
  65950. * @param scene defines the hosting scene
  65951. * @returns the ground mesh
  65952. * @see http://doc.babylonjs.com/babylon101/height_map
  65953. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  65954. */
  65955. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  65956. var width = options.width || 10.0;
  65957. var height = options.height || 10.0;
  65958. var subdivisions = options.subdivisions || 1 | 0;
  65959. var minHeight = options.minHeight || 0.0;
  65960. var maxHeight = options.maxHeight || 1.0;
  65961. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  65962. var alphaFilter = options.alphaFilter || 0.0;
  65963. var updatable = options.updatable;
  65964. var onReady = options.onReady;
  65965. var ground = new BABYLON.GroundMesh(name, scene);
  65966. ground._subdivisionsX = subdivisions;
  65967. ground._subdivisionsY = subdivisions;
  65968. ground._width = width;
  65969. ground._height = height;
  65970. ground._maxX = ground._width / 2.0;
  65971. ground._maxZ = ground._height / 2.0;
  65972. ground._minX = -ground._maxX;
  65973. ground._minZ = -ground._maxZ;
  65974. ground._setReady(false);
  65975. var onload = function (img) {
  65976. // Getting height map data
  65977. var canvas = document.createElement("canvas");
  65978. var context = canvas.getContext("2d");
  65979. if (!context) {
  65980. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  65981. }
  65982. if (scene.isDisposed) {
  65983. return;
  65984. }
  65985. var bufferWidth = img.width;
  65986. var bufferHeight = img.height;
  65987. canvas.width = bufferWidth;
  65988. canvas.height = bufferHeight;
  65989. context.drawImage(img, 0, 0);
  65990. // Create VertexData from map data
  65991. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  65992. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  65993. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  65994. width: width, height: height,
  65995. subdivisions: subdivisions,
  65996. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  65997. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  65998. alphaFilter: alphaFilter
  65999. });
  66000. vertexData.applyToMesh(ground, updatable);
  66001. //execute ready callback, if set
  66002. if (onReady) {
  66003. onReady(ground);
  66004. }
  66005. ground._setReady(true);
  66006. };
  66007. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  66008. return ground;
  66009. };
  66010. /**
  66011. * Creates a polygon mesh
  66012. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  66013. * * 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
  66014. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66015. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66016. * * 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)
  66017. * * Remember you can only change the shape positions, not their number when updating a polygon
  66018. * @param name defines the name of the mesh
  66019. * @param options defines the options used to create the mesh
  66020. * @param scene defines the hosting scene
  66021. * @returns the polygon mesh
  66022. */
  66023. MeshBuilder.CreatePolygon = function (name, options, scene) {
  66024. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66025. var shape = options.shape;
  66026. var holes = options.holes || [];
  66027. var depth = options.depth || 0;
  66028. var contours = [];
  66029. var hole = [];
  66030. for (var i = 0; i < shape.length; i++) {
  66031. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  66032. }
  66033. var epsilon = 0.00000001;
  66034. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  66035. contours.pop();
  66036. }
  66037. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  66038. for (var hNb = 0; hNb < holes.length; hNb++) {
  66039. hole = [];
  66040. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  66041. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  66042. }
  66043. polygonTriangulation.addHole(hole);
  66044. }
  66045. var polygon = polygonTriangulation.build(options.updatable, depth);
  66046. polygon._originalBuilderSideOrientation = options.sideOrientation;
  66047. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  66048. vertexData.applyToMesh(polygon, options.updatable);
  66049. return polygon;
  66050. };
  66051. ;
  66052. /**
  66053. * Creates an extruded polygon mesh, with depth in the Y direction.
  66054. * * 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)
  66055. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  66056. * @param name defines the name of the mesh
  66057. * @param options defines the options used to create the mesh
  66058. * @param scene defines the hosting scene
  66059. * @returns the polygon mesh
  66060. */
  66061. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  66062. return MeshBuilder.CreatePolygon(name, options, scene);
  66063. };
  66064. ;
  66065. /**
  66066. * Creates a tube mesh.
  66067. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  66068. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  66069. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  66070. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  66071. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  66072. * * 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. It must return a radius value (positive float)
  66073. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  66074. * * 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
  66075. * * 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
  66076. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66077. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  66078. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  66079. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66080. * @param name defines the name of the mesh
  66081. * @param options defines the options used to create the mesh
  66082. * @param scene defines the hosting scene
  66083. * @returns the tube mesh
  66084. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  66085. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  66086. */
  66087. MeshBuilder.CreateTube = function (name, options, scene) {
  66088. var path = options.path;
  66089. var instance = options.instance;
  66090. var radius = 1.0;
  66091. if (instance) {
  66092. radius = instance.radius;
  66093. }
  66094. if (options.radius !== undefined) {
  66095. radius = options.radius;
  66096. }
  66097. ;
  66098. var tessellation = options.tessellation || 64 | 0;
  66099. var radiusFunction = options.radiusFunction || null;
  66100. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  66101. var invertUV = options.invertUV || false;
  66102. var updatable = options.updatable;
  66103. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66104. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  66105. // tube geometry
  66106. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  66107. var tangents = path3D.getTangents();
  66108. var normals = path3D.getNormals();
  66109. var distances = path3D.getDistances();
  66110. var pi2 = Math.PI * 2;
  66111. var step = pi2 / tessellation * arc;
  66112. var returnRadius = function () { return radius; };
  66113. var radiusFunctionFinal = radiusFunction || returnRadius;
  66114. var circlePath;
  66115. var rad;
  66116. var normal;
  66117. var rotated;
  66118. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66119. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66120. for (var i = 0; i < path.length; i++) {
  66121. rad = radiusFunctionFinal(i, distances[i]); // current radius
  66122. circlePath = Array(); // current circle array
  66123. normal = normals[i]; // current normal
  66124. for (var t = 0; t < tessellation; t++) {
  66125. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  66126. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  66127. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  66128. rotated.scaleInPlace(rad).addInPlace(path[i]);
  66129. circlePath[t] = rotated;
  66130. }
  66131. circlePaths[index] = circlePath;
  66132. index++;
  66133. }
  66134. // cap
  66135. var capPath = function (nbPoints, pathIndex) {
  66136. var pointCap = Array();
  66137. for (var i = 0; i < nbPoints; i++) {
  66138. pointCap.push(path[pathIndex]);
  66139. }
  66140. return pointCap;
  66141. };
  66142. switch (cap) {
  66143. case BABYLON.Mesh.NO_CAP:
  66144. break;
  66145. case BABYLON.Mesh.CAP_START:
  66146. circlePaths[0] = capPath(tessellation, 0);
  66147. circlePaths[1] = circlePaths[2].slice(0);
  66148. break;
  66149. case BABYLON.Mesh.CAP_END:
  66150. circlePaths[index] = circlePaths[index - 1].slice(0);
  66151. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66152. break;
  66153. case BABYLON.Mesh.CAP_ALL:
  66154. circlePaths[0] = capPath(tessellation, 0);
  66155. circlePaths[1] = circlePaths[2].slice(0);
  66156. circlePaths[index] = circlePaths[index - 1].slice(0);
  66157. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  66158. break;
  66159. default:
  66160. break;
  66161. }
  66162. return circlePaths;
  66163. };
  66164. var path3D;
  66165. var pathArray;
  66166. if (instance) { // tube update
  66167. var arc = options.arc || instance.arc;
  66168. path3D = (instance.path3D).update(path);
  66169. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  66170. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  66171. instance.path3D = path3D;
  66172. instance.pathArray = pathArray;
  66173. instance.arc = arc;
  66174. instance.radius = radius;
  66175. return instance;
  66176. }
  66177. // tube creation
  66178. path3D = new BABYLON.Path3D(path);
  66179. var newPathArray = new Array();
  66180. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66181. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  66182. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  66183. tube.pathArray = pathArray;
  66184. tube.path3D = path3D;
  66185. tube.tessellation = tessellation;
  66186. tube.cap = cap;
  66187. tube.arc = options.arc;
  66188. tube.radius = radius;
  66189. return tube;
  66190. };
  66191. /**
  66192. * Creates a polyhedron mesh
  66193. * * 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 to choose the wanted type
  66194. * * The parameter `size` (positive float, default 1) sets the polygon size
  66195. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  66196. * * 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`
  66197. * * 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
  66198. * * 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)`)
  66199. * * 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
  66200. * * 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
  66201. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  66202. * * 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). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  66203. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  66204. * @param name defines the name of the mesh
  66205. * @param options defines the options used to create the mesh
  66206. * @param scene defines the hosting scene
  66207. * @returns the polyhedron mesh
  66208. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  66209. */
  66210. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  66211. var polyhedron = new BABYLON.Mesh(name, scene);
  66212. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  66213. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  66214. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  66215. vertexData.applyToMesh(polyhedron, options.updatable);
  66216. return polyhedron;
  66217. };
  66218. /**
  66219. * Creates a decal mesh.
  66220. * 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
  66221. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  66222. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  66223. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  66224. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  66225. * @param name defines the name of the mesh
  66226. * @param sourceMesh defines the mesh where the decal must be applied
  66227. * @param options defines the options used to create the mesh
  66228. * @param scene defines the hosting scene
  66229. * @returns the decal mesh
  66230. * @see http://doc.babylonjs.com/how_to/decals
  66231. */
  66232. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  66233. var indices = sourceMesh.getIndices();
  66234. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66235. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66236. var position = options.position || BABYLON.Vector3.Zero();
  66237. var normal = options.normal || BABYLON.Vector3.Up();
  66238. var size = options.size || BABYLON.Vector3.One();
  66239. var angle = options.angle || 0;
  66240. // Getting correct rotation
  66241. if (!normal) {
  66242. var target = new BABYLON.Vector3(0, 0, 1);
  66243. var camera = sourceMesh.getScene().activeCamera;
  66244. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  66245. normal = camera.globalPosition.subtract(cameraWorldTarget);
  66246. }
  66247. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  66248. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  66249. var pitch = Math.atan2(normal.y, len);
  66250. // Matrix
  66251. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  66252. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  66253. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  66254. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  66255. var vertexData = new BABYLON.VertexData();
  66256. vertexData.indices = [];
  66257. vertexData.positions = [];
  66258. vertexData.normals = [];
  66259. vertexData.uvs = [];
  66260. var currentVertexDataIndex = 0;
  66261. var extractDecalVector3 = function (indexId) {
  66262. var result = new BABYLON.PositionNormalVertex();
  66263. if (!indices || !positions || !normals) {
  66264. return result;
  66265. }
  66266. var vertexId = indices[indexId];
  66267. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  66268. // Send vector to decal local world
  66269. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  66270. // Get normal
  66271. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  66272. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  66273. return result;
  66274. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  66275. var clip = function (vertices, axis) {
  66276. if (vertices.length === 0) {
  66277. return vertices;
  66278. }
  66279. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  66280. var clipVertices = function (v0, v1) {
  66281. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  66282. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  66283. };
  66284. var result = new Array();
  66285. for (var index = 0; index < vertices.length; index += 3) {
  66286. var v1Out;
  66287. var v2Out;
  66288. var v3Out;
  66289. var total = 0;
  66290. var nV1 = null;
  66291. var nV2 = null;
  66292. var nV3 = null;
  66293. var nV4 = null;
  66294. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  66295. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  66296. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  66297. v1Out = d1 > 0;
  66298. v2Out = d2 > 0;
  66299. v3Out = d3 > 0;
  66300. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  66301. switch (total) {
  66302. case 0:
  66303. result.push(vertices[index]);
  66304. result.push(vertices[index + 1]);
  66305. result.push(vertices[index + 2]);
  66306. break;
  66307. case 1:
  66308. if (v1Out) {
  66309. nV1 = vertices[index + 1];
  66310. nV2 = vertices[index + 2];
  66311. nV3 = clipVertices(vertices[index], nV1);
  66312. nV4 = clipVertices(vertices[index], nV2);
  66313. }
  66314. if (v2Out) {
  66315. nV1 = vertices[index];
  66316. nV2 = vertices[index + 2];
  66317. nV3 = clipVertices(vertices[index + 1], nV1);
  66318. nV4 = clipVertices(vertices[index + 1], nV2);
  66319. result.push(nV3);
  66320. result.push(nV2.clone());
  66321. result.push(nV1.clone());
  66322. result.push(nV2.clone());
  66323. result.push(nV3.clone());
  66324. result.push(nV4);
  66325. break;
  66326. }
  66327. if (v3Out) {
  66328. nV1 = vertices[index];
  66329. nV2 = vertices[index + 1];
  66330. nV3 = clipVertices(vertices[index + 2], nV1);
  66331. nV4 = clipVertices(vertices[index + 2], nV2);
  66332. }
  66333. if (nV1 && nV2 && nV3 && nV4) {
  66334. result.push(nV1.clone());
  66335. result.push(nV2.clone());
  66336. result.push(nV3);
  66337. result.push(nV4);
  66338. result.push(nV3.clone());
  66339. result.push(nV2.clone());
  66340. }
  66341. break;
  66342. case 2:
  66343. if (!v1Out) {
  66344. nV1 = vertices[index].clone();
  66345. nV2 = clipVertices(nV1, vertices[index + 1]);
  66346. nV3 = clipVertices(nV1, vertices[index + 2]);
  66347. result.push(nV1);
  66348. result.push(nV2);
  66349. result.push(nV3);
  66350. }
  66351. if (!v2Out) {
  66352. nV1 = vertices[index + 1].clone();
  66353. nV2 = clipVertices(nV1, vertices[index + 2]);
  66354. nV3 = clipVertices(nV1, vertices[index]);
  66355. result.push(nV1);
  66356. result.push(nV2);
  66357. result.push(nV3);
  66358. }
  66359. if (!v3Out) {
  66360. nV1 = vertices[index + 2].clone();
  66361. nV2 = clipVertices(nV1, vertices[index]);
  66362. nV3 = clipVertices(nV1, vertices[index + 1]);
  66363. result.push(nV1);
  66364. result.push(nV2);
  66365. result.push(nV3);
  66366. }
  66367. break;
  66368. case 3:
  66369. break;
  66370. }
  66371. }
  66372. return result;
  66373. };
  66374. for (var index = 0; index < indices.length; index += 3) {
  66375. var faceVertices = new Array();
  66376. faceVertices.push(extractDecalVector3(index));
  66377. faceVertices.push(extractDecalVector3(index + 1));
  66378. faceVertices.push(extractDecalVector3(index + 2));
  66379. // Clip
  66380. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  66381. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  66382. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  66383. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  66384. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  66385. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  66386. if (faceVertices.length === 0) {
  66387. continue;
  66388. }
  66389. // Add UVs and get back to world
  66390. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  66391. var vertex = faceVertices[vIndex];
  66392. //TODO check for Int32Array | Uint32Array | Uint16Array
  66393. vertexData.indices.push(currentVertexDataIndex);
  66394. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  66395. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  66396. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  66397. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  66398. currentVertexDataIndex++;
  66399. }
  66400. }
  66401. // Return mesh
  66402. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  66403. vertexData.applyToMesh(decal);
  66404. decal.position = position.clone();
  66405. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  66406. return decal;
  66407. };
  66408. // Privates
  66409. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  66410. // extrusion geometry
  66411. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  66412. var tangents = path3D.getTangents();
  66413. var normals = path3D.getNormals();
  66414. var binormals = path3D.getBinormals();
  66415. var distances = path3D.getDistances();
  66416. var angle = 0;
  66417. var returnScale = function () { return scale !== null ? scale : 1; };
  66418. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  66419. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  66420. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  66421. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  66422. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  66423. for (var i = 0; i < curve.length; i++) {
  66424. var shapePath = new Array();
  66425. var angleStep = rotate(i, distances[i]);
  66426. var scaleRatio = scl(i, distances[i]);
  66427. for (var p = 0; p < shape.length; p++) {
  66428. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  66429. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  66430. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  66431. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  66432. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  66433. shapePath[p] = rotated;
  66434. }
  66435. shapePaths[index] = shapePath;
  66436. angle += angleStep;
  66437. index++;
  66438. }
  66439. // cap
  66440. var capPath = function (shapePath) {
  66441. var pointCap = Array();
  66442. var barycenter = BABYLON.Vector3.Zero();
  66443. var i;
  66444. for (i = 0; i < shapePath.length; i++) {
  66445. barycenter.addInPlace(shapePath[i]);
  66446. }
  66447. barycenter.scaleInPlace(1.0 / shapePath.length);
  66448. for (i = 0; i < shapePath.length; i++) {
  66449. pointCap.push(barycenter);
  66450. }
  66451. return pointCap;
  66452. };
  66453. switch (cap) {
  66454. case BABYLON.Mesh.NO_CAP:
  66455. break;
  66456. case BABYLON.Mesh.CAP_START:
  66457. shapePaths[0] = capPath(shapePaths[2]);
  66458. shapePaths[1] = shapePaths[2];
  66459. break;
  66460. case BABYLON.Mesh.CAP_END:
  66461. shapePaths[index] = shapePaths[index - 1];
  66462. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66463. break;
  66464. case BABYLON.Mesh.CAP_ALL:
  66465. shapePaths[0] = capPath(shapePaths[2]);
  66466. shapePaths[1] = shapePaths[2];
  66467. shapePaths[index] = shapePaths[index - 1];
  66468. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  66469. break;
  66470. default:
  66471. break;
  66472. }
  66473. return shapePaths;
  66474. };
  66475. var path3D;
  66476. var pathArray;
  66477. if (instance) { // instance update
  66478. path3D = (instance.path3D).update(curve);
  66479. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  66480. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  66481. return instance;
  66482. }
  66483. // extruded shape creation
  66484. path3D = new BABYLON.Path3D(curve);
  66485. var newShapePaths = new Array();
  66486. cap = (cap < 0 || cap > 3) ? 0 : cap;
  66487. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  66488. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  66489. extrudedGeneric.pathArray = pathArray;
  66490. extrudedGeneric.path3D = path3D;
  66491. extrudedGeneric.cap = cap;
  66492. return extrudedGeneric;
  66493. };
  66494. return MeshBuilder;
  66495. }());
  66496. BABYLON.MeshBuilder = MeshBuilder;
  66497. })(BABYLON || (BABYLON = {}));
  66498. //# sourceMappingURL=babylon.meshBuilder.js.map
  66499. var BABYLON;
  66500. (function (BABYLON) {
  66501. /**
  66502. * Draco compression (https://google.github.io/draco/)
  66503. *
  66504. * This class wraps the Draco module.
  66505. *
  66506. * **Encoder**
  66507. *
  66508. * The encoder is not currently implemented.
  66509. *
  66510. * **Decoder**
  66511. *
  66512. * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
  66513. *
  66514. * To update the configuration, use the following code:
  66515. * ```javascript
  66516. * BABYLON.DracoCompression.Configuration = {
  66517. * decoder: {
  66518. * wasmUrl: "<url to the WebAssembly library>",
  66519. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  66520. * fallbackUrl: "<url to the fallback JavaScript library>",
  66521. * }
  66522. * };
  66523. * ```
  66524. *
  66525. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  66526. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  66527. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  66528. *
  66529. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  66530. * ```javascript
  66531. * var dracoCompression = new BABYLON.DracoCompression();
  66532. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  66533. * [BABYLON.VertexBuffer.PositionKind]: 0
  66534. * });
  66535. * ```
  66536. *
  66537. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  66538. */
  66539. var DracoCompression = /** @class */ (function () {
  66540. /**
  66541. * Constructor
  66542. */
  66543. function DracoCompression() {
  66544. }
  66545. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  66546. /**
  66547. * Returns true if the decoder is available.
  66548. */
  66549. get: function () {
  66550. if (typeof DracoDecoderModule !== "undefined") {
  66551. return true;
  66552. }
  66553. var decoder = DracoCompression.Configuration.decoder;
  66554. if (decoder) {
  66555. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66556. return true;
  66557. }
  66558. if (decoder.fallbackUrl) {
  66559. return true;
  66560. }
  66561. }
  66562. return false;
  66563. },
  66564. enumerable: true,
  66565. configurable: true
  66566. });
  66567. /**
  66568. * Stop all async operations and release resources.
  66569. */
  66570. DracoCompression.prototype.dispose = function () {
  66571. };
  66572. /**
  66573. * Decode Draco compressed mesh data to vertex data.
  66574. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  66575. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  66576. * @returns A promise that resolves with the decoded vertex data
  66577. */
  66578. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  66579. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  66580. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  66581. var module = wrappedModule.module;
  66582. var vertexData = new BABYLON.VertexData();
  66583. var buffer = new module.DecoderBuffer();
  66584. buffer.Init(dataView, dataView.byteLength);
  66585. var decoder = new module.Decoder();
  66586. var geometry;
  66587. var status;
  66588. try {
  66589. var type = decoder.GetEncodedGeometryType(buffer);
  66590. switch (type) {
  66591. case module.TRIANGULAR_MESH:
  66592. geometry = new module.Mesh();
  66593. status = decoder.DecodeBufferToMesh(buffer, geometry);
  66594. break;
  66595. case module.POINT_CLOUD:
  66596. geometry = new module.PointCloud();
  66597. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  66598. break;
  66599. default:
  66600. throw new Error("Invalid geometry type " + type);
  66601. }
  66602. if (!status.ok() || !geometry.ptr) {
  66603. throw new Error(status.error_msg());
  66604. }
  66605. var numPoints = geometry.num_points();
  66606. if (type === module.TRIANGULAR_MESH) {
  66607. var numFaces = geometry.num_faces();
  66608. var faceIndices = new module.DracoInt32Array();
  66609. try {
  66610. var indices = new Uint32Array(numFaces * 3);
  66611. for (var i = 0; i < numFaces; i++) {
  66612. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  66613. var offset = i * 3;
  66614. indices[offset + 0] = faceIndices.GetValue(0);
  66615. indices[offset + 1] = faceIndices.GetValue(1);
  66616. indices[offset + 2] = faceIndices.GetValue(2);
  66617. }
  66618. vertexData.indices = indices;
  66619. }
  66620. finally {
  66621. module.destroy(faceIndices);
  66622. }
  66623. }
  66624. for (var kind in attributes) {
  66625. var uniqueId = attributes[kind];
  66626. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  66627. var dracoData = new module.DracoFloat32Array();
  66628. try {
  66629. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  66630. var babylonData = new Float32Array(numPoints * attribute.num_components());
  66631. for (var i = 0; i < babylonData.length; i++) {
  66632. babylonData[i] = dracoData.GetValue(i);
  66633. }
  66634. vertexData.set(babylonData, kind);
  66635. }
  66636. finally {
  66637. module.destroy(dracoData);
  66638. }
  66639. }
  66640. }
  66641. finally {
  66642. if (geometry) {
  66643. module.destroy(geometry);
  66644. }
  66645. module.destroy(decoder);
  66646. module.destroy(buffer);
  66647. }
  66648. return vertexData;
  66649. });
  66650. };
  66651. DracoCompression._GetDecoderModule = function () {
  66652. if (!DracoCompression._DecoderModulePromise) {
  66653. var promise = null;
  66654. var config_1 = {};
  66655. if (typeof DracoDecoderModule !== "undefined") {
  66656. promise = Promise.resolve();
  66657. }
  66658. else {
  66659. var decoder = DracoCompression.Configuration.decoder;
  66660. if (decoder) {
  66661. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  66662. promise = Promise.all([
  66663. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  66664. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  66665. config_1.wasmBinary = data;
  66666. })
  66667. ]);
  66668. }
  66669. else if (decoder.fallbackUrl) {
  66670. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  66671. }
  66672. }
  66673. }
  66674. if (!promise) {
  66675. throw new Error("Draco decoder module is not available");
  66676. }
  66677. DracoCompression._DecoderModulePromise = promise.then(function () {
  66678. return new Promise(function (resolve) {
  66679. config_1.onModuleLoaded = function (decoderModule) {
  66680. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  66681. resolve({ module: decoderModule });
  66682. };
  66683. DracoDecoderModule(config_1);
  66684. });
  66685. });
  66686. }
  66687. return DracoCompression._DecoderModulePromise;
  66688. };
  66689. DracoCompression._LoadScriptAsync = function (url) {
  66690. return new Promise(function (resolve, reject) {
  66691. BABYLON.Tools.LoadScript(url, function () {
  66692. resolve();
  66693. }, function (message) {
  66694. reject(new Error(message));
  66695. });
  66696. });
  66697. };
  66698. DracoCompression._LoadFileAsync = function (url) {
  66699. return new Promise(function (resolve, reject) {
  66700. BABYLON.Tools.LoadFile(url, function (data) {
  66701. resolve(data);
  66702. }, undefined, undefined, true, function (request, exception) {
  66703. reject(exception);
  66704. });
  66705. });
  66706. };
  66707. /**
  66708. * The configuration. Defaults to the following urls:
  66709. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  66710. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  66711. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66712. */
  66713. DracoCompression.Configuration = {
  66714. decoder: {
  66715. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  66716. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  66717. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  66718. }
  66719. };
  66720. return DracoCompression;
  66721. }());
  66722. BABYLON.DracoCompression = DracoCompression;
  66723. })(BABYLON || (BABYLON = {}));
  66724. //# sourceMappingURL=babylon.dracoCompression.js.map
  66725. var BABYLON;
  66726. (function (BABYLON) {
  66727. // Sets the default audio engine to Babylon JS.
  66728. BABYLON.Engine.AudioEngineFactory = function (engine) { return new AudioEngine(engine); };
  66729. /**
  66730. * This represents the default audio engine used in babylon.
  66731. * It is responsible to play, synchronize and analyse sounds throughout the application.
  66732. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66733. */
  66734. var AudioEngine = /** @class */ (function () {
  66735. /**
  66736. * Instantiates a new audio engine.
  66737. *
  66738. * There should be only one per page as some browsers restrict the number
  66739. * of audio contexts you can create.
  66740. * @param engine defines the hosting engine
  66741. */
  66742. function AudioEngine(engine) {
  66743. if (engine === void 0) { engine = BABYLON.Engine.LastCreatedEngine; }
  66744. var _this = this;
  66745. this._audioContext = null;
  66746. this._audioContextInitialized = false;
  66747. this._muteButtonDisplayed = false;
  66748. /**
  66749. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  66750. */
  66751. this.canUseWebAudio = false;
  66752. /**
  66753. * Defines if Babylon should emit a warning if WebAudio is not supported.
  66754. * @ignoreNaming
  66755. */
  66756. this.WarnedWebAudioUnsupported = false;
  66757. /**
  66758. * Gets whether or not mp3 are supported by your browser.
  66759. */
  66760. this.isMP3supported = false;
  66761. /**
  66762. * Gets whether or not ogg are supported by your browser.
  66763. */
  66764. this.isOGGsupported = false;
  66765. /**
  66766. * Gets whether audio has been unlocked on the device.
  66767. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  66768. * a user interaction has happened.
  66769. */
  66770. this.unlocked = false;
  66771. /**
  66772. * Event raised when audio has been unlocked on the browser.
  66773. */
  66774. this.onAudioUnlockedObservable = new BABYLON.Observable();
  66775. this._onResize = function () {
  66776. _this._moveButtonToTopLeft();
  66777. };
  66778. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  66779. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  66780. this.canUseWebAudio = true;
  66781. }
  66782. var audioElem = document.createElement('audio');
  66783. this._engine = engine;
  66784. try {
  66785. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  66786. this.isMP3supported = true;
  66787. }
  66788. }
  66789. catch (e) {
  66790. // protect error during capability check.
  66791. }
  66792. try {
  66793. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  66794. this.isOGGsupported = true;
  66795. }
  66796. }
  66797. catch (e) {
  66798. // protect error during capability check.
  66799. }
  66800. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  66801. this._unlockiOSaudio();
  66802. }
  66803. }
  66804. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  66805. /**
  66806. * Gets the current AudioContext if available.
  66807. */
  66808. get: function () {
  66809. if (!this._audioContextInitialized) {
  66810. this._initializeAudioContext();
  66811. }
  66812. else {
  66813. if (!this.unlocked && !this._muteButtonDisplayed) {
  66814. this._displayMuteButton();
  66815. }
  66816. }
  66817. return this._audioContext;
  66818. },
  66819. enumerable: true,
  66820. configurable: true
  66821. });
  66822. AudioEngine.prototype._unlockiOSaudio = function () {
  66823. var _this = this;
  66824. this._displayMuteButton(true);
  66825. var unlockaudio = function () {
  66826. if (!_this.audioContext) {
  66827. return;
  66828. }
  66829. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  66830. var source = _this.audioContext.createBufferSource();
  66831. source.buffer = buffer;
  66832. source.connect(_this.audioContext.destination);
  66833. source.start(0);
  66834. setTimeout(function () {
  66835. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  66836. _this._triggerRunningState();
  66837. _this._muteButton.removeEventListener('touchend', unlockaudio, false);
  66838. }
  66839. }, 0);
  66840. };
  66841. this._muteButton.addEventListener('touchend', unlockaudio, false);
  66842. };
  66843. AudioEngine.prototype._resumeAudioContext = function () {
  66844. this._audioContext.resume();
  66845. };
  66846. AudioEngine.prototype._initializeAudioContext = function () {
  66847. var _this = this;
  66848. try {
  66849. if (this.canUseWebAudio) {
  66850. this._audioContext = new AudioContext();
  66851. // create a global volume gain node
  66852. this.masterGain = this._audioContext.createGain();
  66853. this.masterGain.gain.value = 1;
  66854. this.masterGain.connect(this._audioContext.destination);
  66855. this._audioContextInitialized = true;
  66856. if (this._audioContext.state === "running") {
  66857. this._triggerRunningState();
  66858. }
  66859. else {
  66860. if (!this._muteButtonDisplayed) {
  66861. this._displayMuteButton();
  66862. }
  66863. // 3 possible states: https://webaudio.github.io/web-audio-api/#BaseAudioContext
  66864. this._audioContext.addEventListener("statechange", function () {
  66865. if (_this._audioContext.state === "running") {
  66866. _this._triggerRunningState();
  66867. }
  66868. else {
  66869. _this._triggerSuspendedState();
  66870. }
  66871. });
  66872. }
  66873. }
  66874. }
  66875. catch (e) {
  66876. this.canUseWebAudio = false;
  66877. BABYLON.Tools.Error("Web Audio: " + e.message);
  66878. }
  66879. };
  66880. AudioEngine.prototype._triggerRunningState = function () {
  66881. this.unlocked = true;
  66882. if (this._muteButtonDisplayed) {
  66883. this._hideMuteButton();
  66884. }
  66885. // Notify users that the audio stack is unlocked/unmuted
  66886. this.onAudioUnlockedObservable.notifyObservers(this);
  66887. };
  66888. AudioEngine.prototype._triggerSuspendedState = function () {
  66889. this.unlocked = false;
  66890. this._displayMuteButton();
  66891. };
  66892. AudioEngine.prototype._displayMuteButton = function (iOS) {
  66893. var _this = this;
  66894. if (iOS === void 0) { iOS = false; }
  66895. this._muteButton = document.createElement("BUTTON");
  66896. this._muteButton.className = "babylonUnmuteIcon";
  66897. this._muteButton.id = "babylonUnmuteIconBtn";
  66898. this._muteButton.title = "Unmute";
  66899. var css = ".babylonUnmuteIcon { position: absolute; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 90%; background-repeat:no-repeat; border: none; outline: none; } }";
  66900. var style = document.createElement('style');
  66901. style.appendChild(document.createTextNode(css));
  66902. document.getElementsByTagName('head')[0].appendChild(style);
  66903. this._moveButtonToTopLeft();
  66904. document.body.appendChild(this._muteButton);
  66905. if (!iOS) {
  66906. this._muteButton.addEventListener('mousedown', function () { _this._resumeAudioContext(); }, false);
  66907. }
  66908. this._muteButtonDisplayed = true;
  66909. this._canvas = this._engine.getRenderingCanvas();
  66910. window.addEventListener("resize", this._onResize);
  66911. };
  66912. AudioEngine.prototype._moveButtonToTopLeft = function () {
  66913. if (this._canvas && this._muteButton) {
  66914. this._muteButton.style.top = this._canvas.offsetTop + 20 + "px";
  66915. this._muteButton.style.left = this._canvas.offsetLeft + 20 + "px";
  66916. }
  66917. };
  66918. AudioEngine.prototype._hideMuteButton = function () {
  66919. if (this._muteButtonDisplayed) {
  66920. document.body.removeChild(this._muteButton);
  66921. this._muteButtonDisplayed = false;
  66922. }
  66923. };
  66924. /**
  66925. * Destroy and release the resources associated with the audio ccontext.
  66926. */
  66927. AudioEngine.prototype.dispose = function () {
  66928. if (this.canUseWebAudio && this._audioContextInitialized) {
  66929. if (this._connectedAnalyser && this._audioContext) {
  66930. this._connectedAnalyser.stopDebugCanvas();
  66931. this._connectedAnalyser.dispose();
  66932. this.masterGain.disconnect();
  66933. this.masterGain.connect(this._audioContext.destination);
  66934. this._connectedAnalyser = null;
  66935. }
  66936. this.masterGain.gain.value = 1;
  66937. }
  66938. this.WarnedWebAudioUnsupported = false;
  66939. this._hideMuteButton();
  66940. window.removeEventListener("resize", this._onResize);
  66941. this.onAudioUnlockedObservable.clear();
  66942. };
  66943. /**
  66944. * Gets the global volume sets on the master gain.
  66945. * @returns the global volume if set or -1 otherwise
  66946. */
  66947. AudioEngine.prototype.getGlobalVolume = function () {
  66948. if (this.canUseWebAudio && this._audioContextInitialized) {
  66949. return this.masterGain.gain.value;
  66950. }
  66951. else {
  66952. return -1;
  66953. }
  66954. };
  66955. /**
  66956. * Sets the global volume of your experience (sets on the master gain).
  66957. * @param newVolume Defines the new global volume of the application
  66958. */
  66959. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  66960. if (this.canUseWebAudio && this._audioContextInitialized) {
  66961. this.masterGain.gain.value = newVolume;
  66962. }
  66963. };
  66964. /**
  66965. * Connect the audio engine to an audio analyser allowing some amazing
  66966. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  66967. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  66968. * @param analyser The analyser to connect to the engine
  66969. */
  66970. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  66971. if (this._connectedAnalyser) {
  66972. this._connectedAnalyser.stopDebugCanvas();
  66973. }
  66974. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  66975. this._connectedAnalyser = analyser;
  66976. this.masterGain.disconnect();
  66977. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  66978. }
  66979. };
  66980. return AudioEngine;
  66981. }());
  66982. BABYLON.AudioEngine = AudioEngine;
  66983. })(BABYLON || (BABYLON = {}));
  66984. //# sourceMappingURL=babylon.audioEngine.js.map
  66985. var BABYLON;
  66986. (function (BABYLON) {
  66987. /**
  66988. * Defines a sound that can be played in the application.
  66989. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  66990. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  66991. */
  66992. var Sound = /** @class */ (function () {
  66993. /**
  66994. * Create a sound and attach it to a scene
  66995. * @param name Name of your sound
  66996. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  66997. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  66998. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  66999. */
  67000. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  67001. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  67002. var _this = this;
  67003. /**
  67004. * Does the sound autoplay once loaded.
  67005. */
  67006. this.autoplay = false;
  67007. /**
  67008. * Does the sound loop after it finishes playing once.
  67009. */
  67010. this.loop = false;
  67011. /**
  67012. * Does the sound use a custom attenuation curve to simulate the falloff
  67013. * happening when the source gets further away from the camera.
  67014. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  67015. */
  67016. this.useCustomAttenuation = false;
  67017. /**
  67018. * Does this sound enables spatial sound.
  67019. */
  67020. this.spatialSound = false;
  67021. this.refDistance = 1;
  67022. this.rolloffFactor = 1;
  67023. this.maxDistance = 100;
  67024. this.distanceModel = "linear";
  67025. this._panningModel = "equalpower";
  67026. /**
  67027. * Observable event when the current playing sound finishes.
  67028. */
  67029. this.onEndedObservable = new BABYLON.Observable();
  67030. this._playbackRate = 1;
  67031. this._streaming = false;
  67032. this._startTime = 0;
  67033. this._startOffset = 0;
  67034. this._position = BABYLON.Vector3.Zero();
  67035. /** @hidden */
  67036. this._positionInEmitterSpace = false;
  67037. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  67038. this._volume = 1;
  67039. this._isReadyToPlay = false;
  67040. this.isPlaying = false;
  67041. this.isPaused = false;
  67042. this._isDirectional = false;
  67043. // Used if you'd like to create a directional sound.
  67044. // If not set, the sound will be omnidirectional
  67045. this._coneInnerAngle = 360;
  67046. this._coneOuterAngle = 360;
  67047. this._coneOuterGain = 0;
  67048. this._isOutputConnected = false;
  67049. this._urlType = "Unknown";
  67050. this.name = name;
  67051. this._scene = scene;
  67052. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  67053. if (!compo) {
  67054. compo = new BABYLON.AudioSceneComponent(scene);
  67055. scene._addComponent(compo);
  67056. }
  67057. this._readyToPlayCallback = readyToPlayCallback;
  67058. // Default custom attenuation function is a linear attenuation
  67059. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  67060. if (currentDistance < maxDistance) {
  67061. return currentVolume * (1 - currentDistance / maxDistance);
  67062. }
  67063. else {
  67064. return 0;
  67065. }
  67066. };
  67067. if (options) {
  67068. this.autoplay = options.autoplay || false;
  67069. this.loop = options.loop || false;
  67070. // if volume === 0, we need another way to check this option
  67071. if (options.volume !== undefined) {
  67072. this._volume = options.volume;
  67073. }
  67074. this.spatialSound = options.spatialSound || false;
  67075. this.maxDistance = options.maxDistance || 100;
  67076. this.useCustomAttenuation = options.useCustomAttenuation || false;
  67077. this.rolloffFactor = options.rolloffFactor || 1;
  67078. this.refDistance = options.refDistance || 1;
  67079. this.distanceModel = options.distanceModel || "linear";
  67080. this._playbackRate = options.playbackRate || 1;
  67081. this._streaming = options.streaming || false;
  67082. }
  67083. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67084. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  67085. this._soundGain.gain.value = this._volume;
  67086. this._inputAudioNode = this._soundGain;
  67087. this._outputAudioNode = this._soundGain;
  67088. if (this.spatialSound) {
  67089. this._createSpatialParameters();
  67090. }
  67091. this._scene.mainSoundTrack.AddSound(this);
  67092. var validParameter = true;
  67093. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  67094. if (urlOrArrayBuffer) {
  67095. try {
  67096. if (typeof (urlOrArrayBuffer) === "string") {
  67097. this._urlType = "String";
  67098. }
  67099. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  67100. this._urlType = "ArrayBuffer";
  67101. }
  67102. else if (urlOrArrayBuffer instanceof MediaStream) {
  67103. this._urlType = "MediaStream";
  67104. }
  67105. else if (Array.isArray(urlOrArrayBuffer)) {
  67106. this._urlType = "Array";
  67107. }
  67108. var urls = [];
  67109. var codecSupportedFound = false;
  67110. switch (this._urlType) {
  67111. case "MediaStream":
  67112. this._streaming = true;
  67113. this._isReadyToPlay = true;
  67114. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  67115. if (this.autoplay) {
  67116. this.play();
  67117. }
  67118. if (this._readyToPlayCallback) {
  67119. this._readyToPlayCallback();
  67120. }
  67121. break;
  67122. case "ArrayBuffer":
  67123. if (urlOrArrayBuffer.byteLength > 0) {
  67124. codecSupportedFound = true;
  67125. this._soundLoaded(urlOrArrayBuffer);
  67126. }
  67127. break;
  67128. case "String":
  67129. urls.push(urlOrArrayBuffer);
  67130. case "Array":
  67131. if (urls.length === 0)
  67132. urls = urlOrArrayBuffer;
  67133. // If we found a supported format, we load it immediately and stop the loop
  67134. for (var i = 0; i < urls.length; i++) {
  67135. var url = urls[i];
  67136. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  67137. codecSupportedFound = true;
  67138. }
  67139. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  67140. codecSupportedFound = true;
  67141. }
  67142. if (url.indexOf(".wav", url.length - 4) !== -1) {
  67143. codecSupportedFound = true;
  67144. }
  67145. if (url.indexOf("blob:") !== -1) {
  67146. codecSupportedFound = true;
  67147. }
  67148. if (codecSupportedFound) {
  67149. // Loading sound using XHR2
  67150. if (!this._streaming) {
  67151. this._scene._loadFile(url, function (data) {
  67152. _this._soundLoaded(data);
  67153. }, undefined, true, true, function (exception) {
  67154. if (exception) {
  67155. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  67156. }
  67157. BABYLON.Tools.Error("Sound creation aborted.");
  67158. _this._scene.mainSoundTrack.RemoveSound(_this);
  67159. });
  67160. }
  67161. // Streaming sound using HTML5 Audio tag
  67162. else {
  67163. this._htmlAudioElement = new Audio(url);
  67164. this._htmlAudioElement.controls = false;
  67165. this._htmlAudioElement.loop = this.loop;
  67166. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  67167. this._htmlAudioElement.preload = "auto";
  67168. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  67169. _this._isReadyToPlay = true;
  67170. if (_this.autoplay) {
  67171. _this.play();
  67172. }
  67173. if (_this._readyToPlayCallback) {
  67174. _this._readyToPlayCallback();
  67175. }
  67176. });
  67177. document.body.appendChild(this._htmlAudioElement);
  67178. }
  67179. break;
  67180. }
  67181. }
  67182. break;
  67183. default:
  67184. validParameter = false;
  67185. break;
  67186. }
  67187. if (!validParameter) {
  67188. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  67189. }
  67190. else {
  67191. if (!codecSupportedFound) {
  67192. this._isReadyToPlay = true;
  67193. // Simulating a ready to play event to avoid breaking code path
  67194. if (this._readyToPlayCallback) {
  67195. window.setTimeout(function () {
  67196. if (_this._readyToPlayCallback) {
  67197. _this._readyToPlayCallback();
  67198. }
  67199. }, 1000);
  67200. }
  67201. }
  67202. }
  67203. }
  67204. catch (ex) {
  67205. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  67206. this._scene.mainSoundTrack.RemoveSound(this);
  67207. }
  67208. }
  67209. }
  67210. else {
  67211. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  67212. this._scene.mainSoundTrack.AddSound(this);
  67213. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  67214. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  67215. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  67216. }
  67217. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  67218. if (this._readyToPlayCallback) {
  67219. window.setTimeout(function () {
  67220. if (_this._readyToPlayCallback) {
  67221. _this._readyToPlayCallback();
  67222. }
  67223. }, 1000);
  67224. }
  67225. }
  67226. }
  67227. Sound.prototype.dispose = function () {
  67228. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67229. if (this.isPlaying) {
  67230. this.stop();
  67231. }
  67232. this._isReadyToPlay = false;
  67233. if (this.soundTrackId === -1) {
  67234. this._scene.mainSoundTrack.RemoveSound(this);
  67235. }
  67236. else if (this._scene.soundTracks) {
  67237. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  67238. }
  67239. if (this._soundGain) {
  67240. this._soundGain.disconnect();
  67241. this._soundGain = null;
  67242. }
  67243. if (this._soundPanner) {
  67244. this._soundPanner.disconnect();
  67245. this._soundPanner = null;
  67246. }
  67247. if (this._soundSource) {
  67248. this._soundSource.disconnect();
  67249. this._soundSource = null;
  67250. }
  67251. this._audioBuffer = null;
  67252. if (this._htmlAudioElement) {
  67253. this._htmlAudioElement.pause();
  67254. this._htmlAudioElement.src = "";
  67255. document.body.removeChild(this._htmlAudioElement);
  67256. }
  67257. if (this._streamingSource) {
  67258. this._streamingSource.disconnect();
  67259. }
  67260. if (this._connectedMesh && this._registerFunc) {
  67261. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67262. this._connectedMesh = null;
  67263. }
  67264. }
  67265. };
  67266. Sound.prototype.isReady = function () {
  67267. return this._isReadyToPlay;
  67268. };
  67269. Sound.prototype._soundLoaded = function (audioData) {
  67270. var _this = this;
  67271. if (!BABYLON.Engine.audioEngine.audioContext) {
  67272. return;
  67273. }
  67274. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  67275. _this._audioBuffer = buffer;
  67276. _this._isReadyToPlay = true;
  67277. if (_this.autoplay) {
  67278. _this.play();
  67279. }
  67280. if (_this._readyToPlayCallback) {
  67281. _this._readyToPlayCallback();
  67282. }
  67283. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  67284. };
  67285. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  67286. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67287. this._audioBuffer = audioBuffer;
  67288. this._isReadyToPlay = true;
  67289. }
  67290. };
  67291. Sound.prototype.updateOptions = function (options) {
  67292. if (options) {
  67293. this.loop = options.loop || this.loop;
  67294. this.maxDistance = options.maxDistance || this.maxDistance;
  67295. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  67296. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  67297. this.refDistance = options.refDistance || this.refDistance;
  67298. this.distanceModel = options.distanceModel || this.distanceModel;
  67299. this._playbackRate = options.playbackRate || this._playbackRate;
  67300. this._updateSpatialParameters();
  67301. if (this.isPlaying) {
  67302. if (this._streaming && this._htmlAudioElement) {
  67303. this._htmlAudioElement.playbackRate = this._playbackRate;
  67304. }
  67305. else {
  67306. if (this._soundSource) {
  67307. this._soundSource.playbackRate.value = this._playbackRate;
  67308. }
  67309. }
  67310. }
  67311. }
  67312. };
  67313. Sound.prototype._createSpatialParameters = function () {
  67314. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67315. if (this._scene.headphone) {
  67316. this._panningModel = "HRTF";
  67317. }
  67318. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  67319. this._updateSpatialParameters();
  67320. this._soundPanner.connect(this._outputAudioNode);
  67321. this._inputAudioNode = this._soundPanner;
  67322. }
  67323. };
  67324. Sound.prototype._updateSpatialParameters = function () {
  67325. if (this.spatialSound && this._soundPanner) {
  67326. if (this.useCustomAttenuation) {
  67327. // Tricks to disable in a way embedded Web Audio attenuation
  67328. this._soundPanner.distanceModel = "linear";
  67329. this._soundPanner.maxDistance = Number.MAX_VALUE;
  67330. this._soundPanner.refDistance = 1;
  67331. this._soundPanner.rolloffFactor = 1;
  67332. this._soundPanner.panningModel = this._panningModel;
  67333. }
  67334. else {
  67335. this._soundPanner.distanceModel = this.distanceModel;
  67336. this._soundPanner.maxDistance = this.maxDistance;
  67337. this._soundPanner.refDistance = this.refDistance;
  67338. this._soundPanner.rolloffFactor = this.rolloffFactor;
  67339. this._soundPanner.panningModel = this._panningModel;
  67340. }
  67341. }
  67342. };
  67343. Sound.prototype.switchPanningModelToHRTF = function () {
  67344. this._panningModel = "HRTF";
  67345. this._switchPanningModel();
  67346. };
  67347. Sound.prototype.switchPanningModelToEqualPower = function () {
  67348. this._panningModel = "equalpower";
  67349. this._switchPanningModel();
  67350. };
  67351. Sound.prototype._switchPanningModel = function () {
  67352. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67353. this._soundPanner.panningModel = this._panningModel;
  67354. }
  67355. };
  67356. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  67357. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67358. if (this._isOutputConnected) {
  67359. this._outputAudioNode.disconnect();
  67360. }
  67361. this._outputAudioNode.connect(soundTrackAudioNode);
  67362. this._isOutputConnected = true;
  67363. }
  67364. };
  67365. /**
  67366. * Transform this sound into a directional source
  67367. * @param coneInnerAngle Size of the inner cone in degree
  67368. * @param coneOuterAngle Size of the outer cone in degree
  67369. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  67370. */
  67371. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  67372. if (coneOuterAngle < coneInnerAngle) {
  67373. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  67374. return;
  67375. }
  67376. this._coneInnerAngle = coneInnerAngle;
  67377. this._coneOuterAngle = coneOuterAngle;
  67378. this._coneOuterGain = coneOuterGain;
  67379. this._isDirectional = true;
  67380. if (this.isPlaying && this.loop) {
  67381. this.stop();
  67382. this.play();
  67383. }
  67384. };
  67385. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  67386. /**
  67387. * Gets or sets the inner angle for the directional cone.
  67388. */
  67389. get: function () {
  67390. return this._coneInnerAngle;
  67391. },
  67392. /**
  67393. * Gets or sets the inner angle for the directional cone.
  67394. */
  67395. set: function (value) {
  67396. if (value != this._coneInnerAngle) {
  67397. if (this._coneOuterAngle < value) {
  67398. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67399. return;
  67400. }
  67401. this._coneInnerAngle = value;
  67402. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67403. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67404. }
  67405. }
  67406. },
  67407. enumerable: true,
  67408. configurable: true
  67409. });
  67410. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  67411. /**
  67412. * Gets or sets the outer angle for the directional cone.
  67413. */
  67414. get: function () {
  67415. return this._coneOuterAngle;
  67416. },
  67417. /**
  67418. * Gets or sets the outer angle for the directional cone.
  67419. */
  67420. set: function (value) {
  67421. if (value != this._coneOuterAngle) {
  67422. if (value < this._coneInnerAngle) {
  67423. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  67424. return;
  67425. }
  67426. this._coneOuterAngle = value;
  67427. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  67428. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67429. }
  67430. }
  67431. },
  67432. enumerable: true,
  67433. configurable: true
  67434. });
  67435. Sound.prototype.setPosition = function (newPosition) {
  67436. this._position = newPosition;
  67437. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67438. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67439. }
  67440. };
  67441. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  67442. this._localDirection = newLocalDirection;
  67443. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  67444. this._updateDirection();
  67445. }
  67446. };
  67447. Sound.prototype._updateDirection = function () {
  67448. if (!this._connectedMesh || !this._soundPanner) {
  67449. return;
  67450. }
  67451. var mat = this._connectedMesh.getWorldMatrix();
  67452. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  67453. direction.normalize();
  67454. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  67455. };
  67456. Sound.prototype.updateDistanceFromListener = function () {
  67457. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  67458. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  67459. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  67460. }
  67461. };
  67462. Sound.prototype.setAttenuationFunction = function (callback) {
  67463. this._customAttenuationFunction = callback;
  67464. };
  67465. /**
  67466. * Play the sound
  67467. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  67468. * @param offset (optional) Start the sound setting it at a specific time
  67469. */
  67470. Sound.prototype.play = function (time, offset) {
  67471. var _this = this;
  67472. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  67473. try {
  67474. if (this._startOffset < 0) {
  67475. time = -this._startOffset;
  67476. this._startOffset = 0;
  67477. }
  67478. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67479. if (!this._soundSource || !this._streamingSource) {
  67480. if (this.spatialSound && this._soundPanner) {
  67481. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  67482. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  67483. }
  67484. if (this._isDirectional) {
  67485. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  67486. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  67487. this._soundPanner.coneOuterGain = this._coneOuterGain;
  67488. if (this._connectedMesh) {
  67489. this._updateDirection();
  67490. }
  67491. else {
  67492. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  67493. }
  67494. }
  67495. }
  67496. }
  67497. if (this._streaming) {
  67498. if (!this._streamingSource) {
  67499. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  67500. this._htmlAudioElement.onended = function () { _this._onended(); };
  67501. this._htmlAudioElement.playbackRate = this._playbackRate;
  67502. }
  67503. this._streamingSource.disconnect();
  67504. this._streamingSource.connect(this._inputAudioNode);
  67505. if (this._htmlAudioElement) {
  67506. // required to manage properly the new suspended default state of Chrome
  67507. // When the option 'streaming: true' is used, we need first to wait for
  67508. // the audio engine to be unlocked by a user gesture before trying to play
  67509. // an HTML Audio elememt
  67510. var tryToPlay = function () {
  67511. if (BABYLON.Engine.audioEngine.unlocked) {
  67512. var playPromise = _this._htmlAudioElement.play();
  67513. // In browsers that don’t yet support this functionality,
  67514. // playPromise won’t be defined.
  67515. if (playPromise !== undefined) {
  67516. playPromise.catch(function (error) {
  67517. // Automatic playback failed.
  67518. // Waiting for the audio engine to be unlocked by user click on unmute
  67519. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { return tryToPlay; });
  67520. });
  67521. }
  67522. }
  67523. else {
  67524. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { return tryToPlay; });
  67525. }
  67526. };
  67527. tryToPlay();
  67528. }
  67529. }
  67530. else {
  67531. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  67532. this._soundSource.buffer = this._audioBuffer;
  67533. this._soundSource.connect(this._inputAudioNode);
  67534. this._soundSource.loop = this.loop;
  67535. this._soundSource.playbackRate.value = this._playbackRate;
  67536. this._soundSource.onended = function () { _this._onended(); };
  67537. if (this._soundSource.buffer) {
  67538. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  67539. }
  67540. }
  67541. this._startTime = startTime;
  67542. this.isPlaying = true;
  67543. this.isPaused = false;
  67544. }
  67545. catch (ex) {
  67546. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  67547. }
  67548. }
  67549. };
  67550. Sound.prototype._onended = function () {
  67551. this.isPlaying = false;
  67552. if (this.onended) {
  67553. this.onended();
  67554. }
  67555. this.onEndedObservable.notifyObservers(this);
  67556. };
  67557. /**
  67558. * Stop the sound
  67559. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  67560. */
  67561. Sound.prototype.stop = function (time) {
  67562. if (this.isPlaying) {
  67563. if (this._streaming) {
  67564. if (this._htmlAudioElement) {
  67565. this._htmlAudioElement.pause();
  67566. // Test needed for Firefox or it will generate an Invalid State Error
  67567. if (this._htmlAudioElement.currentTime > 0) {
  67568. this._htmlAudioElement.currentTime = 0;
  67569. }
  67570. }
  67571. else {
  67572. this._streamingSource.disconnect();
  67573. }
  67574. }
  67575. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  67576. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  67577. this._soundSource.stop(stopTime);
  67578. this._soundSource.onended = function () { };
  67579. if (!this.isPaused) {
  67580. this._startOffset = 0;
  67581. }
  67582. }
  67583. this.isPlaying = false;
  67584. }
  67585. };
  67586. Sound.prototype.pause = function () {
  67587. if (this.isPlaying) {
  67588. this.isPaused = true;
  67589. if (this._streaming) {
  67590. if (this._htmlAudioElement) {
  67591. this._htmlAudioElement.pause();
  67592. }
  67593. else {
  67594. this._streamingSource.disconnect();
  67595. }
  67596. }
  67597. else if (BABYLON.Engine.audioEngine.audioContext) {
  67598. this.stop(0);
  67599. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  67600. }
  67601. }
  67602. };
  67603. Sound.prototype.setVolume = function (newVolume, time) {
  67604. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  67605. if (time && BABYLON.Engine.audioEngine.audioContext) {
  67606. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  67607. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  67608. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  67609. }
  67610. else {
  67611. this._soundGain.gain.value = newVolume;
  67612. }
  67613. }
  67614. this._volume = newVolume;
  67615. };
  67616. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  67617. this._playbackRate = newPlaybackRate;
  67618. if (this.isPlaying) {
  67619. if (this._streaming && this._htmlAudioElement) {
  67620. this._htmlAudioElement.playbackRate = this._playbackRate;
  67621. }
  67622. else if (this._soundSource) {
  67623. this._soundSource.playbackRate.value = this._playbackRate;
  67624. }
  67625. }
  67626. };
  67627. Sound.prototype.getVolume = function () {
  67628. return this._volume;
  67629. };
  67630. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  67631. var _this = this;
  67632. if (this._connectedMesh && this._registerFunc) {
  67633. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67634. this._registerFunc = null;
  67635. }
  67636. this._connectedMesh = meshToConnectTo;
  67637. if (!this.spatialSound) {
  67638. this.spatialSound = true;
  67639. this._createSpatialParameters();
  67640. if (this.isPlaying && this.loop) {
  67641. this.stop();
  67642. this.play();
  67643. }
  67644. }
  67645. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  67646. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  67647. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  67648. };
  67649. Sound.prototype.detachFromMesh = function () {
  67650. if (this._connectedMesh && this._registerFunc) {
  67651. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  67652. this._registerFunc = null;
  67653. this._connectedMesh = null;
  67654. }
  67655. };
  67656. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  67657. if (!node.getBoundingInfo) {
  67658. return;
  67659. }
  67660. var mesh = node;
  67661. if (this._positionInEmitterSpace) {
  67662. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  67663. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  67664. }
  67665. else {
  67666. var boundingInfo = mesh.getBoundingInfo();
  67667. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  67668. }
  67669. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  67670. this._updateDirection();
  67671. }
  67672. };
  67673. Sound.prototype.clone = function () {
  67674. var _this = this;
  67675. if (!this._streaming) {
  67676. var setBufferAndRun = function () {
  67677. if (_this._isReadyToPlay) {
  67678. clonedSound._audioBuffer = _this.getAudioBuffer();
  67679. clonedSound._isReadyToPlay = true;
  67680. if (clonedSound.autoplay) {
  67681. clonedSound.play();
  67682. }
  67683. }
  67684. else {
  67685. window.setTimeout(setBufferAndRun, 300);
  67686. }
  67687. };
  67688. var currentOptions = {
  67689. autoplay: this.autoplay, loop: this.loop,
  67690. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  67691. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  67692. refDistance: this.refDistance, distanceModel: this.distanceModel
  67693. };
  67694. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  67695. if (this.useCustomAttenuation) {
  67696. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  67697. }
  67698. clonedSound.setPosition(this._position);
  67699. clonedSound.setPlaybackRate(this._playbackRate);
  67700. setBufferAndRun();
  67701. return clonedSound;
  67702. }
  67703. // Can't clone a streaming sound
  67704. else {
  67705. return null;
  67706. }
  67707. };
  67708. Sound.prototype.getAudioBuffer = function () {
  67709. return this._audioBuffer;
  67710. };
  67711. Sound.prototype.serialize = function () {
  67712. var serializationObject = {
  67713. name: this.name,
  67714. url: this.name,
  67715. autoplay: this.autoplay,
  67716. loop: this.loop,
  67717. volume: this._volume,
  67718. spatialSound: this.spatialSound,
  67719. maxDistance: this.maxDistance,
  67720. rolloffFactor: this.rolloffFactor,
  67721. refDistance: this.refDistance,
  67722. distanceModel: this.distanceModel,
  67723. playbackRate: this._playbackRate,
  67724. panningModel: this._panningModel,
  67725. soundTrackId: this.soundTrackId
  67726. };
  67727. if (this.spatialSound) {
  67728. if (this._connectedMesh)
  67729. serializationObject.connectedMeshId = this._connectedMesh.id;
  67730. serializationObject.position = this._position.asArray();
  67731. serializationObject.refDistance = this.refDistance;
  67732. serializationObject.distanceModel = this.distanceModel;
  67733. serializationObject.isDirectional = this._isDirectional;
  67734. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  67735. serializationObject.coneInnerAngle = this._coneInnerAngle;
  67736. serializationObject.coneOuterAngle = this._coneOuterAngle;
  67737. serializationObject.coneOuterGain = this._coneOuterGain;
  67738. }
  67739. return serializationObject;
  67740. };
  67741. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  67742. var soundName = parsedSound.name;
  67743. var soundUrl;
  67744. if (parsedSound.url) {
  67745. soundUrl = rootUrl + parsedSound.url;
  67746. }
  67747. else {
  67748. soundUrl = rootUrl + soundName;
  67749. }
  67750. var options = {
  67751. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  67752. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  67753. rolloffFactor: parsedSound.rolloffFactor,
  67754. refDistance: parsedSound.refDistance,
  67755. distanceModel: parsedSound.distanceModel,
  67756. playbackRate: parsedSound.playbackRate
  67757. };
  67758. var newSound;
  67759. if (!sourceSound) {
  67760. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  67761. scene._addPendingData(newSound);
  67762. }
  67763. else {
  67764. var setBufferAndRun = function () {
  67765. if (sourceSound._isReadyToPlay) {
  67766. newSound._audioBuffer = sourceSound.getAudioBuffer();
  67767. newSound._isReadyToPlay = true;
  67768. if (newSound.autoplay) {
  67769. newSound.play();
  67770. }
  67771. }
  67772. else {
  67773. window.setTimeout(setBufferAndRun, 300);
  67774. }
  67775. };
  67776. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  67777. setBufferAndRun();
  67778. }
  67779. if (parsedSound.position) {
  67780. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  67781. newSound.setPosition(soundPosition);
  67782. }
  67783. if (parsedSound.isDirectional) {
  67784. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  67785. if (parsedSound.localDirectionToMesh) {
  67786. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  67787. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  67788. }
  67789. }
  67790. if (parsedSound.connectedMeshId) {
  67791. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  67792. if (connectedMesh) {
  67793. newSound.attachToMesh(connectedMesh);
  67794. }
  67795. }
  67796. return newSound;
  67797. };
  67798. return Sound;
  67799. }());
  67800. BABYLON.Sound = Sound;
  67801. })(BABYLON || (BABYLON = {}));
  67802. //# sourceMappingURL=babylon.sound.js.map
  67803. var BABYLON;
  67804. (function (BABYLON) {
  67805. var SoundTrack = /** @class */ (function () {
  67806. function SoundTrack(scene, options) {
  67807. this.id = -1;
  67808. this._isMainTrack = false;
  67809. this._isInitialized = false;
  67810. this._scene = scene;
  67811. this.soundCollection = new Array();
  67812. this._options = options;
  67813. if (!this._isMainTrack && this._scene.soundTracks) {
  67814. this._scene.soundTracks.push(this);
  67815. this.id = this._scene.soundTracks.length - 1;
  67816. }
  67817. }
  67818. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  67819. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  67820. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  67821. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  67822. if (this._options) {
  67823. if (this._options.volume) {
  67824. this._outputAudioNode.gain.value = this._options.volume;
  67825. }
  67826. if (this._options.mainTrack) {
  67827. this._isMainTrack = this._options.mainTrack;
  67828. }
  67829. }
  67830. this._isInitialized = true;
  67831. }
  67832. };
  67833. SoundTrack.prototype.dispose = function () {
  67834. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  67835. if (this._connectedAnalyser) {
  67836. this._connectedAnalyser.stopDebugCanvas();
  67837. }
  67838. while (this.soundCollection.length) {
  67839. this.soundCollection[0].dispose();
  67840. }
  67841. if (this._outputAudioNode) {
  67842. this._outputAudioNode.disconnect();
  67843. }
  67844. this._outputAudioNode = null;
  67845. }
  67846. };
  67847. SoundTrack.prototype.AddSound = function (sound) {
  67848. if (!this._isInitialized) {
  67849. this._initializeSoundTrackAudioGraph();
  67850. }
  67851. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  67852. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  67853. }
  67854. if (sound.soundTrackId) {
  67855. if (sound.soundTrackId === -1) {
  67856. this._scene.mainSoundTrack.RemoveSound(sound);
  67857. }
  67858. else if (this._scene.soundTracks) {
  67859. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  67860. }
  67861. }
  67862. this.soundCollection.push(sound);
  67863. sound.soundTrackId = this.id;
  67864. };
  67865. SoundTrack.prototype.RemoveSound = function (sound) {
  67866. var index = this.soundCollection.indexOf(sound);
  67867. if (index !== -1) {
  67868. this.soundCollection.splice(index, 1);
  67869. }
  67870. };
  67871. SoundTrack.prototype.setVolume = function (newVolume) {
  67872. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  67873. this._outputAudioNode.gain.value = newVolume;
  67874. }
  67875. };
  67876. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  67877. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67878. for (var i = 0; i < this.soundCollection.length; i++) {
  67879. this.soundCollection[i].switchPanningModelToHRTF();
  67880. }
  67881. }
  67882. };
  67883. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  67884. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67885. for (var i = 0; i < this.soundCollection.length; i++) {
  67886. this.soundCollection[i].switchPanningModelToEqualPower();
  67887. }
  67888. }
  67889. };
  67890. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  67891. if (this._connectedAnalyser) {
  67892. this._connectedAnalyser.stopDebugCanvas();
  67893. }
  67894. this._connectedAnalyser = analyser;
  67895. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  67896. this._outputAudioNode.disconnect();
  67897. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  67898. }
  67899. };
  67900. return SoundTrack;
  67901. }());
  67902. BABYLON.SoundTrack = SoundTrack;
  67903. })(BABYLON || (BABYLON = {}));
  67904. //# sourceMappingURL=babylon.soundtrack.js.map
  67905. var BABYLON;
  67906. (function (BABYLON) {
  67907. /**
  67908. * Class used to work with sound analyzer using fast fourier transform (FFT)
  67909. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  67910. */
  67911. var Analyser = /** @class */ (function () {
  67912. /**
  67913. * Creates a new analyser
  67914. * @param scene defines hosting scene
  67915. */
  67916. function Analyser(scene) {
  67917. /**
  67918. * Gets or sets the smoothing
  67919. * @ignorenaming
  67920. */
  67921. this.SMOOTHING = 0.75;
  67922. /**
  67923. * Gets or sets the FFT table size
  67924. * @ignorenaming
  67925. */
  67926. this.FFT_SIZE = 512;
  67927. /**
  67928. * Gets or sets the bar graph amplitude
  67929. * @ignorenaming
  67930. */
  67931. this.BARGRAPHAMPLITUDE = 256;
  67932. /**
  67933. * Gets or sets the position of the debug canvas
  67934. * @ignorenaming
  67935. */
  67936. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  67937. /**
  67938. * Gets or sets the debug canvas size
  67939. * @ignorenaming
  67940. */
  67941. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  67942. this._scene = scene;
  67943. this._audioEngine = BABYLON.Engine.audioEngine;
  67944. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  67945. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  67946. this._webAudioAnalyser.minDecibels = -140;
  67947. this._webAudioAnalyser.maxDecibels = 0;
  67948. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  67949. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  67950. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  67951. }
  67952. }
  67953. /**
  67954. * Get the number of data values you will have to play with for the visualization
  67955. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  67956. * @returns a number
  67957. */
  67958. Analyser.prototype.getFrequencyBinCount = function () {
  67959. if (this._audioEngine.canUseWebAudio) {
  67960. return this._webAudioAnalyser.frequencyBinCount;
  67961. }
  67962. else {
  67963. return 0;
  67964. }
  67965. };
  67966. /**
  67967. * Gets the current frequency data as a byte array
  67968. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  67969. * @returns a Uint8Array
  67970. */
  67971. Analyser.prototype.getByteFrequencyData = function () {
  67972. if (this._audioEngine.canUseWebAudio) {
  67973. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  67974. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  67975. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  67976. }
  67977. return this._byteFreqs;
  67978. };
  67979. /**
  67980. * Gets the current waveform as a byte array
  67981. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  67982. * @returns a Uint8Array
  67983. */
  67984. Analyser.prototype.getByteTimeDomainData = function () {
  67985. if (this._audioEngine.canUseWebAudio) {
  67986. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  67987. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  67988. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  67989. }
  67990. return this._byteTime;
  67991. };
  67992. /**
  67993. * Gets the current frequency data as a float array
  67994. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  67995. * @returns a Float32Array
  67996. */
  67997. Analyser.prototype.getFloatFrequencyData = function () {
  67998. if (this._audioEngine.canUseWebAudio) {
  67999. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  68000. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  68001. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  68002. }
  68003. return this._floatFreqs;
  68004. };
  68005. /**
  68006. * Renders the debug canvas
  68007. */
  68008. Analyser.prototype.drawDebugCanvas = function () {
  68009. var _this = this;
  68010. if (this._audioEngine.canUseWebAudio) {
  68011. if (!this._debugCanvas) {
  68012. this._debugCanvas = document.createElement("canvas");
  68013. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  68014. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  68015. this._debugCanvas.style.position = "absolute";
  68016. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  68017. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  68018. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  68019. document.body.appendChild(this._debugCanvas);
  68020. this._registerFunc = function () {
  68021. _this.drawDebugCanvas();
  68022. };
  68023. this._scene.registerBeforeRender(this._registerFunc);
  68024. }
  68025. if (this._registerFunc && this._debugCanvasContext) {
  68026. var workingArray = this.getByteFrequencyData();
  68027. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  68028. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  68029. // Draw the frequency domain chart.
  68030. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  68031. var value = workingArray[i];
  68032. var percent = value / this.BARGRAPHAMPLITUDE;
  68033. var height = this.DEBUGCANVASSIZE.height * percent;
  68034. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  68035. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  68036. var hue = i / this.getFrequencyBinCount() * 360;
  68037. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  68038. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  68039. }
  68040. }
  68041. }
  68042. };
  68043. /**
  68044. * Stops rendering the debug canvas and removes it
  68045. */
  68046. Analyser.prototype.stopDebugCanvas = function () {
  68047. if (this._debugCanvas) {
  68048. if (this._registerFunc) {
  68049. this._scene.unregisterBeforeRender(this._registerFunc);
  68050. this._registerFunc = null;
  68051. }
  68052. document.body.removeChild(this._debugCanvas);
  68053. this._debugCanvas = null;
  68054. this._debugCanvasContext = null;
  68055. }
  68056. };
  68057. /**
  68058. * Connects two audio nodes
  68059. * @param inputAudioNode defines first node to connect
  68060. * @param outputAudioNode defines second node to connect
  68061. */
  68062. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  68063. if (this._audioEngine.canUseWebAudio) {
  68064. inputAudioNode.connect(this._webAudioAnalyser);
  68065. this._webAudioAnalyser.connect(outputAudioNode);
  68066. }
  68067. };
  68068. /**
  68069. * Releases all associated resources
  68070. */
  68071. Analyser.prototype.dispose = function () {
  68072. if (this._audioEngine.canUseWebAudio) {
  68073. this._webAudioAnalyser.disconnect();
  68074. }
  68075. };
  68076. return Analyser;
  68077. }());
  68078. BABYLON.Analyser = Analyser;
  68079. })(BABYLON || (BABYLON = {}));
  68080. //# sourceMappingURL=babylon.analyser.js.map
  68081. var BABYLON;
  68082. (function (BABYLON) {
  68083. /**
  68084. * Wraps one or more Sound objects and selects one with random weight for playback.
  68085. */
  68086. var WeightedSound = /** @class */ (function () {
  68087. /**
  68088. * Creates a new WeightedSound from the list of sounds given.
  68089. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  68090. * @param sounds Array of Sounds that will be selected from.
  68091. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  68092. */
  68093. function WeightedSound(loop, sounds, weights) {
  68094. var _this = this;
  68095. /** When true a Sound will be selected and played when the current playing Sound completes. */
  68096. this.loop = false;
  68097. this._coneInnerAngle = 360;
  68098. this._coneOuterAngle = 360;
  68099. this._volume = 1;
  68100. /** A Sound is currently playing. */
  68101. this.isPlaying = false;
  68102. /** A Sound is currently paused. */
  68103. this.isPaused = false;
  68104. this._sounds = [];
  68105. this._weights = [];
  68106. if (sounds.length !== weights.length) {
  68107. throw new Error('Sounds length does not equal weights length');
  68108. }
  68109. this.loop = loop;
  68110. this._weights = weights;
  68111. // Normalize the weights
  68112. var weightSum = 0;
  68113. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  68114. var weight = weights_1[_i];
  68115. weightSum += weight;
  68116. }
  68117. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  68118. for (var i = 0; i < this._weights.length; i++) {
  68119. this._weights[i] *= invWeightSum;
  68120. }
  68121. this._sounds = sounds;
  68122. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  68123. var sound = _b[_a];
  68124. sound.onEndedObservable.add(function () { _this._onended(); });
  68125. }
  68126. }
  68127. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  68128. /**
  68129. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  68130. */
  68131. get: function () {
  68132. return this._coneInnerAngle;
  68133. },
  68134. /**
  68135. * The size of cone in degress for a directional sound in which there will be no attenuation.
  68136. */
  68137. set: function (value) {
  68138. if (value !== this._coneInnerAngle) {
  68139. if (this._coneOuterAngle < value) {
  68140. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68141. return;
  68142. }
  68143. this._coneInnerAngle = value;
  68144. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68145. var sound = _a[_i];
  68146. sound.directionalConeInnerAngle = value;
  68147. }
  68148. }
  68149. },
  68150. enumerable: true,
  68151. configurable: true
  68152. });
  68153. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  68154. /**
  68155. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68156. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68157. */
  68158. get: function () {
  68159. return this._coneOuterAngle;
  68160. },
  68161. /**
  68162. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  68163. * Listener angles between innerAngle and outerAngle will falloff linearly.
  68164. */
  68165. set: function (value) {
  68166. if (value !== this._coneOuterAngle) {
  68167. if (value < this._coneInnerAngle) {
  68168. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  68169. return;
  68170. }
  68171. this._coneOuterAngle = value;
  68172. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68173. var sound = _a[_i];
  68174. sound.directionalConeOuterAngle = value;
  68175. }
  68176. }
  68177. },
  68178. enumerable: true,
  68179. configurable: true
  68180. });
  68181. Object.defineProperty(WeightedSound.prototype, "volume", {
  68182. /**
  68183. * Playback volume.
  68184. */
  68185. get: function () {
  68186. return this._volume;
  68187. },
  68188. /**
  68189. * Playback volume.
  68190. */
  68191. set: function (value) {
  68192. if (value !== this._volume) {
  68193. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  68194. var sound = _a[_i];
  68195. sound.setVolume(value);
  68196. }
  68197. }
  68198. },
  68199. enumerable: true,
  68200. configurable: true
  68201. });
  68202. WeightedSound.prototype._onended = function () {
  68203. if (this._currentIndex !== undefined) {
  68204. this._sounds[this._currentIndex].autoplay = false;
  68205. }
  68206. if (this.loop && this.isPlaying) {
  68207. this.play();
  68208. }
  68209. else {
  68210. this.isPlaying = false;
  68211. }
  68212. };
  68213. /**
  68214. * Suspend playback
  68215. */
  68216. WeightedSound.prototype.pause = function () {
  68217. this.isPaused = true;
  68218. if (this._currentIndex !== undefined) {
  68219. this._sounds[this._currentIndex].pause();
  68220. }
  68221. };
  68222. /**
  68223. * Stop playback
  68224. */
  68225. WeightedSound.prototype.stop = function () {
  68226. this.isPlaying = false;
  68227. if (this._currentIndex !== undefined) {
  68228. this._sounds[this._currentIndex].stop();
  68229. }
  68230. };
  68231. /**
  68232. * Start playback.
  68233. * @param startOffset Position the clip head at a specific time in seconds.
  68234. */
  68235. WeightedSound.prototype.play = function (startOffset) {
  68236. if (!this.isPaused) {
  68237. this.stop();
  68238. var randomValue = Math.random();
  68239. var total = 0;
  68240. for (var i = 0; i < this._weights.length; i++) {
  68241. total += this._weights[i];
  68242. if (randomValue <= total) {
  68243. this._currentIndex = i;
  68244. break;
  68245. }
  68246. }
  68247. }
  68248. var sound = this._sounds[this._currentIndex];
  68249. if (sound.isReady()) {
  68250. sound.play(0, this.isPaused ? undefined : startOffset);
  68251. }
  68252. else {
  68253. sound.autoplay = true;
  68254. }
  68255. this.isPlaying = true;
  68256. this.isPaused = false;
  68257. };
  68258. return WeightedSound;
  68259. }());
  68260. BABYLON.WeightedSound = WeightedSound;
  68261. })(BABYLON || (BABYLON = {}));
  68262. //# sourceMappingURL=babylon.weightedsound.js.map
  68263. var BABYLON;
  68264. (function (BABYLON) {
  68265. // Adds the parser to the scene parsers.
  68266. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  68267. // TODO: add sound
  68268. var loadedSounds = [];
  68269. var loadedSound;
  68270. container.sounds = container.sounds || [];
  68271. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68272. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68273. var parsedSound = parsedData.sounds[index];
  68274. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68275. if (!parsedSound.url)
  68276. parsedSound.url = parsedSound.name;
  68277. if (!loadedSounds[parsedSound.url]) {
  68278. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68279. loadedSounds[parsedSound.url] = loadedSound;
  68280. container.sounds.push(loadedSound);
  68281. }
  68282. else {
  68283. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68284. }
  68285. }
  68286. else {
  68287. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68288. }
  68289. }
  68290. }
  68291. loadedSounds = [];
  68292. });
  68293. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  68294. get: function () {
  68295. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68296. if (!compo) {
  68297. compo = new AudioSceneComponent(this);
  68298. this._addComponent(compo);
  68299. }
  68300. if (!this._mainSoundTrack) {
  68301. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  68302. }
  68303. return this._mainSoundTrack;
  68304. },
  68305. enumerable: true,
  68306. configurable: true
  68307. });
  68308. BABYLON.Scene.prototype.getSoundByName = function (name) {
  68309. var index;
  68310. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  68311. if (this.mainSoundTrack.soundCollection[index].name === name) {
  68312. return this.mainSoundTrack.soundCollection[index];
  68313. }
  68314. }
  68315. if (this.soundTracks) {
  68316. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  68317. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  68318. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  68319. return this.soundTracks[sdIndex].soundCollection[index];
  68320. }
  68321. }
  68322. }
  68323. }
  68324. return null;
  68325. };
  68326. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  68327. get: function () {
  68328. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68329. if (!compo) {
  68330. compo = new AudioSceneComponent(this);
  68331. this._addComponent(compo);
  68332. }
  68333. return compo.audioEnabled;
  68334. },
  68335. set: function (value) {
  68336. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68337. if (!compo) {
  68338. compo = new AudioSceneComponent(this);
  68339. this._addComponent(compo);
  68340. }
  68341. if (value) {
  68342. compo.enableAudio();
  68343. }
  68344. else {
  68345. compo.disableAudio();
  68346. }
  68347. },
  68348. enumerable: true,
  68349. configurable: true
  68350. });
  68351. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  68352. get: function () {
  68353. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68354. if (!compo) {
  68355. compo = new AudioSceneComponent(this);
  68356. this._addComponent(compo);
  68357. }
  68358. return compo.headphone;
  68359. },
  68360. set: function (value) {
  68361. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  68362. if (!compo) {
  68363. compo = new AudioSceneComponent(this);
  68364. this._addComponent(compo);
  68365. }
  68366. if (value) {
  68367. compo.switchAudioModeForHeadphones();
  68368. }
  68369. else {
  68370. compo.switchAudioModeForNormalSpeakers();
  68371. }
  68372. },
  68373. enumerable: true,
  68374. configurable: true
  68375. });
  68376. /**
  68377. * Defines the sound scene component responsible to manage any sounds
  68378. * in a given scene.
  68379. */
  68380. var AudioSceneComponent = /** @class */ (function () {
  68381. /**
  68382. * Creates a new instance of the component for the given scene
  68383. * @param scene Defines the scene to register the component in
  68384. */
  68385. function AudioSceneComponent(scene) {
  68386. /**
  68387. * The component name helpfull to identify the component in the list of scene components.
  68388. */
  68389. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  68390. this._audioEnabled = true;
  68391. this._headphone = false;
  68392. this.scene = scene;
  68393. scene.soundTracks = new Array();
  68394. scene.sounds = new Array();
  68395. }
  68396. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  68397. /**
  68398. * Gets whether audio is enabled or not.
  68399. * Please use related enable/disable method to switch state.
  68400. */
  68401. get: function () {
  68402. return this._audioEnabled;
  68403. },
  68404. enumerable: true,
  68405. configurable: true
  68406. });
  68407. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  68408. /**
  68409. * Gets whether audio is outputing to headphone or not.
  68410. * Please use the according Switch methods to change output.
  68411. */
  68412. get: function () {
  68413. return this._headphone;
  68414. },
  68415. enumerable: true,
  68416. configurable: true
  68417. });
  68418. /**
  68419. * Registers the component in a given scene
  68420. */
  68421. AudioSceneComponent.prototype.register = function () {
  68422. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  68423. };
  68424. /**
  68425. * Rebuilds the elements related to this component in case of
  68426. * context lost for instance.
  68427. */
  68428. AudioSceneComponent.prototype.rebuild = function () {
  68429. // Nothing to do here. (Not rendering related)
  68430. };
  68431. /**
  68432. * Serializes the component data to the specified json object
  68433. * @param serializationObject The object to serialize to
  68434. */
  68435. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  68436. serializationObject.sounds = [];
  68437. if (this.scene.soundTracks) {
  68438. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  68439. var soundtrack = this.scene.soundTracks[index];
  68440. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  68441. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  68442. }
  68443. }
  68444. }
  68445. };
  68446. /**
  68447. * Adds all the element from the container to the scene
  68448. * @param container the container holding the elements
  68449. */
  68450. AudioSceneComponent.prototype.addFromContainer = function (container) {
  68451. var _this = this;
  68452. if (!container.sounds) {
  68453. return;
  68454. }
  68455. container.sounds.forEach(function (sound) {
  68456. sound.play();
  68457. sound.autoplay = true;
  68458. _this.scene.mainSoundTrack.AddSound(sound);
  68459. });
  68460. };
  68461. /**
  68462. * Removes all the elements in the container from the scene
  68463. * @param container contains the elements to remove
  68464. */
  68465. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  68466. var _this = this;
  68467. if (!container.sounds) {
  68468. return;
  68469. }
  68470. container.sounds.forEach(function (sound) {
  68471. sound.stop();
  68472. sound.autoplay = false;
  68473. _this.scene.mainSoundTrack.RemoveSound(sound);
  68474. });
  68475. };
  68476. /**
  68477. * Disposes the component and the associated ressources.
  68478. */
  68479. AudioSceneComponent.prototype.dispose = function () {
  68480. var scene = this.scene;
  68481. if (scene._mainSoundTrack) {
  68482. scene.mainSoundTrack.dispose();
  68483. }
  68484. if (scene.soundTracks) {
  68485. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  68486. scene.soundTracks[scIndex].dispose();
  68487. }
  68488. }
  68489. };
  68490. /**
  68491. * Disables audio in the associated scene.
  68492. */
  68493. AudioSceneComponent.prototype.disableAudio = function () {
  68494. var scene = this.scene;
  68495. this._audioEnabled = false;
  68496. var i;
  68497. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68498. scene.mainSoundTrack.soundCollection[i].pause();
  68499. }
  68500. if (scene.soundTracks) {
  68501. for (i = 0; i < scene.soundTracks.length; i++) {
  68502. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68503. scene.soundTracks[i].soundCollection[j].pause();
  68504. }
  68505. }
  68506. }
  68507. };
  68508. /**
  68509. * Enables audio in the associated scene.
  68510. */
  68511. AudioSceneComponent.prototype.enableAudio = function () {
  68512. var scene = this.scene;
  68513. this._audioEnabled = true;
  68514. var i;
  68515. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68516. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  68517. scene.mainSoundTrack.soundCollection[i].play();
  68518. }
  68519. }
  68520. if (scene.soundTracks) {
  68521. for (i = 0; i < scene.soundTracks.length; i++) {
  68522. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68523. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  68524. scene.soundTracks[i].soundCollection[j].play();
  68525. }
  68526. }
  68527. }
  68528. }
  68529. };
  68530. /**
  68531. * Switch audio to headphone output.
  68532. */
  68533. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  68534. var scene = this.scene;
  68535. this._headphone = true;
  68536. scene.mainSoundTrack.switchPanningModelToHRTF();
  68537. if (scene.soundTracks) {
  68538. for (var i = 0; i < scene.soundTracks.length; i++) {
  68539. scene.soundTracks[i].switchPanningModelToHRTF();
  68540. }
  68541. }
  68542. };
  68543. /**
  68544. * Switch audio to normal speakers.
  68545. */
  68546. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  68547. var scene = this.scene;
  68548. this._headphone = false;
  68549. scene.mainSoundTrack.switchPanningModelToEqualPower();
  68550. if (scene.soundTracks) {
  68551. for (var i = 0; i < scene.soundTracks.length; i++) {
  68552. scene.soundTracks[i].switchPanningModelToEqualPower();
  68553. }
  68554. }
  68555. };
  68556. AudioSceneComponent.prototype._afterRender = function () {
  68557. var scene = this.scene;
  68558. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  68559. return;
  68560. }
  68561. var listeningCamera;
  68562. var audioEngine = BABYLON.Engine.audioEngine;
  68563. if (scene.activeCameras.length > 0) {
  68564. listeningCamera = scene.activeCameras[0];
  68565. }
  68566. else {
  68567. listeningCamera = scene.activeCamera;
  68568. }
  68569. if (listeningCamera && audioEngine.audioContext) {
  68570. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  68571. // for VR cameras
  68572. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  68573. listeningCamera = listeningCamera.rigCameras[0];
  68574. }
  68575. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  68576. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  68577. cameraDirection.normalize();
  68578. // To avoid some errors on GearVR
  68579. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  68580. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  68581. }
  68582. var i;
  68583. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  68584. var sound = scene.mainSoundTrack.soundCollection[i];
  68585. if (sound.useCustomAttenuation) {
  68586. sound.updateDistanceFromListener();
  68587. }
  68588. }
  68589. if (scene.soundTracks) {
  68590. for (i = 0; i < scene.soundTracks.length; i++) {
  68591. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  68592. sound = scene.soundTracks[i].soundCollection[j];
  68593. if (sound.useCustomAttenuation) {
  68594. sound.updateDistanceFromListener();
  68595. }
  68596. }
  68597. }
  68598. }
  68599. }
  68600. };
  68601. return AudioSceneComponent;
  68602. }());
  68603. BABYLON.AudioSceneComponent = AudioSceneComponent;
  68604. })(BABYLON || (BABYLON = {}));
  68605. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  68606. var BABYLON;
  68607. (function (BABYLON) {
  68608. /**
  68609. * This defines an action helpful to play a defined sound on a triggered action.
  68610. */
  68611. var PlaySoundAction = /** @class */ (function (_super) {
  68612. __extends(PlaySoundAction, _super);
  68613. /**
  68614. * Instantiate the action
  68615. * @param triggerOptions defines the trigger options
  68616. * @param sound defines the sound to play
  68617. * @param condition defines the trigger related conditions
  68618. */
  68619. function PlaySoundAction(triggerOptions, sound, condition) {
  68620. var _this = _super.call(this, triggerOptions, condition) || this;
  68621. _this._sound = sound;
  68622. return _this;
  68623. }
  68624. /** @hidden */
  68625. PlaySoundAction.prototype._prepare = function () {
  68626. };
  68627. /**
  68628. * Execute the action and play the sound.
  68629. */
  68630. PlaySoundAction.prototype.execute = function () {
  68631. if (this._sound !== undefined)
  68632. this._sound.play();
  68633. };
  68634. /**
  68635. * Serializes the actions and its related information.
  68636. * @param parent defines the object to serialize in
  68637. * @returns the serialized object
  68638. */
  68639. PlaySoundAction.prototype.serialize = function (parent) {
  68640. return _super.prototype._serialize.call(this, {
  68641. name: "PlaySoundAction",
  68642. properties: [{ name: "sound", value: this._sound.name }]
  68643. }, parent);
  68644. };
  68645. return PlaySoundAction;
  68646. }(BABYLON.Action));
  68647. BABYLON.PlaySoundAction = PlaySoundAction;
  68648. /**
  68649. * This defines an action helpful to stop a defined sound on a triggered action.
  68650. */
  68651. var StopSoundAction = /** @class */ (function (_super) {
  68652. __extends(StopSoundAction, _super);
  68653. /**
  68654. * Instantiate the action
  68655. * @param triggerOptions defines the trigger options
  68656. * @param sound defines the sound to stop
  68657. * @param condition defines the trigger related conditions
  68658. */
  68659. function StopSoundAction(triggerOptions, sound, condition) {
  68660. var _this = _super.call(this, triggerOptions, condition) || this;
  68661. _this._sound = sound;
  68662. return _this;
  68663. }
  68664. /** @hidden */
  68665. StopSoundAction.prototype._prepare = function () {
  68666. };
  68667. /**
  68668. * Execute the action and stop the sound.
  68669. */
  68670. StopSoundAction.prototype.execute = function () {
  68671. if (this._sound !== undefined)
  68672. this._sound.stop();
  68673. };
  68674. /**
  68675. * Serializes the actions and its related information.
  68676. * @param parent defines the object to serialize in
  68677. * @returns the serialized object
  68678. */
  68679. StopSoundAction.prototype.serialize = function (parent) {
  68680. return _super.prototype._serialize.call(this, {
  68681. name: "StopSoundAction",
  68682. properties: [{ name: "sound", value: this._sound.name }]
  68683. }, parent);
  68684. };
  68685. return StopSoundAction;
  68686. }(BABYLON.Action));
  68687. BABYLON.StopSoundAction = StopSoundAction;
  68688. })(BABYLON || (BABYLON = {}));
  68689. //# sourceMappingURL=babylon.directAudioActions.js.map
  68690. var BABYLON;
  68691. (function (BABYLON) {
  68692. var CubeTexture = /** @class */ (function (_super) {
  68693. __extends(CubeTexture, _super);
  68694. /**
  68695. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  68696. * as prefiltered data.
  68697. * @param rootUrl defines the url of the texture or the root name of the six images
  68698. * @param scene defines the scene the texture is attached to
  68699. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  68700. * @param noMipmap defines if mipmaps should be created or not
  68701. * @param files defines the six files to load for the different faces
  68702. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  68703. * @param onError defines a callback triggered in case of error during load
  68704. * @param format defines the internal format to use for the texture once loaded
  68705. * @param prefiltered defines whether or not the texture is created from prefiltered data
  68706. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  68707. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  68708. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  68709. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  68710. * @return the cube texture
  68711. */
  68712. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  68713. if (extensions === void 0) { extensions = null; }
  68714. if (noMipmap === void 0) { noMipmap = false; }
  68715. if (files === void 0) { files = null; }
  68716. if (onLoad === void 0) { onLoad = null; }
  68717. if (onError === void 0) { onError = null; }
  68718. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68719. if (prefiltered === void 0) { prefiltered = false; }
  68720. if (forcedExtension === void 0) { forcedExtension = null; }
  68721. if (createPolynomials === void 0) { createPolynomials = false; }
  68722. if (lodScale === void 0) { lodScale = 0.8; }
  68723. if (lodOffset === void 0) { lodOffset = 0; }
  68724. var _this = _super.call(this, scene) || this;
  68725. /**
  68726. * Gets or sets the center of the bounding box associated with the cube texture
  68727. * It must define where the camera used to render the texture was set
  68728. */
  68729. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  68730. _this._rotationY = 0;
  68731. /** @hidden */
  68732. _this._prefiltered = false;
  68733. _this.name = rootUrl;
  68734. _this.url = rootUrl;
  68735. _this._noMipmap = noMipmap;
  68736. _this.hasAlpha = false;
  68737. _this._format = format;
  68738. _this.isCube = true;
  68739. _this._textureMatrix = BABYLON.Matrix.Identity();
  68740. _this._createPolynomials = createPolynomials;
  68741. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  68742. if (!rootUrl && !files) {
  68743. return _this;
  68744. }
  68745. var lastDot = rootUrl.lastIndexOf(".");
  68746. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  68747. var isDDS = (extension === ".dds");
  68748. var isEnv = (extension === ".env");
  68749. if (isEnv) {
  68750. _this.gammaSpace = false;
  68751. _this._prefiltered = false;
  68752. }
  68753. else {
  68754. _this._prefiltered = prefiltered;
  68755. if (prefiltered) {
  68756. _this.gammaSpace = false;
  68757. }
  68758. }
  68759. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  68760. if (!files) {
  68761. if (!isEnv && !isDDS && !extensions) {
  68762. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  68763. }
  68764. files = [];
  68765. if (extensions) {
  68766. for (var index = 0; index < extensions.length; index++) {
  68767. files.push(rootUrl + extensions[index]);
  68768. }
  68769. }
  68770. }
  68771. _this._files = files;
  68772. if (!_this._texture) {
  68773. if (!scene.useDelayedTextureLoading) {
  68774. if (prefiltered) {
  68775. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  68776. }
  68777. else {
  68778. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  68779. }
  68780. }
  68781. else {
  68782. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  68783. }
  68784. }
  68785. else if (onLoad) {
  68786. if (_this._texture.isReady) {
  68787. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  68788. }
  68789. else {
  68790. _this._texture.onLoadedObservable.add(onLoad);
  68791. }
  68792. }
  68793. return _this;
  68794. }
  68795. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  68796. get: function () {
  68797. return this._boundingBoxSize;
  68798. },
  68799. /**
  68800. * Gets or sets the size of the bounding box associated with the cube texture
  68801. * When defined, the cubemap will switch to local mode
  68802. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  68803. * @example https://www.babylonjs-playground.com/#RNASML
  68804. */
  68805. set: function (value) {
  68806. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  68807. return;
  68808. }
  68809. this._boundingBoxSize = value;
  68810. var scene = this.getScene();
  68811. if (scene) {
  68812. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  68813. }
  68814. },
  68815. enumerable: true,
  68816. configurable: true
  68817. });
  68818. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  68819. /**
  68820. * Gets texture matrix rotation angle around Y axis radians.
  68821. */
  68822. get: function () {
  68823. return this._rotationY;
  68824. },
  68825. /**
  68826. * Sets texture matrix rotation angle around Y axis in radians.
  68827. */
  68828. set: function (value) {
  68829. this._rotationY = value;
  68830. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  68831. },
  68832. enumerable: true,
  68833. configurable: true
  68834. });
  68835. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  68836. var rootUrlKey = "";
  68837. files.forEach(function (url) { return rootUrlKey += url; });
  68838. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  68839. };
  68840. /**
  68841. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  68842. * @param url defines the url of the prefiltered texture
  68843. * @param scene defines the scene the texture is attached to
  68844. * @param forcedExtension defines the extension of the file if different from the url
  68845. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  68846. * @return the prefiltered texture
  68847. */
  68848. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  68849. if (forcedExtension === void 0) { forcedExtension = null; }
  68850. if (createPolynomials === void 0) { createPolynomials = true; }
  68851. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  68852. };
  68853. // Methods
  68854. CubeTexture.prototype.delayLoad = function () {
  68855. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  68856. return;
  68857. }
  68858. var scene = this.getScene();
  68859. if (!scene) {
  68860. return;
  68861. }
  68862. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  68863. this._texture = this._getFromCache(this.url, this._noMipmap);
  68864. if (!this._texture) {
  68865. if (this._prefiltered) {
  68866. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  68867. }
  68868. else {
  68869. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  68870. }
  68871. }
  68872. };
  68873. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  68874. return this._textureMatrix;
  68875. };
  68876. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  68877. this._textureMatrix = value;
  68878. };
  68879. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  68880. var texture = BABYLON.SerializationHelper.Parse(function () {
  68881. var prefiltered = false;
  68882. if (parsedTexture.prefiltered) {
  68883. prefiltered = parsedTexture.prefiltered;
  68884. }
  68885. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  68886. }, parsedTexture, scene);
  68887. // Local Cubemaps
  68888. if (parsedTexture.boundingBoxPosition) {
  68889. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  68890. }
  68891. if (parsedTexture.boundingBoxSize) {
  68892. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  68893. }
  68894. // Animations
  68895. if (parsedTexture.animations) {
  68896. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  68897. var parsedAnimation = parsedTexture.animations[animationIndex];
  68898. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68899. }
  68900. }
  68901. return texture;
  68902. };
  68903. CubeTexture.prototype.clone = function () {
  68904. var _this = this;
  68905. return BABYLON.SerializationHelper.Clone(function () {
  68906. var scene = _this.getScene();
  68907. if (!scene) {
  68908. return _this;
  68909. }
  68910. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  68911. }, this);
  68912. };
  68913. __decorate([
  68914. BABYLON.serialize("rotationY")
  68915. ], CubeTexture.prototype, "rotationY", null);
  68916. return CubeTexture;
  68917. }(BABYLON.BaseTexture));
  68918. BABYLON.CubeTexture = CubeTexture;
  68919. })(BABYLON || (BABYLON = {}));
  68920. //# sourceMappingURL=babylon.cubeTexture.js.map
  68921. var BABYLON;
  68922. (function (BABYLON) {
  68923. /**
  68924. * Raw cube texture where the raw buffers are passed in
  68925. */
  68926. var RawCubeTexture = /** @class */ (function (_super) {
  68927. __extends(RawCubeTexture, _super);
  68928. /**
  68929. * Creates a cube texture where the raw buffers are passed in.
  68930. * @param scene defines the scene the texture is attached to
  68931. * @param data defines the array of data to use to create each face
  68932. * @param size defines the size of the textures
  68933. * @param format defines the format of the data
  68934. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  68935. * @param generateMipMaps defines if the engine should generate the mip levels
  68936. * @param invertY defines if data must be stored with Y axis inverted
  68937. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  68938. * @param compression defines the compression used (null by default)
  68939. */
  68940. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  68941. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  68942. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68943. if (generateMipMaps === void 0) { generateMipMaps = false; }
  68944. if (invertY === void 0) { invertY = false; }
  68945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68946. if (compression === void 0) { compression = null; }
  68947. var _this = _super.call(this, "", scene) || this;
  68948. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  68949. return _this;
  68950. }
  68951. /**
  68952. * Updates the raw cube texture.
  68953. * @param data defines the data to store
  68954. * @param format defines the data format
  68955. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  68956. * @param invertY defines if data must be stored with Y axis inverted
  68957. * @param compression defines the compression used (null by default)
  68958. * @param level defines which level of the texture to update
  68959. */
  68960. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  68961. if (compression === void 0) { compression = null; }
  68962. if (level === void 0) { level = 0; }
  68963. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  68964. };
  68965. /**
  68966. * Updates a raw cube texture with RGBD encoded data.
  68967. * @param data defines the array of data [mipmap][face] to use to create each face
  68968. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  68969. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  68970. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  68971. * @returns a promsie that resolves when the operation is complete
  68972. */
  68973. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  68974. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  68975. if (lodScale === void 0) { lodScale = 0.8; }
  68976. if (lodOffset === void 0) { lodOffset = 0; }
  68977. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  68978. };
  68979. /**
  68980. * Clones the raw cube texture.
  68981. * @return a new cube texture
  68982. */
  68983. RawCubeTexture.prototype.clone = function () {
  68984. var _this = this;
  68985. return BABYLON.SerializationHelper.Clone(function () {
  68986. var scene = _this.getScene();
  68987. var internalTexture = _this._texture;
  68988. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  68989. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  68990. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  68991. }
  68992. return texture;
  68993. }, this);
  68994. };
  68995. /** @hidden */
  68996. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  68997. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  68998. internalTexture._bufferViewArrayArray = data;
  68999. internalTexture._lodGenerationScale = lodScale;
  69000. internalTexture._lodGenerationOffset = lodOffset;
  69001. internalTexture._sphericalPolynomial = sphericalPolynomial;
  69002. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  69003. internalTexture.isReady = true;
  69004. });
  69005. };
  69006. return RawCubeTexture;
  69007. }(BABYLON.CubeTexture));
  69008. BABYLON.RawCubeTexture = RawCubeTexture;
  69009. })(BABYLON || (BABYLON = {}));
  69010. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  69011. var BABYLON;
  69012. (function (BABYLON) {
  69013. var RenderTargetTexture = /** @class */ (function (_super) {
  69014. __extends(RenderTargetTexture, _super);
  69015. /**
  69016. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  69017. * or used a shadow, depth texture...
  69018. * @param name The friendly name of the texture
  69019. * @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)
  69020. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  69021. * @param generateMipMaps True if mip maps need to be generated after render.
  69022. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  69023. * @param type The type of the buffer in the RTT (int, half float, float...)
  69024. * @param isCube True if a cube texture needs to be created
  69025. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  69026. * @param generateDepthBuffer True to generate a depth buffer
  69027. * @param generateStencilBuffer True to generate a stencil buffer
  69028. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  69029. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  69030. */
  69031. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  69032. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  69033. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69034. if (isCube === void 0) { isCube = false; }
  69035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  69036. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69037. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  69038. if (isMulti === void 0) { isMulti = false; }
  69039. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  69040. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69041. _this.isCube = isCube;
  69042. _this.renderParticles = true;
  69043. _this.renderSprites = false;
  69044. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  69045. _this.ignoreCameraViewport = false;
  69046. // Events
  69047. /**
  69048. * An event triggered when the texture is unbind.
  69049. */
  69050. _this.onBeforeBindObservable = new BABYLON.Observable();
  69051. /**
  69052. * An event triggered when the texture is unbind.
  69053. */
  69054. _this.onAfterUnbindObservable = new BABYLON.Observable();
  69055. /**
  69056. * An event triggered before rendering the texture
  69057. */
  69058. _this.onBeforeRenderObservable = new BABYLON.Observable();
  69059. /**
  69060. * An event triggered after rendering the texture
  69061. */
  69062. _this.onAfterRenderObservable = new BABYLON.Observable();
  69063. /**
  69064. * An event triggered after the texture clear
  69065. */
  69066. _this.onClearObservable = new BABYLON.Observable();
  69067. _this._currentRefreshId = -1;
  69068. _this._refreshRate = 1;
  69069. _this._samples = 1;
  69070. /**
  69071. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  69072. * It must define where the camera used to render the texture is set
  69073. */
  69074. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  69075. scene = _this.getScene();
  69076. if (!scene) {
  69077. return _this;
  69078. }
  69079. _this.renderList = new Array();
  69080. _this._engine = scene.getEngine();
  69081. _this.name = name;
  69082. _this.isRenderTarget = true;
  69083. _this._initialSizeParameter = size;
  69084. _this._processSizeParameter(size);
  69085. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  69086. });
  69087. _this._generateMipMaps = generateMipMaps ? true : false;
  69088. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  69089. // Rendering groups
  69090. _this._renderingManager = new BABYLON.RenderingManager(scene);
  69091. _this._renderingManager._useSceneAutoClearSetup = true;
  69092. if (isMulti) {
  69093. return _this;
  69094. }
  69095. _this._renderTargetOptions = {
  69096. generateMipMaps: generateMipMaps,
  69097. type: type,
  69098. format: format,
  69099. samplingMode: samplingMode,
  69100. generateDepthBuffer: generateDepthBuffer,
  69101. generateStencilBuffer: generateStencilBuffer
  69102. };
  69103. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  69104. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69105. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69106. }
  69107. if (isCube) {
  69108. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  69109. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  69110. _this._textureMatrix = BABYLON.Matrix.Identity();
  69111. }
  69112. else {
  69113. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  69114. }
  69115. return _this;
  69116. }
  69117. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  69118. get: function () {
  69119. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  69120. },
  69121. enumerable: true,
  69122. configurable: true
  69123. });
  69124. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  69125. get: function () {
  69126. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  69127. },
  69128. enumerable: true,
  69129. configurable: true
  69130. });
  69131. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  69132. get: function () {
  69133. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  69134. },
  69135. enumerable: true,
  69136. configurable: true
  69137. });
  69138. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  69139. /**
  69140. * Use this list to define the list of mesh you want to render.
  69141. */
  69142. get: function () {
  69143. return this._renderList;
  69144. },
  69145. set: function (value) {
  69146. this._renderList = value;
  69147. if (this._renderList) {
  69148. this._hookArray(this._renderList);
  69149. }
  69150. },
  69151. enumerable: true,
  69152. configurable: true
  69153. });
  69154. RenderTargetTexture.prototype._hookArray = function (array) {
  69155. var _this = this;
  69156. var oldPush = array.push;
  69157. array.push = function () {
  69158. var items = [];
  69159. for (var _i = 0; _i < arguments.length; _i++) {
  69160. items[_i] = arguments[_i];
  69161. }
  69162. var result = oldPush.apply(array, items);
  69163. _this.getScene().meshes.forEach(function (mesh) {
  69164. mesh._markSubMeshesAsLightDirty();
  69165. });
  69166. return result;
  69167. };
  69168. var oldSplice = array.splice;
  69169. array.splice = function (index, deleteCount) {
  69170. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69171. _this.getScene().meshes.forEach(function (mesh) {
  69172. mesh._markSubMeshesAsLightDirty();
  69173. });
  69174. return deleted;
  69175. };
  69176. };
  69177. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  69178. set: function (callback) {
  69179. if (this._onAfterUnbindObserver) {
  69180. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  69181. }
  69182. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  69183. },
  69184. enumerable: true,
  69185. configurable: true
  69186. });
  69187. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  69188. set: function (callback) {
  69189. if (this._onBeforeRenderObserver) {
  69190. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69191. }
  69192. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69193. },
  69194. enumerable: true,
  69195. configurable: true
  69196. });
  69197. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  69198. set: function (callback) {
  69199. if (this._onAfterRenderObserver) {
  69200. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69201. }
  69202. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69203. },
  69204. enumerable: true,
  69205. configurable: true
  69206. });
  69207. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  69208. set: function (callback) {
  69209. if (this._onClearObserver) {
  69210. this.onClearObservable.remove(this._onClearObserver);
  69211. }
  69212. this._onClearObserver = this.onClearObservable.add(callback);
  69213. },
  69214. enumerable: true,
  69215. configurable: true
  69216. });
  69217. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  69218. get: function () {
  69219. return this._renderTargetOptions;
  69220. },
  69221. enumerable: true,
  69222. configurable: true
  69223. });
  69224. RenderTargetTexture.prototype._onRatioRescale = function () {
  69225. if (this._sizeRatio) {
  69226. this.resize(this._initialSizeParameter);
  69227. }
  69228. };
  69229. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  69230. get: function () {
  69231. return this._boundingBoxSize;
  69232. },
  69233. /**
  69234. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  69235. * When defined, the cubemap will switch to local mode
  69236. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  69237. * @example https://www.babylonjs-playground.com/#RNASML
  69238. */
  69239. set: function (value) {
  69240. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  69241. return;
  69242. }
  69243. this._boundingBoxSize = value;
  69244. var scene = this.getScene();
  69245. if (scene) {
  69246. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  69247. }
  69248. },
  69249. enumerable: true,
  69250. configurable: true
  69251. });
  69252. /**
  69253. * Creates a depth stencil texture.
  69254. * This is only available in WebGL 2 or with the depth texture extension available.
  69255. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  69256. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  69257. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  69258. */
  69259. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  69260. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  69261. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  69262. if (generateStencil === void 0) { generateStencil = false; }
  69263. if (!this.getScene()) {
  69264. return;
  69265. }
  69266. var engine = this.getScene().getEngine();
  69267. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  69268. bilinearFiltering: bilinearFiltering,
  69269. comparisonFunction: comparisonFunction,
  69270. generateStencil: generateStencil,
  69271. isCube: this.isCube
  69272. });
  69273. engine.setFrameBufferDepthStencilTexture(this);
  69274. };
  69275. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  69276. if (size.ratio) {
  69277. this._sizeRatio = size.ratio;
  69278. this._size = {
  69279. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  69280. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  69281. };
  69282. }
  69283. else {
  69284. this._size = size;
  69285. }
  69286. };
  69287. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  69288. get: function () {
  69289. return this._samples;
  69290. },
  69291. set: function (value) {
  69292. if (this._samples === value) {
  69293. return;
  69294. }
  69295. var scene = this.getScene();
  69296. if (!scene) {
  69297. return;
  69298. }
  69299. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  69300. },
  69301. enumerable: true,
  69302. configurable: true
  69303. });
  69304. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  69305. this._currentRefreshId = -1;
  69306. };
  69307. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  69308. get: function () {
  69309. return this._refreshRate;
  69310. },
  69311. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69312. set: function (value) {
  69313. this._refreshRate = value;
  69314. this.resetRefreshCounter();
  69315. },
  69316. enumerable: true,
  69317. configurable: true
  69318. });
  69319. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  69320. if (!this._postProcessManager) {
  69321. var scene = this.getScene();
  69322. if (!scene) {
  69323. return;
  69324. }
  69325. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  69326. this._postProcesses = new Array();
  69327. }
  69328. this._postProcesses.push(postProcess);
  69329. this._postProcesses[0].autoClear = false;
  69330. };
  69331. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  69332. if (!this._postProcesses) {
  69333. return;
  69334. }
  69335. if (dispose) {
  69336. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  69337. var postProcess = _a[_i];
  69338. postProcess.dispose();
  69339. }
  69340. }
  69341. this._postProcesses = [];
  69342. };
  69343. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  69344. if (!this._postProcesses) {
  69345. return;
  69346. }
  69347. var index = this._postProcesses.indexOf(postProcess);
  69348. if (index === -1) {
  69349. return;
  69350. }
  69351. this._postProcesses.splice(index, 1);
  69352. if (this._postProcesses.length > 0) {
  69353. this._postProcesses[0].autoClear = false;
  69354. }
  69355. };
  69356. /** @hidden */
  69357. RenderTargetTexture.prototype._shouldRender = function () {
  69358. if (this._currentRefreshId === -1) { // At least render once
  69359. this._currentRefreshId = 1;
  69360. return true;
  69361. }
  69362. if (this.refreshRate === this._currentRefreshId) {
  69363. this._currentRefreshId = 1;
  69364. return true;
  69365. }
  69366. this._currentRefreshId++;
  69367. return false;
  69368. };
  69369. RenderTargetTexture.prototype.getRenderSize = function () {
  69370. if (this._size.width) {
  69371. return this._size.width;
  69372. }
  69373. return this._size;
  69374. };
  69375. RenderTargetTexture.prototype.getRenderWidth = function () {
  69376. if (this._size.width) {
  69377. return this._size.width;
  69378. }
  69379. return this._size;
  69380. };
  69381. RenderTargetTexture.prototype.getRenderHeight = function () {
  69382. if (this._size.width) {
  69383. return this._size.height;
  69384. }
  69385. return this._size;
  69386. };
  69387. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  69388. get: function () {
  69389. return true;
  69390. },
  69391. enumerable: true,
  69392. configurable: true
  69393. });
  69394. RenderTargetTexture.prototype.scale = function (ratio) {
  69395. var newSize = this.getRenderSize() * ratio;
  69396. this.resize(newSize);
  69397. };
  69398. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  69399. if (this.isCube) {
  69400. return this._textureMatrix;
  69401. }
  69402. return _super.prototype.getReflectionTextureMatrix.call(this);
  69403. };
  69404. RenderTargetTexture.prototype.resize = function (size) {
  69405. this.releaseInternalTexture();
  69406. var scene = this.getScene();
  69407. if (!scene) {
  69408. return;
  69409. }
  69410. this._processSizeParameter(size);
  69411. if (this.isCube) {
  69412. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  69413. }
  69414. else {
  69415. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  69416. }
  69417. };
  69418. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  69419. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  69420. if (dumpForDebug === void 0) { dumpForDebug = false; }
  69421. var scene = this.getScene();
  69422. if (!scene) {
  69423. return;
  69424. }
  69425. var engine = scene.getEngine();
  69426. if (this.useCameraPostProcesses !== undefined) {
  69427. useCameraPostProcess = this.useCameraPostProcesses;
  69428. }
  69429. if (this._waitingRenderList) {
  69430. this.renderList = [];
  69431. for (var index = 0; index < this._waitingRenderList.length; index++) {
  69432. var id = this._waitingRenderList[index];
  69433. var mesh_1 = scene.getMeshByID(id);
  69434. if (mesh_1) {
  69435. this.renderList.push(mesh_1);
  69436. }
  69437. }
  69438. delete this._waitingRenderList;
  69439. }
  69440. // Is predicate defined?
  69441. if (this.renderListPredicate) {
  69442. if (this.renderList) {
  69443. this.renderList.splice(0); // Clear previous renderList
  69444. }
  69445. else {
  69446. this.renderList = [];
  69447. }
  69448. var scene = this.getScene();
  69449. if (!scene) {
  69450. return;
  69451. }
  69452. var sceneMeshes = scene.meshes;
  69453. for (var index = 0; index < sceneMeshes.length; index++) {
  69454. var mesh = sceneMeshes[index];
  69455. if (this.renderListPredicate(mesh)) {
  69456. this.renderList.push(mesh);
  69457. }
  69458. }
  69459. }
  69460. this.onBeforeBindObservable.notifyObservers(this);
  69461. // Set custom projection.
  69462. // Needs to be before binding to prevent changing the aspect ratio.
  69463. var camera;
  69464. if (this.activeCamera) {
  69465. camera = this.activeCamera;
  69466. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69467. if (this.activeCamera !== scene.activeCamera) {
  69468. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  69469. }
  69470. }
  69471. else {
  69472. camera = scene.activeCamera;
  69473. if (camera) {
  69474. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  69475. }
  69476. }
  69477. // Prepare renderingManager
  69478. this._renderingManager.reset();
  69479. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  69480. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  69481. var sceneRenderId = scene.getRenderId();
  69482. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  69483. var mesh = currentRenderList[meshIndex];
  69484. if (mesh) {
  69485. if (!mesh.isReady(this.refreshRate === 0)) {
  69486. this.resetRefreshCounter();
  69487. continue;
  69488. }
  69489. mesh._preActivateForIntermediateRendering(sceneRenderId);
  69490. var isMasked = void 0;
  69491. if (!this.renderList && camera) {
  69492. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  69493. }
  69494. else {
  69495. isMasked = false;
  69496. }
  69497. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  69498. mesh._activate(sceneRenderId);
  69499. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  69500. var subMesh = mesh.subMeshes[subIndex];
  69501. scene._activeIndices.addCount(subMesh.indexCount, false);
  69502. this._renderingManager.dispatch(subMesh, mesh);
  69503. }
  69504. }
  69505. }
  69506. }
  69507. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  69508. var particleSystem = scene.particleSystems[particleIndex];
  69509. var emitter = particleSystem.emitter;
  69510. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  69511. continue;
  69512. }
  69513. if (currentRenderList.indexOf(emitter) >= 0) {
  69514. this._renderingManager.dispatchParticles(particleSystem);
  69515. }
  69516. }
  69517. if (this.isCube) {
  69518. for (var face = 0; face < 6; face++) {
  69519. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69520. scene.incrementRenderId();
  69521. scene.resetCachedMaterial();
  69522. }
  69523. }
  69524. else {
  69525. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  69526. }
  69527. this.onAfterUnbindObservable.notifyObservers(this);
  69528. if (scene.activeCamera) {
  69529. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  69530. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  69531. }
  69532. engine.setViewport(scene.activeCamera.viewport);
  69533. }
  69534. scene.resetCachedMaterial();
  69535. };
  69536. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  69537. var minimum = 128;
  69538. var x = renderDimension * scale;
  69539. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  69540. // Ensure we don't exceed the render dimension (while staying POT)
  69541. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  69542. };
  69543. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  69544. var _this = this;
  69545. if (!this._texture) {
  69546. return;
  69547. }
  69548. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  69549. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  69550. });
  69551. };
  69552. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  69553. var scene = this.getScene();
  69554. if (!scene) {
  69555. return;
  69556. }
  69557. var engine = scene.getEngine();
  69558. if (!this._texture) {
  69559. return;
  69560. }
  69561. // Bind
  69562. if (this._postProcessManager) {
  69563. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  69564. }
  69565. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  69566. if (this._texture) {
  69567. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  69568. }
  69569. }
  69570. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  69571. // Clear
  69572. if (this.onClearObservable.hasObservers()) {
  69573. this.onClearObservable.notifyObservers(engine);
  69574. }
  69575. else {
  69576. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  69577. }
  69578. if (!this._doNotChangeAspectRatio) {
  69579. scene.updateTransformMatrix(true);
  69580. }
  69581. // Render
  69582. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  69583. if (this._postProcessManager) {
  69584. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  69585. }
  69586. else if (useCameraPostProcess) {
  69587. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  69588. }
  69589. if (!this._doNotChangeAspectRatio) {
  69590. scene.updateTransformMatrix(true);
  69591. }
  69592. // Dump ?
  69593. if (dumpForDebug) {
  69594. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  69595. }
  69596. // Unbind
  69597. if (!this.isCube || faceIndex === 5) {
  69598. if (this.isCube) {
  69599. if (faceIndex === 5) {
  69600. engine.generateMipMapsForCubemap(this._texture);
  69601. }
  69602. }
  69603. this.unbindFrameBuffer(engine, faceIndex);
  69604. }
  69605. else {
  69606. this.onAfterRenderObservable.notifyObservers(faceIndex);
  69607. }
  69608. };
  69609. /**
  69610. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  69611. * This allowed control for front to back rendering or reversly depending of the special needs.
  69612. *
  69613. * @param renderingGroupId The rendering group id corresponding to its index
  69614. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  69615. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  69616. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  69617. */
  69618. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  69619. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  69620. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  69621. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  69622. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  69623. };
  69624. /**
  69625. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  69626. *
  69627. * @param renderingGroupId The rendering group id corresponding to its index
  69628. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  69629. */
  69630. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  69631. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  69632. this._renderingManager._useSceneAutoClearSetup = false;
  69633. };
  69634. RenderTargetTexture.prototype.clone = function () {
  69635. var textureSize = this.getSize();
  69636. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  69637. // Base texture
  69638. newTexture.hasAlpha = this.hasAlpha;
  69639. newTexture.level = this.level;
  69640. // RenderTarget Texture
  69641. newTexture.coordinatesMode = this.coordinatesMode;
  69642. if (this.renderList) {
  69643. newTexture.renderList = this.renderList.slice(0);
  69644. }
  69645. return newTexture;
  69646. };
  69647. RenderTargetTexture.prototype.serialize = function () {
  69648. if (!this.name) {
  69649. return null;
  69650. }
  69651. var serializationObject = _super.prototype.serialize.call(this);
  69652. serializationObject.renderTargetSize = this.getRenderSize();
  69653. serializationObject.renderList = [];
  69654. if (this.renderList) {
  69655. for (var index = 0; index < this.renderList.length; index++) {
  69656. serializationObject.renderList.push(this.renderList[index].id);
  69657. }
  69658. }
  69659. return serializationObject;
  69660. };
  69661. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  69662. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  69663. var objBuffer = this.getInternalTexture();
  69664. var scene = this.getScene();
  69665. if (objBuffer && scene) {
  69666. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  69667. }
  69668. };
  69669. RenderTargetTexture.prototype.dispose = function () {
  69670. if (this._postProcessManager) {
  69671. this._postProcessManager.dispose();
  69672. this._postProcessManager = null;
  69673. }
  69674. this.clearPostProcesses(true);
  69675. if (this._resizeObserver) {
  69676. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  69677. this._resizeObserver = null;
  69678. }
  69679. this.renderList = null;
  69680. // Remove from custom render targets
  69681. var scene = this.getScene();
  69682. if (!scene) {
  69683. return;
  69684. }
  69685. var index = scene.customRenderTargets.indexOf(this);
  69686. if (index >= 0) {
  69687. scene.customRenderTargets.splice(index, 1);
  69688. }
  69689. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  69690. var camera = _a[_i];
  69691. index = camera.customRenderTargets.indexOf(this);
  69692. if (index >= 0) {
  69693. camera.customRenderTargets.splice(index, 1);
  69694. }
  69695. }
  69696. _super.prototype.dispose.call(this);
  69697. };
  69698. /** @hidden */
  69699. RenderTargetTexture.prototype._rebuild = function () {
  69700. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69701. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69702. }
  69703. if (this._postProcessManager) {
  69704. this._postProcessManager._rebuild();
  69705. }
  69706. };
  69707. /**
  69708. * Clear the info related to rendering groups preventing retention point in material dispose.
  69709. */
  69710. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  69711. if (this._renderingManager) {
  69712. this._renderingManager.freeRenderingGroups();
  69713. }
  69714. };
  69715. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  69716. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  69717. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  69718. return RenderTargetTexture;
  69719. }(BABYLON.Texture));
  69720. BABYLON.RenderTargetTexture = RenderTargetTexture;
  69721. })(BABYLON || (BABYLON = {}));
  69722. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  69723. var BABYLON;
  69724. (function (BABYLON) {
  69725. ;
  69726. var MultiRenderTarget = /** @class */ (function (_super) {
  69727. __extends(MultiRenderTarget, _super);
  69728. function MultiRenderTarget(name, size, count, scene, options) {
  69729. var _this = this;
  69730. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  69731. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  69732. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  69733. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  69734. _this._engine = scene.getEngine();
  69735. if (!_this.isSupported) {
  69736. _this.dispose();
  69737. return;
  69738. }
  69739. var types = [];
  69740. var samplingModes = [];
  69741. for (var i = 0; i < count; i++) {
  69742. if (options && options.types && options.types[i] !== undefined) {
  69743. types.push(options.types[i]);
  69744. }
  69745. else {
  69746. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69747. }
  69748. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  69749. samplingModes.push(options.samplingModes[i]);
  69750. }
  69751. else {
  69752. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69753. }
  69754. }
  69755. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  69756. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  69757. _this._size = size;
  69758. _this._multiRenderTargetOptions = {
  69759. samplingModes: samplingModes,
  69760. generateMipMaps: generateMipMaps,
  69761. generateDepthBuffer: generateDepthBuffer,
  69762. generateStencilBuffer: generateStencilBuffer,
  69763. generateDepthTexture: generateDepthTexture,
  69764. types: types,
  69765. textureCount: count
  69766. };
  69767. _this._createInternalTextures();
  69768. _this._createTextures();
  69769. return _this;
  69770. }
  69771. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  69772. get: function () {
  69773. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  69774. },
  69775. enumerable: true,
  69776. configurable: true
  69777. });
  69778. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  69779. get: function () {
  69780. return this._textures;
  69781. },
  69782. enumerable: true,
  69783. configurable: true
  69784. });
  69785. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  69786. get: function () {
  69787. return this._textures[this._textures.length - 1];
  69788. },
  69789. enumerable: true,
  69790. configurable: true
  69791. });
  69792. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  69793. set: function (wrap) {
  69794. if (this._textures) {
  69795. for (var i = 0; i < this._textures.length; i++) {
  69796. this._textures[i].wrapU = wrap;
  69797. }
  69798. }
  69799. },
  69800. enumerable: true,
  69801. configurable: true
  69802. });
  69803. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  69804. set: function (wrap) {
  69805. if (this._textures) {
  69806. for (var i = 0; i < this._textures.length; i++) {
  69807. this._textures[i].wrapV = wrap;
  69808. }
  69809. }
  69810. },
  69811. enumerable: true,
  69812. configurable: true
  69813. });
  69814. /** @hidden */
  69815. MultiRenderTarget.prototype._rebuild = function () {
  69816. this.releaseInternalTextures();
  69817. this._createInternalTextures();
  69818. for (var i = 0; i < this._internalTextures.length; i++) {
  69819. var texture = this._textures[i];
  69820. texture._texture = this._internalTextures[i];
  69821. }
  69822. // Keeps references to frame buffer and stencil/depth buffer
  69823. this._texture = this._internalTextures[0];
  69824. };
  69825. MultiRenderTarget.prototype._createInternalTextures = function () {
  69826. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  69827. };
  69828. MultiRenderTarget.prototype._createTextures = function () {
  69829. this._textures = [];
  69830. for (var i = 0; i < this._internalTextures.length; i++) {
  69831. var texture = new BABYLON.Texture(null, this.getScene());
  69832. texture._texture = this._internalTextures[i];
  69833. this._textures.push(texture);
  69834. }
  69835. // Keeps references to frame buffer and stencil/depth buffer
  69836. this._texture = this._internalTextures[0];
  69837. };
  69838. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  69839. get: function () {
  69840. return this._samples;
  69841. },
  69842. set: function (value) {
  69843. if (this._samples === value) {
  69844. return;
  69845. }
  69846. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  69847. },
  69848. enumerable: true,
  69849. configurable: true
  69850. });
  69851. MultiRenderTarget.prototype.resize = function (size) {
  69852. this.releaseInternalTextures();
  69853. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  69854. this._createInternalTextures();
  69855. };
  69856. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  69857. var _this = this;
  69858. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  69859. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  69860. });
  69861. };
  69862. MultiRenderTarget.prototype.dispose = function () {
  69863. this.releaseInternalTextures();
  69864. _super.prototype.dispose.call(this);
  69865. };
  69866. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  69867. if (!this._internalTextures) {
  69868. return;
  69869. }
  69870. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  69871. if (this._internalTextures[i] !== undefined) {
  69872. this._internalTextures[i].dispose();
  69873. this._internalTextures.splice(i, 1);
  69874. }
  69875. }
  69876. };
  69877. return MultiRenderTarget;
  69878. }(BABYLON.RenderTargetTexture));
  69879. BABYLON.MultiRenderTarget = MultiRenderTarget;
  69880. })(BABYLON || (BABYLON = {}));
  69881. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  69882. var BABYLON;
  69883. (function (BABYLON) {
  69884. var MirrorTexture = /** @class */ (function (_super) {
  69885. __extends(MirrorTexture, _super);
  69886. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  69887. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69888. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69889. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  69890. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  69891. _this.scene = scene;
  69892. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  69893. _this._transformMatrix = BABYLON.Matrix.Zero();
  69894. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  69895. _this._adaptiveBlurKernel = 0;
  69896. _this._blurKernelX = 0;
  69897. _this._blurKernelY = 0;
  69898. _this._blurRatio = 1.0;
  69899. _this.ignoreCameraViewport = true;
  69900. _this._updateGammaSpace();
  69901. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  69902. _this._updateGammaSpace;
  69903. });
  69904. _this.onBeforeRenderObservable.add(function () {
  69905. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  69906. _this._savedViewMatrix = scene.getViewMatrix();
  69907. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  69908. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  69909. scene.clipPlane = _this.mirrorPlane;
  69910. scene.getEngine().cullBackFaces = false;
  69911. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  69912. });
  69913. _this.onAfterRenderObservable.add(function () {
  69914. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  69915. scene.getEngine().cullBackFaces = true;
  69916. scene._mirroredCameraPosition = null;
  69917. delete scene.clipPlane;
  69918. });
  69919. return _this;
  69920. }
  69921. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  69922. get: function () {
  69923. return this._blurRatio;
  69924. },
  69925. set: function (value) {
  69926. if (this._blurRatio === value) {
  69927. return;
  69928. }
  69929. this._blurRatio = value;
  69930. this._preparePostProcesses();
  69931. },
  69932. enumerable: true,
  69933. configurable: true
  69934. });
  69935. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  69936. set: function (value) {
  69937. this._adaptiveBlurKernel = value;
  69938. this._autoComputeBlurKernel();
  69939. },
  69940. enumerable: true,
  69941. configurable: true
  69942. });
  69943. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  69944. set: function (value) {
  69945. this.blurKernelX = value;
  69946. this.blurKernelY = value;
  69947. },
  69948. enumerable: true,
  69949. configurable: true
  69950. });
  69951. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  69952. get: function () {
  69953. return this._blurKernelX;
  69954. },
  69955. set: function (value) {
  69956. if (this._blurKernelX === value) {
  69957. return;
  69958. }
  69959. this._blurKernelX = value;
  69960. this._preparePostProcesses();
  69961. },
  69962. enumerable: true,
  69963. configurable: true
  69964. });
  69965. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  69966. get: function () {
  69967. return this._blurKernelY;
  69968. },
  69969. set: function (value) {
  69970. if (this._blurKernelY === value) {
  69971. return;
  69972. }
  69973. this._blurKernelY = value;
  69974. this._preparePostProcesses();
  69975. },
  69976. enumerable: true,
  69977. configurable: true
  69978. });
  69979. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  69980. var engine = this.getScene().getEngine();
  69981. var dw = this.getRenderWidth() / engine.getRenderWidth();
  69982. var dh = this.getRenderHeight() / engine.getRenderHeight();
  69983. this.blurKernelX = this._adaptiveBlurKernel * dw;
  69984. this.blurKernelY = this._adaptiveBlurKernel * dh;
  69985. };
  69986. MirrorTexture.prototype._onRatioRescale = function () {
  69987. if (this._sizeRatio) {
  69988. this.resize(this._initialSizeParameter);
  69989. if (!this._adaptiveBlurKernel) {
  69990. this._preparePostProcesses();
  69991. }
  69992. }
  69993. if (this._adaptiveBlurKernel) {
  69994. this._autoComputeBlurKernel();
  69995. }
  69996. };
  69997. MirrorTexture.prototype._updateGammaSpace = function () {
  69998. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  69999. };
  70000. MirrorTexture.prototype._preparePostProcesses = function () {
  70001. this.clearPostProcesses(true);
  70002. if (this._blurKernelX && this._blurKernelY) {
  70003. var engine = this.getScene().getEngine();
  70004. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70005. 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);
  70006. this._blurX.autoClear = false;
  70007. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  70008. this._blurX.inputTexture = this._texture;
  70009. }
  70010. else {
  70011. this._blurX.alwaysForcePOT = true;
  70012. }
  70013. 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);
  70014. this._blurY.autoClear = false;
  70015. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  70016. this.addPostProcess(this._blurX);
  70017. this.addPostProcess(this._blurY);
  70018. }
  70019. else {
  70020. if (this._blurY) {
  70021. this.removePostProcess(this._blurY);
  70022. this._blurY.dispose();
  70023. this._blurY = null;
  70024. }
  70025. if (this._blurX) {
  70026. this.removePostProcess(this._blurX);
  70027. this._blurX.dispose();
  70028. this._blurX = null;
  70029. }
  70030. }
  70031. };
  70032. MirrorTexture.prototype.clone = function () {
  70033. var scene = this.getScene();
  70034. if (!scene) {
  70035. return this;
  70036. }
  70037. var textureSize = this.getSize();
  70038. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  70039. // Base texture
  70040. newTexture.hasAlpha = this.hasAlpha;
  70041. newTexture.level = this.level;
  70042. // Mirror Texture
  70043. newTexture.mirrorPlane = this.mirrorPlane.clone();
  70044. if (this.renderList) {
  70045. newTexture.renderList = this.renderList.slice(0);
  70046. }
  70047. return newTexture;
  70048. };
  70049. MirrorTexture.prototype.serialize = function () {
  70050. if (!this.name) {
  70051. return null;
  70052. }
  70053. var serializationObject = _super.prototype.serialize.call(this);
  70054. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  70055. return serializationObject;
  70056. };
  70057. MirrorTexture.prototype.dispose = function () {
  70058. _super.prototype.dispose.call(this);
  70059. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  70060. };
  70061. return MirrorTexture;
  70062. }(BABYLON.RenderTargetTexture));
  70063. BABYLON.MirrorTexture = MirrorTexture;
  70064. })(BABYLON || (BABYLON = {}));
  70065. //# sourceMappingURL=babylon.mirrorTexture.js.map
  70066. var BABYLON;
  70067. (function (BABYLON) {
  70068. /**
  70069. * Creates a refraction texture used by refraction channel of the standard material.
  70070. * @param name the texture name
  70071. * @param size size of the underlying texture
  70072. * @param scene root scene
  70073. */
  70074. var RefractionTexture = /** @class */ (function (_super) {
  70075. __extends(RefractionTexture, _super);
  70076. function RefractionTexture(name, size, scene, generateMipMaps) {
  70077. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  70078. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  70079. _this.depth = 2.0;
  70080. _this.onBeforeRenderObservable.add(function () {
  70081. scene.clipPlane = _this.refractionPlane;
  70082. });
  70083. _this.onAfterRenderObservable.add(function () {
  70084. delete scene.clipPlane;
  70085. });
  70086. return _this;
  70087. }
  70088. RefractionTexture.prototype.clone = function () {
  70089. var scene = this.getScene();
  70090. if (!scene) {
  70091. return this;
  70092. }
  70093. var textureSize = this.getSize();
  70094. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  70095. // Base texture
  70096. newTexture.hasAlpha = this.hasAlpha;
  70097. newTexture.level = this.level;
  70098. // Refraction Texture
  70099. newTexture.refractionPlane = this.refractionPlane.clone();
  70100. if (this.renderList) {
  70101. newTexture.renderList = this.renderList.slice(0);
  70102. }
  70103. newTexture.depth = this.depth;
  70104. return newTexture;
  70105. };
  70106. RefractionTexture.prototype.serialize = function () {
  70107. if (!this.name) {
  70108. return null;
  70109. }
  70110. var serializationObject = _super.prototype.serialize.call(this);
  70111. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  70112. serializationObject.depth = this.depth;
  70113. return serializationObject;
  70114. };
  70115. return RefractionTexture;
  70116. }(BABYLON.RenderTargetTexture));
  70117. BABYLON.RefractionTexture = RefractionTexture;
  70118. })(BABYLON || (BABYLON = {}));
  70119. //# sourceMappingURL=babylon.refractionTexture.js.map
  70120. var BABYLON;
  70121. (function (BABYLON) {
  70122. /**
  70123. * A class extending {BABYLON.Texture} allowing drawing on a texture
  70124. * @see http://doc.babylonjs.com/how_to/dynamictexture
  70125. */
  70126. var DynamicTexture = /** @class */ (function (_super) {
  70127. __extends(DynamicTexture, _super);
  70128. /**
  70129. * Creates a {BABYLON.DynamicTexture}
  70130. * @param name defines the name of the texture
  70131. * @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
  70132. * @param scene defines the scene where you want the texture
  70133. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  70134. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  70135. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  70136. */
  70137. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  70138. if (scene === void 0) { scene = null; }
  70139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70140. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  70141. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  70142. _this.name = name;
  70143. _this._engine = _this.getScene().getEngine();
  70144. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70145. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70146. _this._generateMipMaps = generateMipMaps;
  70147. if (options.getContext) {
  70148. _this._canvas = options;
  70149. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70150. }
  70151. else {
  70152. _this._canvas = document.createElement("canvas");
  70153. if (options.width || options.width === 0) {
  70154. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  70155. }
  70156. else {
  70157. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  70158. }
  70159. }
  70160. var textureSize = _this.getSize();
  70161. _this._canvas.width = textureSize.width;
  70162. _this._canvas.height = textureSize.height;
  70163. _this._context = _this._canvas.getContext("2d");
  70164. return _this;
  70165. }
  70166. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  70167. /**
  70168. * Gets the current state of canRescale
  70169. */
  70170. get: function () {
  70171. return true;
  70172. },
  70173. enumerable: true,
  70174. configurable: true
  70175. });
  70176. DynamicTexture.prototype._recreate = function (textureSize) {
  70177. this._canvas.width = textureSize.width;
  70178. this._canvas.height = textureSize.height;
  70179. this.releaseInternalTexture();
  70180. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  70181. };
  70182. /**
  70183. * Scales the texture
  70184. * @param ratio the scale factor to apply to both width and height
  70185. */
  70186. DynamicTexture.prototype.scale = function (ratio) {
  70187. var textureSize = this.getSize();
  70188. textureSize.width *= ratio;
  70189. textureSize.height *= ratio;
  70190. this._recreate(textureSize);
  70191. };
  70192. /**
  70193. * Resizes the texture
  70194. * @param width the new width
  70195. * @param height the new height
  70196. */
  70197. DynamicTexture.prototype.scaleTo = function (width, height) {
  70198. var textureSize = this.getSize();
  70199. textureSize.width = width;
  70200. textureSize.height = height;
  70201. this._recreate(textureSize);
  70202. };
  70203. /**
  70204. * Gets the context of the canvas used by the texture
  70205. * @returns the canvas context of the dynamic texture
  70206. */
  70207. DynamicTexture.prototype.getContext = function () {
  70208. return this._context;
  70209. };
  70210. /**
  70211. * Clears the texture
  70212. */
  70213. DynamicTexture.prototype.clear = function () {
  70214. var size = this.getSize();
  70215. this._context.fillRect(0, 0, size.width, size.height);
  70216. };
  70217. /**
  70218. * Updates the texture
  70219. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70220. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  70221. */
  70222. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  70223. if (premulAlpha === void 0) { premulAlpha = false; }
  70224. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  70225. };
  70226. /**
  70227. * Draws text onto the texture
  70228. * @param text defines the text to be drawn
  70229. * @param x defines the placement of the text from the left
  70230. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  70231. * @param font defines the font to be used with font-style, font-size, font-name
  70232. * @param color defines the color used for the text
  70233. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  70234. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  70235. * @param update defines whether texture is immediately update (default is true)
  70236. */
  70237. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  70238. if (update === void 0) { update = true; }
  70239. var size = this.getSize();
  70240. if (clearColor) {
  70241. this._context.fillStyle = clearColor;
  70242. this._context.fillRect(0, 0, size.width, size.height);
  70243. }
  70244. this._context.font = font;
  70245. if (x === null || x === undefined) {
  70246. var textSize = this._context.measureText(text);
  70247. x = (size.width - textSize.width) / 2;
  70248. }
  70249. if (y === null || y === undefined) {
  70250. var fontSize = parseInt((font.replace(/\D/g, '')));
  70251. y = (size.height / 2) + (fontSize / 3.65);
  70252. }
  70253. this._context.fillStyle = color;
  70254. this._context.fillText(text, x, y);
  70255. if (update) {
  70256. this.update(invertY);
  70257. }
  70258. };
  70259. /**
  70260. * Clones the texture
  70261. * @returns the clone of the texture.
  70262. */
  70263. DynamicTexture.prototype.clone = function () {
  70264. var scene = this.getScene();
  70265. if (!scene) {
  70266. return this;
  70267. }
  70268. var textureSize = this.getSize();
  70269. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  70270. // Base texture
  70271. newTexture.hasAlpha = this.hasAlpha;
  70272. newTexture.level = this.level;
  70273. // Dynamic Texture
  70274. newTexture.wrapU = this.wrapU;
  70275. newTexture.wrapV = this.wrapV;
  70276. return newTexture;
  70277. };
  70278. /**
  70279. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  70280. * @returns a serialized dynamic texture object
  70281. */
  70282. DynamicTexture.prototype.serialize = function () {
  70283. var scene = this.getScene();
  70284. if (scene && !scene.isReady()) {
  70285. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  70286. }
  70287. var serializationObject = _super.prototype.serialize.call(this);
  70288. serializationObject.base64String = this._canvas.toDataURL();
  70289. serializationObject.invertY = this._invertY;
  70290. serializationObject.samplingMode = this.samplingMode;
  70291. return serializationObject;
  70292. };
  70293. /** @hidden */
  70294. DynamicTexture.prototype._rebuild = function () {
  70295. this.update();
  70296. };
  70297. return DynamicTexture;
  70298. }(BABYLON.Texture));
  70299. BABYLON.DynamicTexture = DynamicTexture;
  70300. })(BABYLON || (BABYLON = {}));
  70301. //# sourceMappingURL=babylon.dynamicTexture.js.map
  70302. var BABYLON;
  70303. (function (BABYLON) {
  70304. var VideoTexture = /** @class */ (function (_super) {
  70305. __extends(VideoTexture, _super);
  70306. /**
  70307. * Creates a video texture.
  70308. * Sample : https://doc.babylonjs.com/how_to/video_texture
  70309. * @param {string | null} name optional name, will detect from video source, if not defined
  70310. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  70311. * @param {BABYLON.Scene} scene is obviously the current scene.
  70312. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  70313. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  70314. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  70315. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  70316. */
  70317. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  70318. if (generateMipMaps === void 0) { generateMipMaps = false; }
  70319. if (invertY === void 0) { invertY = false; }
  70320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70321. if (settings === void 0) { settings = {
  70322. autoPlay: true,
  70323. loop: true,
  70324. autoUpdateTexture: true,
  70325. }; }
  70326. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70327. _this._onUserActionRequestedObservable = null;
  70328. _this._stillImageCaptured = false;
  70329. _this._poster = false;
  70330. _this._createInternalTexture = function () {
  70331. if (_this._texture != null) {
  70332. if (_this._poster) {
  70333. _this._texture.dispose();
  70334. _this._poster = false;
  70335. }
  70336. else {
  70337. return;
  70338. }
  70339. }
  70340. if (!_this._engine.needPOTTextures ||
  70341. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  70342. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  70343. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  70344. }
  70345. else {
  70346. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70347. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70348. _this._generateMipMaps = false;
  70349. }
  70350. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  70351. if (!_this.video.autoplay) {
  70352. var oldHandler_1 = _this.video.onplaying;
  70353. var error_1 = false;
  70354. _this.video.onplaying = function () {
  70355. _this.video.onplaying = oldHandler_1;
  70356. _this._texture.isReady = true;
  70357. _this._updateInternalTexture();
  70358. if (!error_1) {
  70359. _this.video.pause();
  70360. }
  70361. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70362. _this.onLoadObservable.notifyObservers(_this);
  70363. }
  70364. };
  70365. var playing = _this.video.play();
  70366. if (playing) {
  70367. playing.then(function () {
  70368. // Everything is good.
  70369. })
  70370. .catch(function () {
  70371. error_1 = true;
  70372. // On Chrome for instance, new policies might prevent playing without user interaction.
  70373. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  70374. _this._onUserActionRequestedObservable.notifyObservers(_this);
  70375. }
  70376. });
  70377. }
  70378. else {
  70379. _this.video.onplaying = oldHandler_1;
  70380. _this._texture.isReady = true;
  70381. _this._updateInternalTexture();
  70382. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70383. _this.onLoadObservable.notifyObservers(_this);
  70384. }
  70385. }
  70386. }
  70387. else {
  70388. _this._texture.isReady = true;
  70389. _this._updateInternalTexture();
  70390. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  70391. _this.onLoadObservable.notifyObservers(_this);
  70392. }
  70393. }
  70394. };
  70395. _this.reset = function () {
  70396. if (_this._texture == null) {
  70397. return;
  70398. }
  70399. if (!_this._poster) {
  70400. _this._texture.dispose();
  70401. _this._texture = null;
  70402. }
  70403. };
  70404. _this._updateInternalTexture = function (e) {
  70405. if (_this._texture == null || !_this._texture.isReady) {
  70406. return;
  70407. }
  70408. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  70409. return;
  70410. }
  70411. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  70412. };
  70413. _this._engine = _this.getScene().getEngine();
  70414. _this._generateMipMaps = generateMipMaps;
  70415. _this._samplingMode = samplingMode;
  70416. _this.autoUpdateTexture = settings.autoUpdateTexture;
  70417. _this.name = name || _this._getName(src);
  70418. _this.video = _this._getVideo(src);
  70419. if (settings.poster) {
  70420. _this.video.poster = settings.poster;
  70421. }
  70422. if (settings.autoPlay !== undefined) {
  70423. _this.video.autoplay = settings.autoPlay;
  70424. }
  70425. if (settings.loop !== undefined) {
  70426. _this.video.loop = settings.loop;
  70427. }
  70428. _this.video.setAttribute("playsinline", "");
  70429. _this.video.addEventListener("canplay", _this._createInternalTexture);
  70430. _this.video.addEventListener("paused", _this._updateInternalTexture);
  70431. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  70432. _this.video.addEventListener("emptied", _this.reset);
  70433. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  70434. _this._createInternalTexture();
  70435. }
  70436. if (settings.poster) {
  70437. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  70438. _this._poster = true;
  70439. }
  70440. return _this;
  70441. }
  70442. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  70443. get: function () {
  70444. if (!this._onUserActionRequestedObservable) {
  70445. this._onUserActionRequestedObservable = new BABYLON.Observable();
  70446. }
  70447. return this._onUserActionRequestedObservable;
  70448. },
  70449. enumerable: true,
  70450. configurable: true
  70451. });
  70452. VideoTexture.prototype._getName = function (src) {
  70453. if (src instanceof HTMLVideoElement) {
  70454. return src.currentSrc;
  70455. }
  70456. if (typeof src === "object") {
  70457. return src.toString();
  70458. }
  70459. return src;
  70460. };
  70461. ;
  70462. VideoTexture.prototype._getVideo = function (src) {
  70463. if (src instanceof HTMLVideoElement) {
  70464. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  70465. return src;
  70466. }
  70467. var video = document.createElement("video");
  70468. if (typeof src === "string") {
  70469. BABYLON.Tools.SetCorsBehavior(src, video);
  70470. video.src = src;
  70471. }
  70472. else {
  70473. BABYLON.Tools.SetCorsBehavior(src[0], video);
  70474. src.forEach(function (url) {
  70475. var source = document.createElement("source");
  70476. source.src = url;
  70477. video.appendChild(source);
  70478. });
  70479. }
  70480. return video;
  70481. };
  70482. ;
  70483. /**
  70484. * @hidden Internal method to initiate `update`.
  70485. */
  70486. VideoTexture.prototype._rebuild = function () {
  70487. this.update();
  70488. };
  70489. /**
  70490. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  70491. */
  70492. VideoTexture.prototype.update = function () {
  70493. if (!this.autoUpdateTexture) {
  70494. // Expecting user to call `updateTexture` manually
  70495. return;
  70496. }
  70497. this.updateTexture(true);
  70498. };
  70499. /**
  70500. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  70501. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  70502. */
  70503. VideoTexture.prototype.updateTexture = function (isVisible) {
  70504. if (!isVisible) {
  70505. return;
  70506. }
  70507. if (this.video.paused && this._stillImageCaptured) {
  70508. return;
  70509. }
  70510. this._stillImageCaptured = true;
  70511. this._updateInternalTexture();
  70512. };
  70513. /**
  70514. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  70515. * @param url New url.
  70516. */
  70517. VideoTexture.prototype.updateURL = function (url) {
  70518. this.video.src = url;
  70519. };
  70520. VideoTexture.prototype.dispose = function () {
  70521. _super.prototype.dispose.call(this);
  70522. if (this._onUserActionRequestedObservable) {
  70523. this._onUserActionRequestedObservable.clear();
  70524. this._onUserActionRequestedObservable = null;
  70525. }
  70526. this.video.removeEventListener("canplay", this._createInternalTexture);
  70527. this.video.removeEventListener("paused", this._updateInternalTexture);
  70528. this.video.removeEventListener("seeked", this._updateInternalTexture);
  70529. this.video.removeEventListener("emptied", this.reset);
  70530. this.video.pause();
  70531. };
  70532. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  70533. var video = document.createElement("video");
  70534. video.setAttribute('autoplay', '');
  70535. video.setAttribute('muted', '');
  70536. video.setAttribute('playsinline', '');
  70537. var constraintsDeviceId;
  70538. if (constraints && constraints.deviceId) {
  70539. constraintsDeviceId = {
  70540. exact: constraints.deviceId,
  70541. };
  70542. }
  70543. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  70544. if (navigator.mediaDevices) {
  70545. navigator.mediaDevices.getUserMedia({ video: constraints })
  70546. .then(function (stream) {
  70547. if (video.mozSrcObject !== undefined) {
  70548. // hack for Firefox < 19
  70549. video.mozSrcObject = stream;
  70550. }
  70551. else {
  70552. video.srcObject = stream;
  70553. }
  70554. var onPlaying = function () {
  70555. if (onReady) {
  70556. onReady(new VideoTexture("video", video, scene, true, true));
  70557. }
  70558. video.removeEventListener("playing", onPlaying);
  70559. };
  70560. video.addEventListener("playing", onPlaying);
  70561. video.play();
  70562. })
  70563. .catch(function (err) {
  70564. BABYLON.Tools.Error(err.name);
  70565. });
  70566. }
  70567. else {
  70568. navigator.getUserMedia =
  70569. navigator.getUserMedia ||
  70570. navigator.webkitGetUserMedia ||
  70571. navigator.mozGetUserMedia ||
  70572. navigator.msGetUserMedia;
  70573. if (navigator.getUserMedia) {
  70574. navigator.getUserMedia({
  70575. video: {
  70576. deviceId: constraintsDeviceId,
  70577. width: {
  70578. min: (constraints && constraints.minWidth) || 256,
  70579. max: (constraints && constraints.maxWidth) || 640,
  70580. },
  70581. height: {
  70582. min: (constraints && constraints.minHeight) || 256,
  70583. max: (constraints && constraints.maxHeight) || 480,
  70584. },
  70585. },
  70586. }, function (stream) {
  70587. if (video.mozSrcObject !== undefined) {
  70588. // hack for Firefox < 19
  70589. video.mozSrcObject = stream;
  70590. }
  70591. else {
  70592. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  70593. }
  70594. video.play();
  70595. if (onReady) {
  70596. onReady(new VideoTexture("video", video, scene, true, true));
  70597. }
  70598. }, function (e) {
  70599. BABYLON.Tools.Error(e.name);
  70600. });
  70601. }
  70602. }
  70603. };
  70604. return VideoTexture;
  70605. }(BABYLON.Texture));
  70606. BABYLON.VideoTexture = VideoTexture;
  70607. })(BABYLON || (BABYLON = {}));
  70608. //# sourceMappingURL=babylon.videoTexture.js.map
  70609. var BABYLON;
  70610. (function (BABYLON) {
  70611. var RawTexture = /** @class */ (function (_super) {
  70612. __extends(RawTexture, _super);
  70613. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  70614. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70615. if (invertY === void 0) { invertY = false; }
  70616. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70617. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70618. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70619. _this.format = format;
  70620. _this._engine = scene.getEngine();
  70621. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  70622. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70623. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70624. return _this;
  70625. }
  70626. RawTexture.prototype.update = function (data) {
  70627. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  70628. };
  70629. // Statics
  70630. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70631. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70632. if (invertY === void 0) { invertY = false; }
  70633. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70634. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  70635. };
  70636. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70637. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70638. if (invertY === void 0) { invertY = false; }
  70639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70640. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  70641. };
  70642. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  70643. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70644. if (invertY === void 0) { invertY = false; }
  70645. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70646. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  70647. };
  70648. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70649. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70650. if (invertY === void 0) { invertY = false; }
  70651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70652. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70653. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  70654. };
  70655. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70656. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70657. if (invertY === void 0) { invertY = false; }
  70658. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70659. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70660. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  70661. };
  70662. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  70663. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70664. if (invertY === void 0) { invertY = false; }
  70665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70666. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  70667. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  70668. };
  70669. return RawTexture;
  70670. }(BABYLON.Texture));
  70671. BABYLON.RawTexture = RawTexture;
  70672. })(BABYLON || (BABYLON = {}));
  70673. //# sourceMappingURL=babylon.rawTexture.js.map
  70674. var BABYLON;
  70675. (function (BABYLON) {
  70676. /**
  70677. * Class used to store 3D textures containing user data
  70678. */
  70679. var RawTexture3D = /** @class */ (function (_super) {
  70680. __extends(RawTexture3D, _super);
  70681. /**
  70682. * Create a new RawTexture3D
  70683. * @param data defines the data of the texture
  70684. * @param width defines the width of the texture
  70685. * @param height defines the height of the texture
  70686. * @param depth defines the depth of the texture
  70687. * @param format defines the texture format to use
  70688. * @param scene defines the hosting scene
  70689. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  70690. * @param invertY defines if texture must be stored with Y axis inverted
  70691. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  70692. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  70693. */
  70694. function RawTexture3D(data, width, height, depth,
  70695. /** Gets or sets the texture format to use */
  70696. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  70697. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70698. if (invertY === void 0) { invertY = false; }
  70699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  70700. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70701. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  70702. _this.format = format;
  70703. _this._engine = scene.getEngine();
  70704. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  70705. _this.is3D = true;
  70706. return _this;
  70707. }
  70708. /**
  70709. * Update the texture with new data
  70710. * @param data defines the data to store in the texture
  70711. */
  70712. RawTexture3D.prototype.update = function (data) {
  70713. if (!this._texture) {
  70714. return;
  70715. }
  70716. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  70717. };
  70718. return RawTexture3D;
  70719. }(BABYLON.Texture));
  70720. BABYLON.RawTexture3D = RawTexture3D;
  70721. })(BABYLON || (BABYLON = {}));
  70722. //# sourceMappingURL=babylon.rawTexture3D.js.map
  70723. var BABYLON;
  70724. (function (BABYLON) {
  70725. /**
  70726. * PostProcessManager is used to manage one or more post processes or post process pipelines
  70727. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  70728. */
  70729. var PostProcessManager = /** @class */ (function () {
  70730. /**
  70731. * Creates a new instance PostProcess
  70732. * @param scene The scene that the post process is associated with.
  70733. */
  70734. function PostProcessManager(scene) {
  70735. this._vertexBuffers = {};
  70736. this._scene = scene;
  70737. }
  70738. PostProcessManager.prototype._prepareBuffers = function () {
  70739. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  70740. return;
  70741. }
  70742. // VBO
  70743. var vertices = [];
  70744. vertices.push(1, 1);
  70745. vertices.push(-1, 1);
  70746. vertices.push(-1, -1);
  70747. vertices.push(1, -1);
  70748. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70749. this._buildIndexBuffer();
  70750. };
  70751. PostProcessManager.prototype._buildIndexBuffer = function () {
  70752. // Indices
  70753. var indices = [];
  70754. indices.push(0);
  70755. indices.push(1);
  70756. indices.push(2);
  70757. indices.push(0);
  70758. indices.push(2);
  70759. indices.push(3);
  70760. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  70761. };
  70762. /**
  70763. * Rebuilds the vertex buffers of the manager.
  70764. * @hidden
  70765. */
  70766. PostProcessManager.prototype._rebuild = function () {
  70767. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70768. if (!vb) {
  70769. return;
  70770. }
  70771. vb._rebuild();
  70772. this._buildIndexBuffer();
  70773. };
  70774. // Methods
  70775. /**
  70776. * Prepares a frame to be run through a post process.
  70777. * @param sourceTexture The input texture to the post procesess. (default: null)
  70778. * @param postProcesses An array of post processes to be run. (default: null)
  70779. * @returns True if the post processes were able to be run.
  70780. * @hidden
  70781. */
  70782. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  70783. if (sourceTexture === void 0) { sourceTexture = null; }
  70784. if (postProcesses === void 0) { postProcesses = null; }
  70785. var camera = this._scene.activeCamera;
  70786. if (!camera) {
  70787. return false;
  70788. }
  70789. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  70790. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  70791. return false;
  70792. }
  70793. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  70794. return true;
  70795. };
  70796. /**
  70797. * Manually render a set of post processes to a texture.
  70798. * @param postProcesses An array of post processes to be run.
  70799. * @param targetTexture The target texture to render to.
  70800. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  70801. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  70802. * @param lodLevel defines which lod of the texture to render to
  70803. */
  70804. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  70805. if (targetTexture === void 0) { targetTexture = null; }
  70806. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  70807. if (faceIndex === void 0) { faceIndex = 0; }
  70808. if (lodLevel === void 0) { lodLevel = 0; }
  70809. var engine = this._scene.getEngine();
  70810. for (var index = 0; index < postProcesses.length; index++) {
  70811. if (index < postProcesses.length - 1) {
  70812. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  70813. }
  70814. else {
  70815. if (targetTexture) {
  70816. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  70817. }
  70818. else {
  70819. engine.restoreDefaultFramebuffer();
  70820. }
  70821. }
  70822. var pp = postProcesses[index];
  70823. var effect = pp.apply();
  70824. if (effect) {
  70825. pp.onBeforeRenderObservable.notifyObservers(effect);
  70826. // VBOs
  70827. this._prepareBuffers();
  70828. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  70829. // Draw order
  70830. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70831. pp.onAfterRenderObservable.notifyObservers(effect);
  70832. }
  70833. }
  70834. // Restore depth buffer
  70835. engine.setDepthBuffer(true);
  70836. engine.setDepthWrite(true);
  70837. };
  70838. /**
  70839. * Finalize the result of the output of the postprocesses.
  70840. * @param doNotPresent If true the result will not be displayed to the screen.
  70841. * @param targetTexture The target texture to render to.
  70842. * @param faceIndex The index of the face to bind the target texture to.
  70843. * @param postProcesses The array of post processes to render.
  70844. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  70845. * @hidden
  70846. */
  70847. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  70848. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  70849. var camera = this._scene.activeCamera;
  70850. if (!camera) {
  70851. return;
  70852. }
  70853. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  70854. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  70855. return;
  70856. }
  70857. var engine = this._scene.getEngine();
  70858. for (var index = 0, len = postProcesses.length; index < len; index++) {
  70859. var pp = postProcesses[index];
  70860. if (index < len - 1) {
  70861. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  70862. }
  70863. else {
  70864. if (targetTexture) {
  70865. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  70866. pp._outputTexture = targetTexture;
  70867. }
  70868. else {
  70869. engine.restoreDefaultFramebuffer();
  70870. pp._outputTexture = null;
  70871. }
  70872. }
  70873. if (doNotPresent) {
  70874. break;
  70875. }
  70876. var effect = pp.apply();
  70877. if (effect) {
  70878. pp.onBeforeRenderObservable.notifyObservers(effect);
  70879. // VBOs
  70880. this._prepareBuffers();
  70881. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  70882. // Draw order
  70883. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70884. pp.onAfterRenderObservable.notifyObservers(effect);
  70885. }
  70886. }
  70887. // Restore states
  70888. engine.setDepthBuffer(true);
  70889. engine.setDepthWrite(true);
  70890. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70891. };
  70892. /**
  70893. * Disposes of the post process manager.
  70894. */
  70895. PostProcessManager.prototype.dispose = function () {
  70896. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70897. if (buffer) {
  70898. buffer.dispose();
  70899. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70900. }
  70901. if (this._indexBuffer) {
  70902. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  70903. this._indexBuffer = null;
  70904. }
  70905. };
  70906. return PostProcessManager;
  70907. }());
  70908. BABYLON.PostProcessManager = PostProcessManager;
  70909. })(BABYLON || (BABYLON = {}));
  70910. //# sourceMappingURL=babylon.postProcessManager.js.map
  70911. var BABYLON;
  70912. (function (BABYLON) {
  70913. /**
  70914. * PostProcess can be used to apply a shader to a texture after it has been rendered
  70915. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  70916. */
  70917. var PostProcess = /** @class */ (function () {
  70918. /**
  70919. * Creates a new instance PostProcess
  70920. * @param name The name of the PostProcess.
  70921. * @param fragmentUrl The url of the fragment shader to be used.
  70922. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  70923. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  70924. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70925. * @param camera The camera to apply the render pass to.
  70926. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70927. * @param engine The engine which the post process will be applied. (default: current engine)
  70928. * @param reusable If the post process can be reused on the same frame. (default: false)
  70929. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  70930. * @param textureType Type of textures used when performing the post process. (default: 0)
  70931. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  70932. * @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
  70933. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  70934. */
  70935. function PostProcess(
  70936. /** Name of the PostProcess. */
  70937. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  70938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  70939. if (defines === void 0) { defines = null; }
  70940. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70941. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  70942. if (blockCompilation === void 0) { blockCompilation = false; }
  70943. this.name = name;
  70944. /**
  70945. * Width of the texture to apply the post process on
  70946. */
  70947. this.width = -1;
  70948. /**
  70949. * Height of the texture to apply the post process on
  70950. */
  70951. this.height = -1;
  70952. /**
  70953. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  70954. * @hidden
  70955. */
  70956. this._outputTexture = null;
  70957. /**
  70958. * If the buffer needs to be cleared before applying the post process. (default: true)
  70959. * Should be set to false if shader will overwrite all previous pixels.
  70960. */
  70961. this.autoClear = true;
  70962. /**
  70963. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  70964. */
  70965. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  70966. /**
  70967. * Animations to be used for the post processing
  70968. */
  70969. this.animations = new Array();
  70970. /**
  70971. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  70972. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  70973. */
  70974. this.enablePixelPerfectMode = false;
  70975. /**
  70976. * Force the postprocess to be applied without taking in account viewport
  70977. */
  70978. this.forceFullscreenViewport = true;
  70979. /**
  70980. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  70981. *
  70982. * | Value | Type | Description |
  70983. * | ----- | ----------------------------------- | ----------- |
  70984. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  70985. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  70986. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  70987. *
  70988. */
  70989. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  70990. /**
  70991. * Force textures to be a power of two (default: false)
  70992. */
  70993. this.alwaysForcePOT = false;
  70994. this._samples = 1;
  70995. /**
  70996. * Modify the scale of the post process to be the same as the viewport (default: false)
  70997. */
  70998. this.adaptScaleToCurrentViewport = false;
  70999. this._reusable = false;
  71000. /**
  71001. * Smart array of input and output textures for the post process.
  71002. * @hidden
  71003. */
  71004. this._textures = new BABYLON.SmartArray(2);
  71005. /**
  71006. * The index in _textures that corresponds to the output texture.
  71007. * @hidden
  71008. */
  71009. this._currentRenderTextureInd = 0;
  71010. this._scaleRatio = new BABYLON.Vector2(1, 1);
  71011. this._texelSize = BABYLON.Vector2.Zero();
  71012. // Events
  71013. /**
  71014. * An event triggered when the postprocess is activated.
  71015. */
  71016. this.onActivateObservable = new BABYLON.Observable();
  71017. /**
  71018. * An event triggered when the postprocess changes its size.
  71019. */
  71020. this.onSizeChangedObservable = new BABYLON.Observable();
  71021. /**
  71022. * An event triggered when the postprocess applies its effect.
  71023. */
  71024. this.onApplyObservable = new BABYLON.Observable();
  71025. /**
  71026. * An event triggered before rendering the postprocess
  71027. */
  71028. this.onBeforeRenderObservable = new BABYLON.Observable();
  71029. /**
  71030. * An event triggered after rendering the postprocess
  71031. */
  71032. this.onAfterRenderObservable = new BABYLON.Observable();
  71033. if (camera != null) {
  71034. this._camera = camera;
  71035. this._scene = camera.getScene();
  71036. camera.attachPostProcess(this);
  71037. this._engine = this._scene.getEngine();
  71038. this._scene.postProcesses.push(this);
  71039. }
  71040. else if (engine) {
  71041. this._engine = engine;
  71042. this._engine.postProcesses.push(this);
  71043. }
  71044. this._options = options;
  71045. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  71046. this._reusable = reusable || false;
  71047. this._textureType = textureType;
  71048. this._samplers = samplers || [];
  71049. this._samplers.push("textureSampler");
  71050. this._fragmentUrl = fragmentUrl;
  71051. this._vertexUrl = vertexUrl;
  71052. this._parameters = parameters || [];
  71053. this._parameters.push("scale");
  71054. this._indexParameters = indexParameters;
  71055. if (!blockCompilation) {
  71056. this.updateEffect(defines);
  71057. }
  71058. }
  71059. Object.defineProperty(PostProcess.prototype, "samples", {
  71060. /**
  71061. * Number of sample textures (default: 1)
  71062. */
  71063. get: function () {
  71064. return this._samples;
  71065. },
  71066. set: function (n) {
  71067. var _this = this;
  71068. this._samples = n;
  71069. this._textures.forEach(function (texture) {
  71070. if (texture.samples !== _this._samples) {
  71071. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  71072. }
  71073. });
  71074. },
  71075. enumerable: true,
  71076. configurable: true
  71077. });
  71078. Object.defineProperty(PostProcess.prototype, "onActivate", {
  71079. /**
  71080. * A function that is added to the onActivateObservable
  71081. */
  71082. set: function (callback) {
  71083. if (this._onActivateObserver) {
  71084. this.onActivateObservable.remove(this._onActivateObserver);
  71085. }
  71086. if (callback) {
  71087. this._onActivateObserver = this.onActivateObservable.add(callback);
  71088. }
  71089. },
  71090. enumerable: true,
  71091. configurable: true
  71092. });
  71093. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  71094. /**
  71095. * A function that is added to the onSizeChangedObservable
  71096. */
  71097. set: function (callback) {
  71098. if (this._onSizeChangedObserver) {
  71099. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  71100. }
  71101. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  71102. },
  71103. enumerable: true,
  71104. configurable: true
  71105. });
  71106. Object.defineProperty(PostProcess.prototype, "onApply", {
  71107. /**
  71108. * A function that is added to the onApplyObservable
  71109. */
  71110. set: function (callback) {
  71111. if (this._onApplyObserver) {
  71112. this.onApplyObservable.remove(this._onApplyObserver);
  71113. }
  71114. this._onApplyObserver = this.onApplyObservable.add(callback);
  71115. },
  71116. enumerable: true,
  71117. configurable: true
  71118. });
  71119. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  71120. /**
  71121. * A function that is added to the onBeforeRenderObservable
  71122. */
  71123. set: function (callback) {
  71124. if (this._onBeforeRenderObserver) {
  71125. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71126. }
  71127. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71128. },
  71129. enumerable: true,
  71130. configurable: true
  71131. });
  71132. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  71133. /**
  71134. * A function that is added to the onAfterRenderObservable
  71135. */
  71136. set: function (callback) {
  71137. if (this._onAfterRenderObserver) {
  71138. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71139. }
  71140. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71141. },
  71142. enumerable: true,
  71143. configurable: true
  71144. });
  71145. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  71146. /**
  71147. * 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
  71148. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  71149. */
  71150. get: function () {
  71151. return this._textures.data[this._currentRenderTextureInd];
  71152. },
  71153. set: function (value) {
  71154. this._forcedOutputTexture = value;
  71155. },
  71156. enumerable: true,
  71157. configurable: true
  71158. });
  71159. /**
  71160. * Gets the camera which post process is applied to.
  71161. * @returns The camera the post process is applied to.
  71162. */
  71163. PostProcess.prototype.getCamera = function () {
  71164. return this._camera;
  71165. };
  71166. Object.defineProperty(PostProcess.prototype, "texelSize", {
  71167. /**
  71168. * Gets the texel size of the postprocess.
  71169. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  71170. */
  71171. get: function () {
  71172. if (this._shareOutputWithPostProcess) {
  71173. return this._shareOutputWithPostProcess.texelSize;
  71174. }
  71175. if (this._forcedOutputTexture) {
  71176. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  71177. }
  71178. return this._texelSize;
  71179. },
  71180. enumerable: true,
  71181. configurable: true
  71182. });
  71183. /**
  71184. * Gets the engine which this post process belongs to.
  71185. * @returns The engine the post process was enabled with.
  71186. */
  71187. PostProcess.prototype.getEngine = function () {
  71188. return this._engine;
  71189. };
  71190. /**
  71191. * The effect that is created when initializing the post process.
  71192. * @returns The created effect corrisponding the the postprocess.
  71193. */
  71194. PostProcess.prototype.getEffect = function () {
  71195. return this._effect;
  71196. };
  71197. /**
  71198. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  71199. * @param postProcess The post process to share the output with.
  71200. * @returns This post process.
  71201. */
  71202. PostProcess.prototype.shareOutputWith = function (postProcess) {
  71203. this._disposeTextures();
  71204. this._shareOutputWithPostProcess = postProcess;
  71205. return this;
  71206. };
  71207. /**
  71208. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  71209. * This should be called if the post process that shares output with this post process is disabled/disposed.
  71210. */
  71211. PostProcess.prototype.useOwnOutput = function () {
  71212. if (this._textures.length == 0) {
  71213. this._textures = new BABYLON.SmartArray(2);
  71214. }
  71215. this._shareOutputWithPostProcess = null;
  71216. };
  71217. /**
  71218. * Updates the effect with the current post process compile time values and recompiles the shader.
  71219. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71220. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71221. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71222. * @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
  71223. * @param onCompiled Called when the shader has been compiled.
  71224. * @param onError Called if there is an error when compiling a shader.
  71225. */
  71226. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71227. if (defines === void 0) { defines = null; }
  71228. if (uniforms === void 0) { uniforms = null; }
  71229. if (samplers === void 0) { samplers = null; }
  71230. 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);
  71231. };
  71232. /**
  71233. * The post process is reusable if it can be used multiple times within one frame.
  71234. * @returns If the post process is reusable
  71235. */
  71236. PostProcess.prototype.isReusable = function () {
  71237. return this._reusable;
  71238. };
  71239. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  71240. PostProcess.prototype.markTextureDirty = function () {
  71241. this.width = -1;
  71242. };
  71243. /**
  71244. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  71245. * 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.
  71246. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  71247. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  71248. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  71249. * @returns The target texture that was bound to be written to.
  71250. */
  71251. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  71252. var _this = this;
  71253. if (sourceTexture === void 0) { sourceTexture = null; }
  71254. camera = camera || this._camera;
  71255. var scene = camera.getScene();
  71256. var engine = scene.getEngine();
  71257. var maxSize = engine.getCaps().maxTextureSize;
  71258. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  71259. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  71260. // 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
  71261. var webVRCamera = camera.parent;
  71262. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  71263. requiredWidth /= 2;
  71264. }
  71265. var desiredWidth = (this._options.width || requiredWidth);
  71266. var desiredHeight = this._options.height || requiredHeight;
  71267. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  71268. if (this.adaptScaleToCurrentViewport) {
  71269. var currentViewport = engine.currentViewport;
  71270. if (currentViewport) {
  71271. desiredWidth *= currentViewport.width;
  71272. desiredHeight *= currentViewport.height;
  71273. }
  71274. }
  71275. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  71276. if (!this._options.width) {
  71277. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  71278. }
  71279. if (!this._options.height) {
  71280. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  71281. }
  71282. }
  71283. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  71284. if (this._textures.length > 0) {
  71285. for (var i = 0; i < this._textures.length; i++) {
  71286. this._engine._releaseTexture(this._textures.data[i]);
  71287. }
  71288. this._textures.reset();
  71289. }
  71290. this.width = desiredWidth;
  71291. this.height = desiredHeight;
  71292. var textureSize = { width: this.width, height: this.height };
  71293. var textureOptions = {
  71294. generateMipMaps: false,
  71295. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  71296. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  71297. samplingMode: this.renderTargetSamplingMode,
  71298. type: this._textureType
  71299. };
  71300. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71301. if (this._reusable) {
  71302. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  71303. }
  71304. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  71305. this.onSizeChangedObservable.notifyObservers(this);
  71306. }
  71307. this._textures.forEach(function (texture) {
  71308. if (texture.samples !== _this.samples) {
  71309. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  71310. }
  71311. });
  71312. }
  71313. var target;
  71314. if (this._shareOutputWithPostProcess) {
  71315. target = this._shareOutputWithPostProcess.inputTexture;
  71316. }
  71317. else if (this._forcedOutputTexture) {
  71318. target = this._forcedOutputTexture;
  71319. this.width = this._forcedOutputTexture.width;
  71320. this.height = this._forcedOutputTexture.height;
  71321. }
  71322. else {
  71323. target = this.inputTexture;
  71324. }
  71325. // Bind the input of this post process to be used as the output of the previous post process.
  71326. if (this.enablePixelPerfectMode) {
  71327. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  71328. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  71329. }
  71330. else {
  71331. this._scaleRatio.copyFromFloats(1, 1);
  71332. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  71333. }
  71334. this.onActivateObservable.notifyObservers(camera);
  71335. // Clear
  71336. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  71337. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  71338. }
  71339. if (this._reusable) {
  71340. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  71341. }
  71342. return target;
  71343. };
  71344. Object.defineProperty(PostProcess.prototype, "isSupported", {
  71345. /**
  71346. * If the post process is supported.
  71347. */
  71348. get: function () {
  71349. return this._effect.isSupported;
  71350. },
  71351. enumerable: true,
  71352. configurable: true
  71353. });
  71354. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  71355. /**
  71356. * The aspect ratio of the output texture.
  71357. */
  71358. get: function () {
  71359. if (this._shareOutputWithPostProcess) {
  71360. return this._shareOutputWithPostProcess.aspectRatio;
  71361. }
  71362. if (this._forcedOutputTexture) {
  71363. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  71364. }
  71365. return this.width / this.height;
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. /**
  71371. * Get a value indicating if the post-process is ready to be used
  71372. * @returns true if the post-process is ready (shader is compiled)
  71373. */
  71374. PostProcess.prototype.isReady = function () {
  71375. return this._effect && this._effect.isReady();
  71376. };
  71377. /**
  71378. * Binds all textures and uniforms to the shader, this will be run on every pass.
  71379. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  71380. */
  71381. PostProcess.prototype.apply = function () {
  71382. // Check
  71383. if (!this._effect || !this._effect.isReady())
  71384. return null;
  71385. // States
  71386. this._engine.enableEffect(this._effect);
  71387. this._engine.setState(false);
  71388. this._engine.setDepthBuffer(false);
  71389. this._engine.setDepthWrite(false);
  71390. // Alpha
  71391. this._engine.setAlphaMode(this.alphaMode);
  71392. if (this.alphaConstants) {
  71393. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  71394. }
  71395. // Bind the output texture of the preivous post process as the input to this post process.
  71396. var source;
  71397. if (this._shareOutputWithPostProcess) {
  71398. source = this._shareOutputWithPostProcess.inputTexture;
  71399. }
  71400. else if (this._forcedOutputTexture) {
  71401. source = this._forcedOutputTexture;
  71402. }
  71403. else {
  71404. source = this.inputTexture;
  71405. }
  71406. this._effect._bindTexture("textureSampler", source);
  71407. // Parameters
  71408. this._effect.setVector2("scale", this._scaleRatio);
  71409. this.onApplyObservable.notifyObservers(this._effect);
  71410. return this._effect;
  71411. };
  71412. PostProcess.prototype._disposeTextures = function () {
  71413. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  71414. return;
  71415. }
  71416. if (this._textures.length > 0) {
  71417. for (var i = 0; i < this._textures.length; i++) {
  71418. this._engine._releaseTexture(this._textures.data[i]);
  71419. }
  71420. }
  71421. this._textures.dispose();
  71422. };
  71423. /**
  71424. * Disposes the post process.
  71425. * @param camera The camera to dispose the post process on.
  71426. */
  71427. PostProcess.prototype.dispose = function (camera) {
  71428. camera = camera || this._camera;
  71429. this._disposeTextures();
  71430. if (this._scene) {
  71431. var index_1 = this._scene.postProcesses.indexOf(this);
  71432. if (index_1 !== -1) {
  71433. this._scene.postProcesses.splice(index_1, 1);
  71434. }
  71435. }
  71436. else {
  71437. var index_2 = this._engine.postProcesses.indexOf(this);
  71438. if (index_2 !== -1) {
  71439. this._engine.postProcesses.splice(index_2, 1);
  71440. }
  71441. }
  71442. if (!camera) {
  71443. return;
  71444. }
  71445. camera.detachPostProcess(this);
  71446. var index = camera._postProcesses.indexOf(this);
  71447. if (index === 0 && camera._postProcesses.length > 0) {
  71448. var firstPostProcess = this._camera._getFirstPostProcess();
  71449. if (firstPostProcess) {
  71450. firstPostProcess.markTextureDirty();
  71451. }
  71452. }
  71453. this.onActivateObservable.clear();
  71454. this.onAfterRenderObservable.clear();
  71455. this.onApplyObservable.clear();
  71456. this.onBeforeRenderObservable.clear();
  71457. this.onSizeChangedObservable.clear();
  71458. };
  71459. return PostProcess;
  71460. }());
  71461. BABYLON.PostProcess = PostProcess;
  71462. })(BABYLON || (BABYLON = {}));
  71463. //# sourceMappingURL=babylon.postProcess.js.map
  71464. var BABYLON;
  71465. (function (BABYLON) {
  71466. var PassPostProcess = /** @class */ (function (_super) {
  71467. __extends(PassPostProcess, _super);
  71468. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71469. if (camera === void 0) { camera = null; }
  71470. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71471. if (blockCompilation === void 0) { blockCompilation = false; }
  71472. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  71473. }
  71474. return PassPostProcess;
  71475. }(BABYLON.PostProcess));
  71476. BABYLON.PassPostProcess = PassPostProcess;
  71477. })(BABYLON || (BABYLON = {}));
  71478. //# sourceMappingURL=babylon.passPostProcess.js.map
  71479. var __assign = (this && this.__assign) || function () {
  71480. __assign = Object.assign || function(t) {
  71481. for (var s, i = 1, n = arguments.length; i < n; i++) {
  71482. s = arguments[i];
  71483. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  71484. t[p] = s[p];
  71485. }
  71486. return t;
  71487. };
  71488. return __assign.apply(this, arguments);
  71489. };
  71490. var BABYLON;
  71491. (function (BABYLON) {
  71492. /**
  71493. * Default implementation IShadowGenerator.
  71494. * This is the main object responsible of generating shadows in the framework.
  71495. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  71496. */
  71497. var ShadowGenerator = /** @class */ (function () {
  71498. /**
  71499. * Creates a ShadowGenerator object.
  71500. * A ShadowGenerator is the required tool to use the shadows.
  71501. * Each light casting shadows needs to use its own ShadowGenerator.
  71502. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  71503. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  71504. * @param light The light object generating the shadows.
  71505. * @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.
  71506. */
  71507. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  71508. this._bias = 0.00005;
  71509. this._normalBias = 0;
  71510. this._blurBoxOffset = 1;
  71511. this._blurScale = 2;
  71512. this._blurKernel = 1;
  71513. this._useKernelBlur = false;
  71514. this._filter = ShadowGenerator.FILTER_NONE;
  71515. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  71516. this._contactHardeningLightSizeUVRatio = 0.1;
  71517. this._darkness = 0;
  71518. this._transparencyShadow = false;
  71519. /**
  71520. * Controls the extent to which the shadows fade out at the edge of the frustum
  71521. * Used only by directionals and spots
  71522. */
  71523. this.frustumEdgeFalloff = 0;
  71524. /**
  71525. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  71526. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  71527. * It might on the other hand introduce peter panning.
  71528. */
  71529. this.forceBackFacesOnly = false;
  71530. this._lightDirection = BABYLON.Vector3.Zero();
  71531. this._viewMatrix = BABYLON.Matrix.Zero();
  71532. this._projectionMatrix = BABYLON.Matrix.Zero();
  71533. this._transformMatrix = BABYLON.Matrix.Zero();
  71534. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71535. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  71536. this._currentFaceIndex = 0;
  71537. this._currentFaceIndexCache = 0;
  71538. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  71539. this._mapSize = mapSize;
  71540. this._light = light;
  71541. this._scene = light.getScene();
  71542. light._shadowGenerator = this;
  71543. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  71544. if (!component) {
  71545. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  71546. this._scene._addComponent(component);
  71547. }
  71548. // Texture type fallback from float to int if not supported.
  71549. var caps = this._scene.getEngine().getCaps();
  71550. if (!useFullFloatFirst) {
  71551. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71552. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71553. }
  71554. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71555. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71556. }
  71557. else {
  71558. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71559. }
  71560. }
  71561. else {
  71562. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  71563. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71564. }
  71565. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  71566. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71567. }
  71568. else {
  71569. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71570. }
  71571. }
  71572. this._initializeGenerator();
  71573. this._applyFilterValues();
  71574. }
  71575. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  71576. /**
  71577. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  71578. */
  71579. get: function () {
  71580. return this._bias;
  71581. },
  71582. /**
  71583. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  71584. */
  71585. set: function (bias) {
  71586. this._bias = bias;
  71587. },
  71588. enumerable: true,
  71589. configurable: true
  71590. });
  71591. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  71592. /**
  71593. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71594. */
  71595. get: function () {
  71596. return this._normalBias;
  71597. },
  71598. /**
  71599. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  71600. */
  71601. set: function (normalBias) {
  71602. this._normalBias = normalBias;
  71603. },
  71604. enumerable: true,
  71605. configurable: true
  71606. });
  71607. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  71608. /**
  71609. * Gets the blur box offset: offset applied during the blur pass.
  71610. * Only usefull if useKernelBlur = false
  71611. */
  71612. get: function () {
  71613. return this._blurBoxOffset;
  71614. },
  71615. /**
  71616. * Sets the blur box offset: offset applied during the blur pass.
  71617. * Only usefull if useKernelBlur = false
  71618. */
  71619. set: function (value) {
  71620. if (this._blurBoxOffset === value) {
  71621. return;
  71622. }
  71623. this._blurBoxOffset = value;
  71624. this._disposeBlurPostProcesses();
  71625. },
  71626. enumerable: true,
  71627. configurable: true
  71628. });
  71629. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  71630. /**
  71631. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  71632. * 2 means half of the size.
  71633. */
  71634. get: function () {
  71635. return this._blurScale;
  71636. },
  71637. /**
  71638. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  71639. * 2 means half of the size.
  71640. */
  71641. set: function (value) {
  71642. if (this._blurScale === value) {
  71643. return;
  71644. }
  71645. this._blurScale = value;
  71646. this._disposeBlurPostProcesses();
  71647. },
  71648. enumerable: true,
  71649. configurable: true
  71650. });
  71651. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  71652. /**
  71653. * Gets the blur kernel: kernel size of the blur pass.
  71654. * Only usefull if useKernelBlur = true
  71655. */
  71656. get: function () {
  71657. return this._blurKernel;
  71658. },
  71659. /**
  71660. * Sets the blur kernel: kernel size of the blur pass.
  71661. * Only usefull if useKernelBlur = true
  71662. */
  71663. set: function (value) {
  71664. if (this._blurKernel === value) {
  71665. return;
  71666. }
  71667. this._blurKernel = value;
  71668. this._disposeBlurPostProcesses();
  71669. },
  71670. enumerable: true,
  71671. configurable: true
  71672. });
  71673. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  71674. /**
  71675. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  71676. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  71677. */
  71678. get: function () {
  71679. return this._useKernelBlur;
  71680. },
  71681. /**
  71682. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  71683. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  71684. */
  71685. set: function (value) {
  71686. if (this._useKernelBlur === value) {
  71687. return;
  71688. }
  71689. this._useKernelBlur = value;
  71690. this._disposeBlurPostProcesses();
  71691. },
  71692. enumerable: true,
  71693. configurable: true
  71694. });
  71695. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  71696. /**
  71697. * Gets the depth scale used in ESM mode.
  71698. */
  71699. get: function () {
  71700. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  71701. },
  71702. /**
  71703. * Sets the depth scale used in ESM mode.
  71704. * This can override the scale stored on the light.
  71705. */
  71706. set: function (value) {
  71707. this._depthScale = value;
  71708. },
  71709. enumerable: true,
  71710. configurable: true
  71711. });
  71712. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  71713. /**
  71714. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  71715. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  71716. */
  71717. get: function () {
  71718. return this._filter;
  71719. },
  71720. /**
  71721. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  71722. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  71723. */
  71724. set: function (value) {
  71725. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  71726. if (this._light.needCube()) {
  71727. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  71728. this.useExponentialShadowMap = true;
  71729. return;
  71730. }
  71731. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  71732. this.useCloseExponentialShadowMap = true;
  71733. return;
  71734. }
  71735. // PCF on cubemap would also be expensive
  71736. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  71737. this.usePoissonSampling = true;
  71738. return;
  71739. }
  71740. }
  71741. // Weblg1 fallback for PCF.
  71742. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  71743. if (this._scene.getEngine().webGLVersion === 1) {
  71744. this.usePoissonSampling = true;
  71745. return;
  71746. }
  71747. }
  71748. if (this._filter === value) {
  71749. return;
  71750. }
  71751. this._filter = value;
  71752. this._disposeBlurPostProcesses();
  71753. this._applyFilterValues();
  71754. this._light._markMeshesAsLightDirty();
  71755. },
  71756. enumerable: true,
  71757. configurable: true
  71758. });
  71759. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  71760. /**
  71761. * Gets if the current filter is set to Poisson Sampling.
  71762. */
  71763. get: function () {
  71764. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  71765. },
  71766. /**
  71767. * Sets the current filter to Poisson Sampling.
  71768. */
  71769. set: function (value) {
  71770. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  71771. return;
  71772. }
  71773. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  71774. },
  71775. enumerable: true,
  71776. configurable: true
  71777. });
  71778. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  71779. /**
  71780. * Gets if the current filter is set to VSM.
  71781. * DEPRECATED. Should use useExponentialShadowMap instead.
  71782. */
  71783. get: function () {
  71784. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  71785. return this.useExponentialShadowMap;
  71786. },
  71787. /**
  71788. * Sets the current filter is to VSM.
  71789. * DEPRECATED. Should use useExponentialShadowMap instead.
  71790. */
  71791. set: function (value) {
  71792. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  71793. this.useExponentialShadowMap = value;
  71794. },
  71795. enumerable: true,
  71796. configurable: true
  71797. });
  71798. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  71799. /**
  71800. * Gets if the current filter is set to blurred VSM.
  71801. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  71802. */
  71803. get: function () {
  71804. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  71805. return this.useBlurExponentialShadowMap;
  71806. },
  71807. /**
  71808. * Sets the current filter is to blurred VSM.
  71809. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  71810. */
  71811. set: function (value) {
  71812. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  71813. this.useBlurExponentialShadowMap = value;
  71814. },
  71815. enumerable: true,
  71816. configurable: true
  71817. });
  71818. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  71819. /**
  71820. * Gets if the current filter is set to ESM.
  71821. */
  71822. get: function () {
  71823. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  71824. },
  71825. /**
  71826. * Sets the current filter is to ESM.
  71827. */
  71828. set: function (value) {
  71829. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  71830. return;
  71831. }
  71832. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71833. },
  71834. enumerable: true,
  71835. configurable: true
  71836. });
  71837. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  71838. /**
  71839. * Gets if the current filter is set to filtered ESM.
  71840. */
  71841. get: function () {
  71842. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  71843. },
  71844. /**
  71845. * Gets if the current filter is set to filtered ESM.
  71846. */
  71847. set: function (value) {
  71848. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  71849. return;
  71850. }
  71851. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71852. },
  71853. enumerable: true,
  71854. configurable: true
  71855. });
  71856. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  71857. /**
  71858. * Gets if the current filter is set to "close ESM" (using the inverse of the
  71859. * exponential to prevent steep falloff artifacts).
  71860. */
  71861. get: function () {
  71862. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  71863. },
  71864. /**
  71865. * Sets the current filter to "close ESM" (using the inverse of the
  71866. * exponential to prevent steep falloff artifacts).
  71867. */
  71868. set: function (value) {
  71869. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  71870. return;
  71871. }
  71872. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71873. },
  71874. enumerable: true,
  71875. configurable: true
  71876. });
  71877. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  71878. /**
  71879. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  71880. * exponential to prevent steep falloff artifacts).
  71881. */
  71882. get: function () {
  71883. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  71884. },
  71885. /**
  71886. * Sets the current filter to filtered "close ESM" (using the inverse of the
  71887. * exponential to prevent steep falloff artifacts).
  71888. */
  71889. set: function (value) {
  71890. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  71891. return;
  71892. }
  71893. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  71894. },
  71895. enumerable: true,
  71896. configurable: true
  71897. });
  71898. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  71899. /**
  71900. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  71901. */
  71902. get: function () {
  71903. return this.filter === ShadowGenerator.FILTER_PCF;
  71904. },
  71905. /**
  71906. * Sets the current filter to "PCF" (percentage closer filtering).
  71907. */
  71908. set: function (value) {
  71909. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  71910. return;
  71911. }
  71912. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  71913. },
  71914. enumerable: true,
  71915. configurable: true
  71916. });
  71917. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  71918. /**
  71919. * Gets the PCF or PCSS Quality.
  71920. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  71921. */
  71922. get: function () {
  71923. return this._filteringQuality;
  71924. },
  71925. /**
  71926. * Sets the PCF or PCSS Quality.
  71927. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  71928. */
  71929. set: function (filteringQuality) {
  71930. this._filteringQuality = filteringQuality;
  71931. },
  71932. enumerable: true,
  71933. configurable: true
  71934. });
  71935. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  71936. /**
  71937. * Gets if the current filter is set to "PCSS" (contact hardening).
  71938. */
  71939. get: function () {
  71940. return this.filter === ShadowGenerator.FILTER_PCSS;
  71941. },
  71942. /**
  71943. * Sets the current filter to "PCSS" (contact hardening).
  71944. */
  71945. set: function (value) {
  71946. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  71947. return;
  71948. }
  71949. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  71950. },
  71951. enumerable: true,
  71952. configurable: true
  71953. });
  71954. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  71955. /**
  71956. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  71957. * Using a ratio helps keeping shape stability independently of the map size.
  71958. *
  71959. * It does not account for the light projection as it was having too much
  71960. * instability during the light setup or during light position changes.
  71961. *
  71962. * Only valid if useContactHardeningShadow is true.
  71963. */
  71964. get: function () {
  71965. return this._contactHardeningLightSizeUVRatio;
  71966. },
  71967. /**
  71968. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  71969. * Using a ratio helps keeping shape stability independently of the map size.
  71970. *
  71971. * It does not account for the light projection as it was having too much
  71972. * instability during the light setup or during light position changes.
  71973. *
  71974. * Only valid if useContactHardeningShadow is true.
  71975. */
  71976. set: function (contactHardeningLightSizeUVRatio) {
  71977. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  71978. },
  71979. enumerable: true,
  71980. configurable: true
  71981. });
  71982. /**
  71983. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  71984. * 0 means strongest and 1 would means no shadow.
  71985. * @returns the darkness.
  71986. */
  71987. ShadowGenerator.prototype.getDarkness = function () {
  71988. return this._darkness;
  71989. };
  71990. /**
  71991. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  71992. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  71993. * @returns the shadow generator allowing fluent coding.
  71994. */
  71995. ShadowGenerator.prototype.setDarkness = function (darkness) {
  71996. if (darkness >= 1.0)
  71997. this._darkness = 1.0;
  71998. else if (darkness <= 0.0)
  71999. this._darkness = 0.0;
  72000. else
  72001. this._darkness = darkness;
  72002. return this;
  72003. };
  72004. /**
  72005. * Sets the ability to have transparent shadow (boolean).
  72006. * @param transparent True if transparent else False
  72007. * @returns the shadow generator allowing fluent coding
  72008. */
  72009. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  72010. this._transparencyShadow = transparent;
  72011. return this;
  72012. };
  72013. /**
  72014. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  72015. * @returns The render target texture if present otherwise, null
  72016. */
  72017. ShadowGenerator.prototype.getShadowMap = function () {
  72018. return this._shadowMap;
  72019. };
  72020. /**
  72021. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  72022. * @returns The render target texture if the shadow map is present otherwise, null
  72023. */
  72024. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  72025. if (this._shadowMap2) {
  72026. return this._shadowMap2;
  72027. }
  72028. return this._shadowMap;
  72029. };
  72030. /**
  72031. * Helper function to add a mesh and its descendants to the list of shadow casters.
  72032. * @param mesh Mesh to add
  72033. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  72034. * @returns the Shadow Generator itself
  72035. */
  72036. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  72037. if (includeDescendants === void 0) { includeDescendants = true; }
  72038. var _a;
  72039. if (!this._shadowMap) {
  72040. return this;
  72041. }
  72042. if (!this._shadowMap.renderList) {
  72043. this._shadowMap.renderList = [];
  72044. }
  72045. this._shadowMap.renderList.push(mesh);
  72046. if (includeDescendants) {
  72047. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  72048. }
  72049. return this;
  72050. };
  72051. /**
  72052. * Helper function to remove a mesh and its descendants from the list of shadow casters
  72053. * @param mesh Mesh to remove
  72054. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  72055. * @returns the Shadow Generator itself
  72056. */
  72057. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  72058. if (includeDescendants === void 0) { includeDescendants = true; }
  72059. if (!this._shadowMap || !this._shadowMap.renderList) {
  72060. return this;
  72061. }
  72062. var index = this._shadowMap.renderList.indexOf(mesh);
  72063. if (index !== -1) {
  72064. this._shadowMap.renderList.splice(index, 1);
  72065. }
  72066. if (includeDescendants) {
  72067. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  72068. var child = _a[_i];
  72069. this.removeShadowCaster(child);
  72070. }
  72071. }
  72072. return this;
  72073. };
  72074. /**
  72075. * Returns the associated light object.
  72076. * @returns the light generating the shadow
  72077. */
  72078. ShadowGenerator.prototype.getLight = function () {
  72079. return this._light;
  72080. };
  72081. ShadowGenerator.prototype._initializeGenerator = function () {
  72082. this._light._markMeshesAsLightDirty();
  72083. this._initializeShadowMap();
  72084. };
  72085. ShadowGenerator.prototype._initializeShadowMap = function () {
  72086. var _this = this;
  72087. // Render target
  72088. var engine = this._scene.getEngine();
  72089. if (engine.webGLVersion > 1) {
  72090. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  72091. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  72092. }
  72093. else {
  72094. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  72095. }
  72096. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72097. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72098. this._shadowMap.anisotropicFilteringLevel = 1;
  72099. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72100. this._shadowMap.renderParticles = false;
  72101. this._shadowMap.ignoreCameraViewport = true;
  72102. // Record Face Index before render.
  72103. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  72104. _this._currentFaceIndex = faceIndex;
  72105. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72106. engine.setColorWrite(false);
  72107. }
  72108. });
  72109. // Custom render function.
  72110. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  72111. // Blur if required afer render.
  72112. this._shadowMap.onAfterUnbindObservable.add(function () {
  72113. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72114. engine.setColorWrite(true);
  72115. }
  72116. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  72117. return;
  72118. }
  72119. var shadowMap = _this.getShadowMapForRendering();
  72120. if (shadowMap) {
  72121. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  72122. }
  72123. });
  72124. // Clear according to the chosen filter.
  72125. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  72126. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  72127. this._shadowMap.onClearObservable.add(function (engine) {
  72128. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  72129. engine.clear(clearOne, false, true, false);
  72130. }
  72131. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  72132. engine.clear(clearZero, true, true, false);
  72133. }
  72134. else {
  72135. engine.clear(clearOne, true, true, false);
  72136. }
  72137. });
  72138. };
  72139. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  72140. var _this = this;
  72141. var engine = this._scene.getEngine();
  72142. var targetSize = this._mapSize / this.blurScale;
  72143. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  72144. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  72145. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72146. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72147. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72148. }
  72149. if (this.useKernelBlur) {
  72150. 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);
  72151. this._kernelBlurXPostprocess.width = targetSize;
  72152. this._kernelBlurXPostprocess.height = targetSize;
  72153. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  72154. effect.setTexture("textureSampler", _this._shadowMap);
  72155. });
  72156. 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);
  72157. this._kernelBlurXPostprocess.autoClear = false;
  72158. this._kernelBlurYPostprocess.autoClear = false;
  72159. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72160. this._kernelBlurXPostprocess.packedFloat = true;
  72161. this._kernelBlurYPostprocess.packedFloat = true;
  72162. }
  72163. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  72164. }
  72165. else {
  72166. 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);
  72167. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  72168. effect.setFloat2("screenSize", targetSize, targetSize);
  72169. effect.setTexture("textureSampler", _this._shadowMap);
  72170. });
  72171. this._boxBlurPostprocess.autoClear = false;
  72172. this._blurPostProcesses = [this._boxBlurPostprocess];
  72173. }
  72174. };
  72175. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72176. var index;
  72177. var engine = this._scene.getEngine();
  72178. if (depthOnlySubMeshes.length) {
  72179. engine.setColorWrite(false);
  72180. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72181. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  72182. }
  72183. engine.setColorWrite(true);
  72184. }
  72185. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72186. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  72187. }
  72188. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72189. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  72190. }
  72191. if (this._transparencyShadow) {
  72192. for (index = 0; index < transparentSubMeshes.length; index++) {
  72193. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  72194. }
  72195. }
  72196. };
  72197. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  72198. var _this = this;
  72199. var mesh = subMesh.getRenderingMesh();
  72200. var scene = this._scene;
  72201. var engine = scene.getEngine();
  72202. var material = subMesh.getMaterial();
  72203. if (!material) {
  72204. return;
  72205. }
  72206. // Culling
  72207. engine.setState(material.backFaceCulling);
  72208. // Managing instances
  72209. var batch = mesh._getInstancesRenderList(subMesh._id);
  72210. if (batch.mustReturn) {
  72211. return;
  72212. }
  72213. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72214. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  72215. engine.enableEffect(this._effect);
  72216. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  72217. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  72218. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  72219. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72220. this._effect.setVector3("lightData", this._cachedDirection);
  72221. }
  72222. else {
  72223. this._effect.setVector3("lightData", this._cachedPosition);
  72224. }
  72225. if (scene.activeCamera) {
  72226. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  72227. }
  72228. // Alpha test
  72229. if (material && material.needAlphaTesting()) {
  72230. var alphaTexture = material.getAlphaTestTexture();
  72231. if (alphaTexture) {
  72232. this._effect.setTexture("diffuseSampler", alphaTexture);
  72233. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  72234. }
  72235. }
  72236. // Bones
  72237. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72238. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  72239. }
  72240. // Morph targets
  72241. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  72242. if (this.forceBackFacesOnly) {
  72243. engine.setState(true, 0, false, true);
  72244. }
  72245. // Draw
  72246. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72247. if (this.forceBackFacesOnly) {
  72248. engine.setState(true, 0, false, false);
  72249. }
  72250. }
  72251. else {
  72252. // Need to reset refresh rate of the shadowMap
  72253. if (this._shadowMap) {
  72254. this._shadowMap.resetRefreshCounter();
  72255. }
  72256. }
  72257. };
  72258. ShadowGenerator.prototype._applyFilterValues = function () {
  72259. if (!this._shadowMap) {
  72260. return;
  72261. }
  72262. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  72263. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  72264. }
  72265. else {
  72266. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72267. }
  72268. };
  72269. /**
  72270. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72271. * @param onCompiled Callback triggered at the and of the effects compilation
  72272. * @param options Sets of optional options forcing the compilation with different modes
  72273. */
  72274. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  72275. var _this = this;
  72276. var localOptions = __assign({ useInstances: false }, options);
  72277. var shadowMap = this.getShadowMap();
  72278. if (!shadowMap) {
  72279. if (onCompiled) {
  72280. onCompiled(this);
  72281. }
  72282. return;
  72283. }
  72284. var renderList = shadowMap.renderList;
  72285. if (!renderList) {
  72286. if (onCompiled) {
  72287. onCompiled(this);
  72288. }
  72289. return;
  72290. }
  72291. var subMeshes = new Array();
  72292. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  72293. var mesh = renderList_1[_i];
  72294. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  72295. }
  72296. if (subMeshes.length === 0) {
  72297. if (onCompiled) {
  72298. onCompiled(this);
  72299. }
  72300. return;
  72301. }
  72302. var currentIndex = 0;
  72303. var checkReady = function () {
  72304. if (!_this._scene || !_this._scene.getEngine()) {
  72305. return;
  72306. }
  72307. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  72308. currentIndex++;
  72309. if (currentIndex >= subMeshes.length) {
  72310. if (onCompiled) {
  72311. onCompiled(_this);
  72312. }
  72313. return;
  72314. }
  72315. }
  72316. setTimeout(checkReady, 16);
  72317. };
  72318. checkReady();
  72319. };
  72320. /**
  72321. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  72322. * @param options Sets of optional options forcing the compilation with different modes
  72323. * @returns A promise that resolves when the compilation completes
  72324. */
  72325. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  72326. var _this = this;
  72327. return new Promise(function (resolve) {
  72328. _this.forceCompilation(function () {
  72329. resolve();
  72330. }, options);
  72331. });
  72332. };
  72333. /**
  72334. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  72335. * @param subMesh The submesh we want to render in the shadow map
  72336. * @param useInstances Defines wether will draw in the map using instances
  72337. * @returns true if ready otherwise, false
  72338. */
  72339. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  72340. var defines = [];
  72341. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  72342. defines.push("#define FLOAT");
  72343. }
  72344. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72345. defines.push("#define ESM");
  72346. }
  72347. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  72348. defines.push("#define DEPTHTEXTURE");
  72349. }
  72350. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72351. var mesh = subMesh.getMesh();
  72352. var material = subMesh.getMaterial();
  72353. // Normal bias.
  72354. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  72355. attribs.push(BABYLON.VertexBuffer.NormalKind);
  72356. defines.push("#define NORMAL");
  72357. if (mesh.nonUniformScaling) {
  72358. defines.push("#define NONUNIFORMSCALING");
  72359. }
  72360. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  72361. defines.push("#define DIRECTIONINLIGHTDATA");
  72362. }
  72363. }
  72364. // Alpha test
  72365. if (material && material.needAlphaTesting()) {
  72366. var alphaTexture = material.getAlphaTestTexture();
  72367. if (alphaTexture) {
  72368. defines.push("#define ALPHATEST");
  72369. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72370. attribs.push(BABYLON.VertexBuffer.UVKind);
  72371. defines.push("#define UV1");
  72372. }
  72373. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72374. if (alphaTexture.coordinatesIndex === 1) {
  72375. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72376. defines.push("#define UV2");
  72377. }
  72378. }
  72379. }
  72380. }
  72381. // Bones
  72382. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72383. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72384. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72385. if (mesh.numBoneInfluencers > 4) {
  72386. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72387. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72388. }
  72389. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72390. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  72391. }
  72392. else {
  72393. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72394. }
  72395. // Morph targets
  72396. var manager = mesh.morphTargetManager;
  72397. var morphInfluencers = 0;
  72398. if (manager) {
  72399. if (manager.numInfluencers > 0) {
  72400. defines.push("#define MORPHTARGETS");
  72401. morphInfluencers = manager.numInfluencers;
  72402. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  72403. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  72404. }
  72405. }
  72406. // Instances
  72407. if (useInstances) {
  72408. defines.push("#define INSTANCES");
  72409. attribs.push("world0");
  72410. attribs.push("world1");
  72411. attribs.push("world2");
  72412. attribs.push("world3");
  72413. }
  72414. // Get correct effect
  72415. var join = defines.join("\n");
  72416. if (this._cachedDefines !== join) {
  72417. this._cachedDefines = join;
  72418. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  72419. }
  72420. if (!this._effect.isReady()) {
  72421. return false;
  72422. }
  72423. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72424. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  72425. this._initializeBlurRTTAndPostProcesses();
  72426. }
  72427. }
  72428. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  72429. return false;
  72430. }
  72431. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  72432. return false;
  72433. }
  72434. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  72435. return false;
  72436. }
  72437. return true;
  72438. };
  72439. /**
  72440. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  72441. * @param defines Defines of the material we want to update
  72442. * @param lightIndex Index of the light in the enabled light list of the material
  72443. */
  72444. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  72445. var scene = this._scene;
  72446. var light = this._light;
  72447. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72448. return;
  72449. }
  72450. defines["SHADOW" + lightIndex] = true;
  72451. if (this.useContactHardeningShadow) {
  72452. defines["SHADOWPCSS" + lightIndex] = true;
  72453. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72454. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72455. }
  72456. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72457. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72458. }
  72459. // else default to high.
  72460. }
  72461. if (this.usePercentageCloserFiltering) {
  72462. defines["SHADOWPCF" + lightIndex] = true;
  72463. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  72464. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  72465. }
  72466. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  72467. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  72468. }
  72469. // else default to high.
  72470. }
  72471. else if (this.usePoissonSampling) {
  72472. defines["SHADOWPOISSON" + lightIndex] = true;
  72473. }
  72474. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  72475. defines["SHADOWESM" + lightIndex] = true;
  72476. }
  72477. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  72478. defines["SHADOWCLOSEESM" + lightIndex] = true;
  72479. }
  72480. if (light.needCube()) {
  72481. defines["SHADOWCUBE" + lightIndex] = true;
  72482. }
  72483. };
  72484. /**
  72485. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  72486. * defined in the generator but impacting the effect).
  72487. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  72488. * @param effect The effect we are binfing the information for
  72489. */
  72490. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  72491. var light = this._light;
  72492. var scene = this._scene;
  72493. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  72494. return;
  72495. }
  72496. var camera = scene.activeCamera;
  72497. if (!camera) {
  72498. return;
  72499. }
  72500. var shadowMap = this.getShadowMap();
  72501. if (!shadowMap) {
  72502. return;
  72503. }
  72504. if (!light.needCube()) {
  72505. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  72506. }
  72507. // Only PCF uses depth stencil texture.
  72508. if (this._filter === ShadowGenerator.FILTER_PCF) {
  72509. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72510. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72511. }
  72512. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  72513. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72514. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  72515. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  72516. }
  72517. else {
  72518. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  72519. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  72520. }
  72521. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  72522. };
  72523. /**
  72524. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  72525. * (eq to shadow prjection matrix * light transform matrix)
  72526. * @returns The transform matrix used to create the shadow map
  72527. */
  72528. ShadowGenerator.prototype.getTransformMatrix = function () {
  72529. var scene = this._scene;
  72530. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  72531. return this._transformMatrix;
  72532. }
  72533. this._currentRenderID = scene.getRenderId();
  72534. this._currentFaceIndexCache = this._currentFaceIndex;
  72535. var lightPosition = this._light.position;
  72536. if (this._light.computeTransformedInformation()) {
  72537. lightPosition = this._light.transformedPosition;
  72538. }
  72539. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  72540. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  72541. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  72542. }
  72543. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  72544. this._cachedPosition.copyFrom(lightPosition);
  72545. this._cachedDirection.copyFrom(this._lightDirection);
  72546. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  72547. var shadowMap = this.getShadowMap();
  72548. if (shadowMap) {
  72549. var renderList = shadowMap.renderList;
  72550. if (renderList) {
  72551. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  72552. }
  72553. }
  72554. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  72555. }
  72556. return this._transformMatrix;
  72557. };
  72558. /**
  72559. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  72560. * Cube and 2D textures for instance.
  72561. */
  72562. ShadowGenerator.prototype.recreateShadowMap = function () {
  72563. var shadowMap = this._shadowMap;
  72564. if (!shadowMap) {
  72565. return;
  72566. }
  72567. // Track render list.
  72568. var renderList = shadowMap.renderList;
  72569. // Clean up existing data.
  72570. this._disposeRTTandPostProcesses();
  72571. // Reinitializes.
  72572. this._initializeGenerator();
  72573. // Reaffect the filter to ensure a correct fallback if necessary.
  72574. this.filter = this.filter;
  72575. // Reaffect the filter.
  72576. this._applyFilterValues();
  72577. // Reaffect Render List.
  72578. this._shadowMap.renderList = renderList;
  72579. };
  72580. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  72581. if (this._shadowMap2) {
  72582. this._shadowMap2.dispose();
  72583. this._shadowMap2 = null;
  72584. }
  72585. if (this._boxBlurPostprocess) {
  72586. this._boxBlurPostprocess.dispose();
  72587. this._boxBlurPostprocess = null;
  72588. }
  72589. if (this._kernelBlurXPostprocess) {
  72590. this._kernelBlurXPostprocess.dispose();
  72591. this._kernelBlurXPostprocess = null;
  72592. }
  72593. if (this._kernelBlurYPostprocess) {
  72594. this._kernelBlurYPostprocess.dispose();
  72595. this._kernelBlurYPostprocess = null;
  72596. }
  72597. this._blurPostProcesses = [];
  72598. };
  72599. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  72600. if (this._shadowMap) {
  72601. this._shadowMap.dispose();
  72602. this._shadowMap = null;
  72603. }
  72604. this._disposeBlurPostProcesses();
  72605. };
  72606. /**
  72607. * Disposes the ShadowGenerator.
  72608. * Returns nothing.
  72609. */
  72610. ShadowGenerator.prototype.dispose = function () {
  72611. this._disposeRTTandPostProcesses();
  72612. if (this._light) {
  72613. this._light._shadowGenerator = null;
  72614. this._light._markMeshesAsLightDirty();
  72615. }
  72616. };
  72617. /**
  72618. * Serializes the shadow generator setup to a json object.
  72619. * @returns The serialized JSON object
  72620. */
  72621. ShadowGenerator.prototype.serialize = function () {
  72622. var serializationObject = {};
  72623. var shadowMap = this.getShadowMap();
  72624. if (!shadowMap) {
  72625. return serializationObject;
  72626. }
  72627. serializationObject.lightId = this._light.id;
  72628. serializationObject.mapSize = shadowMap.getRenderSize();
  72629. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  72630. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  72631. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  72632. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  72633. serializationObject.usePoissonSampling = this.usePoissonSampling;
  72634. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  72635. serializationObject.depthScale = this.depthScale;
  72636. serializationObject.darkness = this.getDarkness();
  72637. serializationObject.blurBoxOffset = this.blurBoxOffset;
  72638. serializationObject.blurKernel = this.blurKernel;
  72639. serializationObject.blurScale = this.blurScale;
  72640. serializationObject.useKernelBlur = this.useKernelBlur;
  72641. serializationObject.transparencyShadow = this._transparencyShadow;
  72642. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  72643. serializationObject.bias = this.bias;
  72644. serializationObject.normalBias = this.normalBias;
  72645. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  72646. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  72647. serializationObject.filteringQuality = this.filteringQuality;
  72648. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  72649. serializationObject.renderList = [];
  72650. if (shadowMap.renderList) {
  72651. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  72652. var mesh = shadowMap.renderList[meshIndex];
  72653. serializationObject.renderList.push(mesh.id);
  72654. }
  72655. }
  72656. return serializationObject;
  72657. };
  72658. /**
  72659. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  72660. * @param parsedShadowGenerator The JSON object to parse
  72661. * @param scene The scene to create the shadow map for
  72662. * @returns The parsed shadow generator
  72663. */
  72664. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  72665. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  72666. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  72667. var shadowMap = shadowGenerator.getShadowMap();
  72668. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  72669. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  72670. meshes.forEach(function (mesh) {
  72671. if (!shadowMap) {
  72672. return;
  72673. }
  72674. if (!shadowMap.renderList) {
  72675. shadowMap.renderList = [];
  72676. }
  72677. shadowMap.renderList.push(mesh);
  72678. });
  72679. }
  72680. if (parsedShadowGenerator.usePoissonSampling) {
  72681. shadowGenerator.usePoissonSampling = true;
  72682. }
  72683. else if (parsedShadowGenerator.useExponentialShadowMap) {
  72684. shadowGenerator.useExponentialShadowMap = true;
  72685. }
  72686. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  72687. shadowGenerator.useBlurExponentialShadowMap = true;
  72688. }
  72689. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  72690. shadowGenerator.useCloseExponentialShadowMap = true;
  72691. }
  72692. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  72693. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  72694. }
  72695. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  72696. shadowGenerator.usePercentageCloserFiltering = true;
  72697. }
  72698. else if (parsedShadowGenerator.useContactHardeningShadow) {
  72699. shadowGenerator.useContactHardeningShadow = true;
  72700. }
  72701. if (parsedShadowGenerator.filteringQuality) {
  72702. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  72703. }
  72704. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  72705. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  72706. }
  72707. // Backward compat
  72708. else if (parsedShadowGenerator.useVarianceShadowMap) {
  72709. shadowGenerator.useExponentialShadowMap = true;
  72710. }
  72711. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  72712. shadowGenerator.useBlurExponentialShadowMap = true;
  72713. }
  72714. if (parsedShadowGenerator.depthScale) {
  72715. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  72716. }
  72717. if (parsedShadowGenerator.blurScale) {
  72718. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  72719. }
  72720. if (parsedShadowGenerator.blurBoxOffset) {
  72721. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  72722. }
  72723. if (parsedShadowGenerator.useKernelBlur) {
  72724. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  72725. }
  72726. if (parsedShadowGenerator.blurKernel) {
  72727. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  72728. }
  72729. if (parsedShadowGenerator.bias !== undefined) {
  72730. shadowGenerator.bias = parsedShadowGenerator.bias;
  72731. }
  72732. if (parsedShadowGenerator.normalBias !== undefined) {
  72733. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  72734. }
  72735. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  72736. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  72737. }
  72738. if (parsedShadowGenerator.darkness) {
  72739. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  72740. }
  72741. if (parsedShadowGenerator.transparencyShadow) {
  72742. shadowGenerator.setTransparencyShadow(true);
  72743. }
  72744. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  72745. return shadowGenerator;
  72746. };
  72747. /**
  72748. * Shadow generator mode None: no filtering applied.
  72749. */
  72750. ShadowGenerator.FILTER_NONE = 0;
  72751. /**
  72752. * Shadow generator mode ESM: Exponential Shadow Mapping.
  72753. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72754. */
  72755. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  72756. /**
  72757. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  72758. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  72759. */
  72760. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  72761. /**
  72762. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  72763. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72764. */
  72765. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  72766. /**
  72767. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  72768. * edge artifacts on steep falloff.
  72769. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72770. */
  72771. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  72772. /**
  72773. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  72774. * edge artifacts on steep falloff.
  72775. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  72776. */
  72777. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  72778. /**
  72779. * Shadow generator mode PCF: Percentage Closer Filtering
  72780. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  72781. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  72782. */
  72783. ShadowGenerator.FILTER_PCF = 6;
  72784. /**
  72785. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  72786. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  72787. * Contact Hardening
  72788. */
  72789. ShadowGenerator.FILTER_PCSS = 7;
  72790. /**
  72791. * Reserved for PCF and PCSS
  72792. * Highest Quality.
  72793. *
  72794. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  72795. *
  72796. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  72797. */
  72798. ShadowGenerator.QUALITY_HIGH = 0;
  72799. /**
  72800. * Reserved for PCF and PCSS
  72801. * Good tradeoff for quality/perf cross devices
  72802. *
  72803. * Execute PCF on a 3*3 kernel.
  72804. *
  72805. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  72806. */
  72807. ShadowGenerator.QUALITY_MEDIUM = 1;
  72808. /**
  72809. * Reserved for PCF and PCSS
  72810. * The lowest quality but the fastest.
  72811. *
  72812. * Execute PCF on a 1*1 kernel.
  72813. *
  72814. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  72815. */
  72816. ShadowGenerator.QUALITY_LOW = 2;
  72817. return ShadowGenerator;
  72818. }());
  72819. BABYLON.ShadowGenerator = ShadowGenerator;
  72820. })(BABYLON || (BABYLON = {}));
  72821. //# sourceMappingURL=babylon.shadowGenerator.js.map
  72822. var BABYLON;
  72823. (function (BABYLON) {
  72824. // Adds the parser to the scene parsers.
  72825. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  72826. // Shadows
  72827. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  72828. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  72829. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  72830. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  72831. // SG would be available on their associated lights
  72832. }
  72833. }
  72834. });
  72835. /**
  72836. * Defines the shadow generator component responsible to manage any shadow generators
  72837. * in a given scene.
  72838. */
  72839. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  72840. /**
  72841. * Creates a new instance of the component for the given scene
  72842. * @param scene Defines the scene to register the component in
  72843. */
  72844. function ShadowGeneratorSceneComponent(scene) {
  72845. /**
  72846. * The component name helpfull to identify the component in the list of scene components.
  72847. */
  72848. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  72849. this.scene = scene;
  72850. }
  72851. /**
  72852. * Registers the component in a given scene
  72853. */
  72854. ShadowGeneratorSceneComponent.prototype.register = function () {
  72855. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  72856. };
  72857. /**
  72858. * Rebuilds the elements related to this component in case of
  72859. * context lost for instance.
  72860. */
  72861. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  72862. // Nothing To Do Here.
  72863. };
  72864. /**
  72865. * Serializes the component data to the specified json object
  72866. * @param serializationObject The object to serialize to
  72867. */
  72868. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  72869. // Shadows
  72870. serializationObject.shadowGenerators = [];
  72871. var lights = this.scene.lights;
  72872. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  72873. var light = lights_1[_i];
  72874. var shadowGenerator = light.getShadowGenerator();
  72875. if (shadowGenerator) {
  72876. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  72877. }
  72878. }
  72879. };
  72880. /**
  72881. * Adds all the element from the container to the scene
  72882. * @param container the container holding the elements
  72883. */
  72884. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  72885. // Nothing To Do Here. (directly attached to a light)
  72886. };
  72887. /**
  72888. * Removes all the elements in the container from the scene
  72889. * @param container contains the elements to remove
  72890. */
  72891. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  72892. // Nothing To Do Here. (directly attached to a light)
  72893. };
  72894. /**
  72895. * Rebuilds the elements related to this component in case of
  72896. * context lost for instance.
  72897. */
  72898. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  72899. // Nothing To Do Here.
  72900. };
  72901. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  72902. // Shadows
  72903. var scene = this.scene;
  72904. if (this.scene.shadowsEnabled) {
  72905. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  72906. var light = scene.lights[lightIndex];
  72907. var shadowGenerator = light.getShadowGenerator();
  72908. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  72909. var shadowMap = (shadowGenerator.getShadowMap());
  72910. if (scene.textures.indexOf(shadowMap) !== -1) {
  72911. renderTargets.push(shadowMap);
  72912. }
  72913. }
  72914. }
  72915. }
  72916. };
  72917. return ShadowGeneratorSceneComponent;
  72918. }());
  72919. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  72920. })(BABYLON || (BABYLON = {}));
  72921. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  72922. var BABYLON;
  72923. (function (BABYLON) {
  72924. var DefaultLoadingScreen = /** @class */ (function () {
  72925. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  72926. if (_loadingText === void 0) { _loadingText = ""; }
  72927. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  72928. var _this = this;
  72929. this._renderingCanvas = _renderingCanvas;
  72930. this._loadingText = _loadingText;
  72931. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  72932. // Resize
  72933. this._resizeLoadingUI = function () {
  72934. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  72935. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  72936. if (!_this._loadingDiv) {
  72937. return;
  72938. }
  72939. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  72940. _this._loadingDiv.style.left = canvasRect.left + "px";
  72941. _this._loadingDiv.style.top = canvasRect.top + "px";
  72942. _this._loadingDiv.style.width = canvasRect.width + "px";
  72943. _this._loadingDiv.style.height = canvasRect.height + "px";
  72944. };
  72945. }
  72946. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  72947. if (this._loadingDiv) {
  72948. // Do not add a loading screen if there is already one
  72949. return;
  72950. }
  72951. this._loadingDiv = document.createElement("div");
  72952. this._loadingDiv.id = "babylonjsLoadingDiv";
  72953. this._loadingDiv.style.opacity = "0";
  72954. this._loadingDiv.style.transition = "opacity 1.5s ease";
  72955. this._loadingDiv.style.pointerEvents = "none";
  72956. // Loading text
  72957. this._loadingTextDiv = document.createElement("div");
  72958. this._loadingTextDiv.style.position = "absolute";
  72959. this._loadingTextDiv.style.left = "0";
  72960. this._loadingTextDiv.style.top = "50%";
  72961. this._loadingTextDiv.style.marginTop = "80px";
  72962. this._loadingTextDiv.style.width = "100%";
  72963. this._loadingTextDiv.style.height = "20px";
  72964. this._loadingTextDiv.style.fontFamily = "Arial";
  72965. this._loadingTextDiv.style.fontSize = "14px";
  72966. this._loadingTextDiv.style.color = "white";
  72967. this._loadingTextDiv.style.textAlign = "center";
  72968. this._loadingTextDiv.innerHTML = "Loading";
  72969. this._loadingDiv.appendChild(this._loadingTextDiv);
  72970. //set the predefined text
  72971. this._loadingTextDiv.innerHTML = this._loadingText;
  72972. // Generating keyframes
  72973. var style = document.createElement('style');
  72974. style.type = 'text/css';
  72975. 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 }";
  72976. style.innerHTML = keyFrames;
  72977. document.getElementsByTagName('head')[0].appendChild(style);
  72978. // Loading img
  72979. var imgBack = new Image();
  72980. 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";
  72981. imgBack.style.position = "absolute";
  72982. imgBack.style.left = "50%";
  72983. imgBack.style.top = "50%";
  72984. imgBack.style.marginLeft = "-60px";
  72985. imgBack.style.marginTop = "-60px";
  72986. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  72987. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  72988. imgBack.style.transformOrigin = "50% 50%";
  72989. imgBack.style.webkitTransformOrigin = "50% 50%";
  72990. this._loadingDiv.appendChild(imgBack);
  72991. this._resizeLoadingUI();
  72992. window.addEventListener("resize", this._resizeLoadingUI);
  72993. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  72994. document.body.appendChild(this._loadingDiv);
  72995. this._loadingDiv.style.opacity = "1";
  72996. };
  72997. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  72998. var _this = this;
  72999. if (!this._loadingDiv) {
  73000. return;
  73001. }
  73002. var onTransitionEnd = function () {
  73003. if (!_this._loadingDiv) {
  73004. return;
  73005. }
  73006. document.body.removeChild(_this._loadingDiv);
  73007. window.removeEventListener("resize", _this._resizeLoadingUI);
  73008. _this._loadingDiv = null;
  73009. };
  73010. this._loadingDiv.style.opacity = "0";
  73011. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  73012. };
  73013. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  73014. set: function (text) {
  73015. this._loadingText = text;
  73016. if (this._loadingTextDiv) {
  73017. this._loadingTextDiv.innerHTML = this._loadingText;
  73018. }
  73019. },
  73020. enumerable: true,
  73021. configurable: true
  73022. });
  73023. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  73024. get: function () {
  73025. return this._loadingDivBackgroundColor;
  73026. },
  73027. set: function (color) {
  73028. this._loadingDivBackgroundColor = color;
  73029. if (!this._loadingDiv) {
  73030. return;
  73031. }
  73032. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  73033. },
  73034. enumerable: true,
  73035. configurable: true
  73036. });
  73037. return DefaultLoadingScreen;
  73038. }());
  73039. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  73040. })(BABYLON || (BABYLON = {}));
  73041. //# sourceMappingURL=babylon.loadingScreen.js.map
  73042. var BABYLON;
  73043. (function (BABYLON) {
  73044. var SceneLoaderProgressEvent = /** @class */ (function () {
  73045. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  73046. this.lengthComputable = lengthComputable;
  73047. this.loaded = loaded;
  73048. this.total = total;
  73049. }
  73050. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  73051. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  73052. };
  73053. return SceneLoaderProgressEvent;
  73054. }());
  73055. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  73056. var SceneLoader = /** @class */ (function () {
  73057. function SceneLoader() {
  73058. }
  73059. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  73060. get: function () {
  73061. return 0;
  73062. },
  73063. enumerable: true,
  73064. configurable: true
  73065. });
  73066. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  73067. get: function () {
  73068. return 1;
  73069. },
  73070. enumerable: true,
  73071. configurable: true
  73072. });
  73073. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  73074. get: function () {
  73075. return 2;
  73076. },
  73077. enumerable: true,
  73078. configurable: true
  73079. });
  73080. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  73081. get: function () {
  73082. return 3;
  73083. },
  73084. enumerable: true,
  73085. configurable: true
  73086. });
  73087. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  73088. get: function () {
  73089. return SceneLoader._ForceFullSceneLoadingForIncremental;
  73090. },
  73091. set: function (value) {
  73092. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  73093. },
  73094. enumerable: true,
  73095. configurable: true
  73096. });
  73097. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  73098. get: function () {
  73099. return SceneLoader._ShowLoadingScreen;
  73100. },
  73101. set: function (value) {
  73102. SceneLoader._ShowLoadingScreen = value;
  73103. },
  73104. enumerable: true,
  73105. configurable: true
  73106. });
  73107. Object.defineProperty(SceneLoader, "loggingLevel", {
  73108. get: function () {
  73109. return SceneLoader._loggingLevel;
  73110. },
  73111. set: function (value) {
  73112. SceneLoader._loggingLevel = value;
  73113. },
  73114. enumerable: true,
  73115. configurable: true
  73116. });
  73117. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  73118. get: function () {
  73119. return SceneLoader._CleanBoneMatrixWeights;
  73120. },
  73121. set: function (value) {
  73122. SceneLoader._CleanBoneMatrixWeights = value;
  73123. },
  73124. enumerable: true,
  73125. configurable: true
  73126. });
  73127. SceneLoader._getDefaultPlugin = function () {
  73128. return SceneLoader._registeredPlugins[".babylon"];
  73129. };
  73130. SceneLoader._getPluginForExtension = function (extension) {
  73131. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  73132. if (registeredPlugin) {
  73133. return registeredPlugin;
  73134. }
  73135. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  73136. return SceneLoader._getDefaultPlugin();
  73137. };
  73138. SceneLoader._getPluginForDirectLoad = function (data) {
  73139. for (var extension in SceneLoader._registeredPlugins) {
  73140. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  73141. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  73142. return SceneLoader._registeredPlugins[extension];
  73143. }
  73144. }
  73145. return SceneLoader._getDefaultPlugin();
  73146. };
  73147. SceneLoader._getPluginForFilename = function (sceneFilename) {
  73148. var queryStringPosition = sceneFilename.indexOf("?");
  73149. if (queryStringPosition !== -1) {
  73150. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  73151. }
  73152. var dotPosition = sceneFilename.lastIndexOf(".");
  73153. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  73154. return SceneLoader._getPluginForExtension(extension);
  73155. };
  73156. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  73157. SceneLoader._getDirectLoad = function (sceneFilename) {
  73158. if (sceneFilename.substr(0, 5) === "data:") {
  73159. return sceneFilename.substr(5);
  73160. }
  73161. return null;
  73162. };
  73163. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  73164. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  73165. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  73166. var plugin;
  73167. if (registeredPlugin.plugin.createPlugin) {
  73168. plugin = registeredPlugin.plugin.createPlugin();
  73169. }
  73170. else {
  73171. plugin = registeredPlugin.plugin;
  73172. }
  73173. var useArrayBuffer = registeredPlugin.isBinary;
  73174. var database;
  73175. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  73176. var dataCallback = function (data, responseURL) {
  73177. if (scene.isDisposed) {
  73178. onError("Scene has been disposed");
  73179. return;
  73180. }
  73181. scene.database = database;
  73182. onSuccess(plugin, data, responseURL);
  73183. };
  73184. var request = null;
  73185. var pluginDisposed = false;
  73186. var onDisposeObservable = plugin.onDisposeObservable;
  73187. if (onDisposeObservable) {
  73188. onDisposeObservable.add(function () {
  73189. pluginDisposed = true;
  73190. if (request) {
  73191. request.abort();
  73192. request = null;
  73193. }
  73194. onDispose();
  73195. });
  73196. }
  73197. var manifestChecked = function () {
  73198. if (pluginDisposed) {
  73199. return;
  73200. }
  73201. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  73202. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  73203. } : undefined, database, useArrayBuffer, function (request, exception) {
  73204. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  73205. });
  73206. };
  73207. if (directLoad) {
  73208. dataCallback(directLoad);
  73209. return plugin;
  73210. }
  73211. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  73212. var engine = scene.getEngine();
  73213. var canUseOfflineSupport = engine.enableOfflineSupport;
  73214. if (canUseOfflineSupport) {
  73215. // Also check for exceptions
  73216. var exceptionFound = false;
  73217. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  73218. var regex = _a[_i];
  73219. if (regex.test(fileInfo.url)) {
  73220. exceptionFound = true;
  73221. break;
  73222. }
  73223. }
  73224. canUseOfflineSupport = !exceptionFound;
  73225. }
  73226. if (canUseOfflineSupport) {
  73227. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  73228. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  73229. }
  73230. else {
  73231. manifestChecked();
  73232. }
  73233. }
  73234. // Loading file from disk via input file or drag'n'drop
  73235. else {
  73236. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  73237. if (file) {
  73238. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  73239. }
  73240. else {
  73241. onError("Unable to find file named " + fileInfo.name);
  73242. }
  73243. }
  73244. return plugin;
  73245. };
  73246. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  73247. var url;
  73248. var name;
  73249. if (!sceneFilename) {
  73250. url = rootUrl;
  73251. name = BABYLON.Tools.GetFilename(rootUrl);
  73252. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  73253. }
  73254. else {
  73255. if (sceneFilename.substr(0, 1) === "/") {
  73256. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  73257. return null;
  73258. }
  73259. url = rootUrl + sceneFilename;
  73260. name = sceneFilename;
  73261. }
  73262. ;
  73263. return {
  73264. url: url,
  73265. rootUrl: rootUrl,
  73266. name: name
  73267. };
  73268. };
  73269. // Public functions
  73270. SceneLoader.GetPluginForExtension = function (extension) {
  73271. return SceneLoader._getPluginForExtension(extension).plugin;
  73272. };
  73273. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  73274. return !!SceneLoader._registeredPlugins[extension];
  73275. };
  73276. SceneLoader.RegisterPlugin = function (plugin) {
  73277. if (typeof plugin.extensions === "string") {
  73278. var extension = plugin.extensions;
  73279. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73280. plugin: plugin,
  73281. isBinary: false
  73282. };
  73283. }
  73284. else {
  73285. var extensions = plugin.extensions;
  73286. Object.keys(extensions).forEach(function (extension) {
  73287. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  73288. plugin: plugin,
  73289. isBinary: extensions[extension].isBinary
  73290. };
  73291. });
  73292. }
  73293. };
  73294. /**
  73295. * Import meshes into a scene
  73296. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73297. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73298. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73299. * @param scene the instance of BABYLON.Scene to append to
  73300. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  73301. * @param onProgress a callback with a progress event for each file being loaded
  73302. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73303. * @param pluginExtension the extension used to determine the plugin
  73304. * @returns The loaded plugin
  73305. */
  73306. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73307. if (sceneFilename === void 0) { sceneFilename = ""; }
  73308. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73309. if (onSuccess === void 0) { onSuccess = null; }
  73310. if (onProgress === void 0) { onProgress = null; }
  73311. if (onError === void 0) { onError = null; }
  73312. if (pluginExtension === void 0) { pluginExtension = null; }
  73313. if (!scene) {
  73314. BABYLON.Tools.Error("No scene available to import mesh to");
  73315. return null;
  73316. }
  73317. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73318. if (!fileInfo) {
  73319. return null;
  73320. }
  73321. var loadingToken = {};
  73322. scene._addPendingData(loadingToken);
  73323. var disposeHandler = function () {
  73324. scene._removePendingData(loadingToken);
  73325. };
  73326. var errorHandler = function (message, exception) {
  73327. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  73328. if (onError) {
  73329. onError(scene, errorMessage, exception);
  73330. }
  73331. else {
  73332. BABYLON.Tools.Error(errorMessage);
  73333. // should the exception be thrown?
  73334. }
  73335. disposeHandler();
  73336. };
  73337. var progressHandler = onProgress ? function (event) {
  73338. try {
  73339. onProgress(event);
  73340. }
  73341. catch (e) {
  73342. errorHandler("Error in onProgress callback", e);
  73343. }
  73344. } : undefined;
  73345. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  73346. scene.importedMeshesFiles.push(fileInfo.url);
  73347. if (onSuccess) {
  73348. try {
  73349. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  73350. }
  73351. catch (e) {
  73352. errorHandler("Error in onSuccess callback", e);
  73353. }
  73354. }
  73355. scene._removePendingData(loadingToken);
  73356. };
  73357. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73358. if (plugin.rewriteRootURL) {
  73359. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  73360. }
  73361. if (plugin.importMesh) {
  73362. var syncedPlugin = plugin;
  73363. var meshes = new Array();
  73364. var particleSystems = new Array();
  73365. var skeletons = new Array();
  73366. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  73367. return;
  73368. }
  73369. scene.loadingPluginName = plugin.name;
  73370. successHandler(meshes, particleSystems, skeletons, []);
  73371. }
  73372. else {
  73373. var asyncedPlugin = plugin;
  73374. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  73375. scene.loadingPluginName = plugin.name;
  73376. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  73377. }).catch(function (error) {
  73378. errorHandler(error.message, error);
  73379. });
  73380. }
  73381. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73382. };
  73383. /**
  73384. * Import meshes into a scene
  73385. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  73386. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73387. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73388. * @param scene the instance of BABYLON.Scene to append to
  73389. * @param onProgress a callback with a progress event for each file being loaded
  73390. * @param pluginExtension the extension used to determine the plugin
  73391. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  73392. */
  73393. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73394. if (sceneFilename === void 0) { sceneFilename = ""; }
  73395. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73396. if (onProgress === void 0) { onProgress = null; }
  73397. if (pluginExtension === void 0) { pluginExtension = null; }
  73398. return new Promise(function (resolve, reject) {
  73399. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  73400. resolve({
  73401. meshes: meshes,
  73402. particleSystems: particleSystems,
  73403. skeletons: skeletons,
  73404. animationGroups: animationGroups
  73405. });
  73406. }, onProgress, function (scene, message, exception) {
  73407. reject(exception || new Error(message));
  73408. }, pluginExtension);
  73409. });
  73410. };
  73411. /**
  73412. * Load a scene
  73413. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73414. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73415. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73416. * @param onSuccess a callback with the scene when import succeeds
  73417. * @param onProgress a callback with a progress event for each file being loaded
  73418. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73419. * @param pluginExtension the extension used to determine the plugin
  73420. * @returns The loaded plugin
  73421. */
  73422. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  73423. if (onSuccess === void 0) { onSuccess = null; }
  73424. if (onProgress === void 0) { onProgress = null; }
  73425. if (onError === void 0) { onError = null; }
  73426. if (pluginExtension === void 0) { pluginExtension = null; }
  73427. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  73428. };
  73429. /**
  73430. * Load a scene
  73431. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73432. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73433. * @param engine is the instance of BABYLON.Engine to use to create the scene
  73434. * @param onProgress a callback with a progress event for each file being loaded
  73435. * @param pluginExtension the extension used to determine the plugin
  73436. * @returns The loaded scene
  73437. */
  73438. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  73439. if (onProgress === void 0) { onProgress = null; }
  73440. if (pluginExtension === void 0) { pluginExtension = null; }
  73441. return new Promise(function (resolve, reject) {
  73442. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  73443. resolve(scene);
  73444. }, onProgress, function (scene, message, exception) {
  73445. reject(exception || new Error(message));
  73446. }, pluginExtension);
  73447. });
  73448. };
  73449. /**
  73450. * Append a scene
  73451. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73452. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73453. * @param scene is the instance of BABYLON.Scene to append to
  73454. * @param onSuccess a callback with the scene when import succeeds
  73455. * @param onProgress a callback with a progress event for each file being loaded
  73456. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73457. * @param pluginExtension the extension used to determine the plugin
  73458. * @returns The loaded plugin
  73459. */
  73460. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73461. if (sceneFilename === void 0) { sceneFilename = ""; }
  73462. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73463. if (onSuccess === void 0) { onSuccess = null; }
  73464. if (onProgress === void 0) { onProgress = null; }
  73465. if (onError === void 0) { onError = null; }
  73466. if (pluginExtension === void 0) { pluginExtension = null; }
  73467. if (!scene) {
  73468. BABYLON.Tools.Error("No scene available to append to");
  73469. return null;
  73470. }
  73471. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73472. if (!fileInfo) {
  73473. return null;
  73474. }
  73475. if (SceneLoader.ShowLoadingScreen) {
  73476. scene.getEngine().displayLoadingUI();
  73477. }
  73478. var loadingToken = {};
  73479. scene._addPendingData(loadingToken);
  73480. var disposeHandler = function () {
  73481. scene._removePendingData(loadingToken);
  73482. scene.getEngine().hideLoadingUI();
  73483. };
  73484. var errorHandler = function (message, exception) {
  73485. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  73486. if (onError) {
  73487. onError(scene, errorMessage, exception);
  73488. }
  73489. else {
  73490. BABYLON.Tools.Error(errorMessage);
  73491. // should the exception be thrown?
  73492. }
  73493. disposeHandler();
  73494. };
  73495. var progressHandler = onProgress ? function (event) {
  73496. try {
  73497. onProgress(event);
  73498. }
  73499. catch (e) {
  73500. errorHandler("Error in onProgress callback", e);
  73501. }
  73502. } : undefined;
  73503. var successHandler = function () {
  73504. if (onSuccess) {
  73505. try {
  73506. onSuccess(scene);
  73507. }
  73508. catch (e) {
  73509. errorHandler("Error in onSuccess callback", e);
  73510. }
  73511. }
  73512. scene._removePendingData(loadingToken);
  73513. };
  73514. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73515. if (plugin.load) {
  73516. var syncedPlugin = plugin;
  73517. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  73518. return;
  73519. }
  73520. scene.loadingPluginName = plugin.name;
  73521. successHandler();
  73522. }
  73523. else {
  73524. var asyncedPlugin = plugin;
  73525. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  73526. scene.loadingPluginName = plugin.name;
  73527. successHandler();
  73528. }).catch(function (error) {
  73529. errorHandler(error.message, error);
  73530. });
  73531. }
  73532. if (SceneLoader.ShowLoadingScreen) {
  73533. scene.executeWhenReady(function () {
  73534. scene.getEngine().hideLoadingUI();
  73535. });
  73536. }
  73537. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73538. };
  73539. /**
  73540. * Append a scene
  73541. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73542. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73543. * @param scene is the instance of BABYLON.Scene to append to
  73544. * @param onProgress a callback with a progress event for each file being loaded
  73545. * @param pluginExtension the extension used to determine the plugin
  73546. * @returns The given scene
  73547. */
  73548. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73549. if (sceneFilename === void 0) { sceneFilename = ""; }
  73550. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73551. if (onProgress === void 0) { onProgress = null; }
  73552. if (pluginExtension === void 0) { pluginExtension = null; }
  73553. return new Promise(function (resolve, reject) {
  73554. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  73555. resolve(scene);
  73556. }, onProgress, function (scene, message, exception) {
  73557. reject(exception || new Error(message));
  73558. }, pluginExtension);
  73559. });
  73560. };
  73561. /**
  73562. * Load a scene into an asset container
  73563. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73564. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73565. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  73566. * @param onSuccess a callback with the scene when import succeeds
  73567. * @param onProgress a callback with a progress event for each file being loaded
  73568. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  73569. * @param pluginExtension the extension used to determine the plugin
  73570. * @returns The loaded plugin
  73571. */
  73572. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  73573. if (sceneFilename === void 0) { sceneFilename = ""; }
  73574. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73575. if (onSuccess === void 0) { onSuccess = null; }
  73576. if (onProgress === void 0) { onProgress = null; }
  73577. if (onError === void 0) { onError = null; }
  73578. if (pluginExtension === void 0) { pluginExtension = null; }
  73579. if (!scene) {
  73580. BABYLON.Tools.Error("No scene available to load asset container to");
  73581. return null;
  73582. }
  73583. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  73584. if (!fileInfo) {
  73585. return null;
  73586. }
  73587. var loadingToken = {};
  73588. scene._addPendingData(loadingToken);
  73589. var disposeHandler = function () {
  73590. scene._removePendingData(loadingToken);
  73591. };
  73592. var errorHandler = function (message, exception) {
  73593. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  73594. if (onError) {
  73595. onError(scene, errorMessage, exception);
  73596. }
  73597. else {
  73598. BABYLON.Tools.Error(errorMessage);
  73599. // should the exception be thrown?
  73600. }
  73601. disposeHandler();
  73602. };
  73603. var progressHandler = onProgress ? function (event) {
  73604. try {
  73605. onProgress(event);
  73606. }
  73607. catch (e) {
  73608. errorHandler("Error in onProgress callback", e);
  73609. }
  73610. } : undefined;
  73611. var successHandler = function (assets) {
  73612. if (onSuccess) {
  73613. try {
  73614. onSuccess(assets);
  73615. }
  73616. catch (e) {
  73617. errorHandler("Error in onSuccess callback", e);
  73618. }
  73619. }
  73620. scene._removePendingData(loadingToken);
  73621. };
  73622. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  73623. if (plugin.loadAssetContainer) {
  73624. var syncedPlugin = plugin;
  73625. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  73626. if (!assetContainer) {
  73627. return;
  73628. }
  73629. scene.loadingPluginName = plugin.name;
  73630. successHandler(assetContainer);
  73631. }
  73632. else if (plugin.loadAssetContainerAsync) {
  73633. var asyncedPlugin = plugin;
  73634. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  73635. scene.loadingPluginName = plugin.name;
  73636. successHandler(assetContainer);
  73637. }).catch(function (error) {
  73638. errorHandler(error.message, error);
  73639. });
  73640. }
  73641. else {
  73642. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  73643. }
  73644. if (SceneLoader.ShowLoadingScreen) {
  73645. scene.executeWhenReady(function () {
  73646. scene.getEngine().hideLoadingUI();
  73647. });
  73648. }
  73649. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  73650. };
  73651. /**
  73652. * Load a scene into an asset container
  73653. * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
  73654. * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
  73655. * @param scene is the instance of BABYLON.Scene to append to
  73656. * @param onProgress a callback with a progress event for each file being loaded
  73657. * @param pluginExtension the extension used to determine the plugin
  73658. * @returns The loaded asset container
  73659. */
  73660. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  73661. if (sceneFilename === void 0) { sceneFilename = ""; }
  73662. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  73663. if (onProgress === void 0) { onProgress = null; }
  73664. if (pluginExtension === void 0) { pluginExtension = null; }
  73665. return new Promise(function (resolve, reject) {
  73666. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  73667. resolve(assetContainer);
  73668. }, onProgress, function (scene, message, exception) {
  73669. reject(exception || new Error(message));
  73670. }, pluginExtension);
  73671. });
  73672. };
  73673. // Flags
  73674. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  73675. SceneLoader._ShowLoadingScreen = true;
  73676. SceneLoader._CleanBoneMatrixWeights = false;
  73677. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  73678. // Members
  73679. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  73680. SceneLoader._registeredPlugins = {};
  73681. return SceneLoader;
  73682. }());
  73683. BABYLON.SceneLoader = SceneLoader;
  73684. ;
  73685. })(BABYLON || (BABYLON = {}));
  73686. //# sourceMappingURL=babylon.sceneLoader.js.map
  73687. var BABYLON;
  73688. (function (BABYLON) {
  73689. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  73690. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  73691. var parsedMaterial = parsedData.materials[index];
  73692. if (parsedMaterial.id === id) {
  73693. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  73694. }
  73695. }
  73696. return null;
  73697. };
  73698. var isDescendantOf = function (mesh, names, hierarchyIds) {
  73699. for (var i in names) {
  73700. if (mesh.name === names[i]) {
  73701. hierarchyIds.push(mesh.id);
  73702. return true;
  73703. }
  73704. }
  73705. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  73706. hierarchyIds.push(mesh.id);
  73707. return true;
  73708. }
  73709. return false;
  73710. };
  73711. var logOperation = function (operation, producer) {
  73712. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  73713. };
  73714. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  73715. if (addToScene === void 0) { addToScene = false; }
  73716. var container = new BABYLON.AssetContainer(scene);
  73717. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  73718. // when SceneLoader.debugLogging = true (default), or exception encountered.
  73719. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  73720. // and avoid problems with multiple concurrent .babylon loads.
  73721. var log = "importScene has failed JSON parse";
  73722. try {
  73723. var parsedData = JSON.parse(data);
  73724. log = "";
  73725. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  73726. var index;
  73727. var cache;
  73728. // Lights
  73729. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  73730. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  73731. var parsedLight = parsedData.lights[index];
  73732. var light = BABYLON.Light.Parse(parsedLight, scene);
  73733. if (light) {
  73734. container.lights.push(light);
  73735. log += (index === 0 ? "\n\tLights:" : "");
  73736. log += "\n\t\t" + light.toString(fullDetails);
  73737. }
  73738. }
  73739. }
  73740. // Animations
  73741. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  73742. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  73743. var parsedAnimation = parsedData.animations[index];
  73744. var animation = BABYLON.Animation.Parse(parsedAnimation);
  73745. scene.animations.push(animation);
  73746. container.animations.push(animation);
  73747. log += (index === 0 ? "\n\tAnimations:" : "");
  73748. log += "\n\t\t" + animation.toString(fullDetails);
  73749. }
  73750. }
  73751. // Materials
  73752. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  73753. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  73754. var parsedMaterial = parsedData.materials[index];
  73755. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  73756. container.materials.push(mat);
  73757. log += (index === 0 ? "\n\tMaterials:" : "");
  73758. log += "\n\t\t" + mat.toString(fullDetails);
  73759. }
  73760. }
  73761. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  73762. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  73763. var parsedMultiMaterial = parsedData.multiMaterials[index];
  73764. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  73765. container.multiMaterials.push(mmat);
  73766. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  73767. log += "\n\t\t" + mmat.toString(fullDetails);
  73768. }
  73769. }
  73770. // Morph targets
  73771. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  73772. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  73773. var managerData = _a[_i];
  73774. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  73775. }
  73776. }
  73777. // Skeletons
  73778. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  73779. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  73780. var parsedSkeleton = parsedData.skeletons[index];
  73781. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  73782. container.skeletons.push(skeleton);
  73783. log += (index === 0 ? "\n\tSkeletons:" : "");
  73784. log += "\n\t\t" + skeleton.toString(fullDetails);
  73785. }
  73786. }
  73787. // Geometries
  73788. var geometries = parsedData.geometries;
  73789. if (geometries !== undefined && geometries !== null) {
  73790. var addedGeometry = new Array();
  73791. // Boxes
  73792. var boxes = geometries.boxes;
  73793. if (boxes !== undefined && boxes !== null) {
  73794. for (index = 0, cache = boxes.length; index < cache; index++) {
  73795. var parsedBox = boxes[index];
  73796. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  73797. }
  73798. }
  73799. // Spheres
  73800. var spheres = geometries.spheres;
  73801. if (spheres !== undefined && spheres !== null) {
  73802. for (index = 0, cache = spheres.length; index < cache; index++) {
  73803. var parsedSphere = spheres[index];
  73804. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  73805. }
  73806. }
  73807. // Cylinders
  73808. var cylinders = geometries.cylinders;
  73809. if (cylinders !== undefined && cylinders !== null) {
  73810. for (index = 0, cache = cylinders.length; index < cache; index++) {
  73811. var parsedCylinder = cylinders[index];
  73812. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  73813. }
  73814. }
  73815. // Toruses
  73816. var toruses = geometries.toruses;
  73817. if (toruses !== undefined && toruses !== null) {
  73818. for (index = 0, cache = toruses.length; index < cache; index++) {
  73819. var parsedTorus = toruses[index];
  73820. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  73821. }
  73822. }
  73823. // Grounds
  73824. var grounds = geometries.grounds;
  73825. if (grounds !== undefined && grounds !== null) {
  73826. for (index = 0, cache = grounds.length; index < cache; index++) {
  73827. var parsedGround = grounds[index];
  73828. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  73829. }
  73830. }
  73831. // Planes
  73832. var planes = geometries.planes;
  73833. if (planes !== undefined && planes !== null) {
  73834. for (index = 0, cache = planes.length; index < cache; index++) {
  73835. var parsedPlane = planes[index];
  73836. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  73837. }
  73838. }
  73839. // TorusKnots
  73840. var torusKnots = geometries.torusKnots;
  73841. if (torusKnots !== undefined && torusKnots !== null) {
  73842. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  73843. var parsedTorusKnot = torusKnots[index];
  73844. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  73845. }
  73846. }
  73847. // VertexData
  73848. var vertexData = geometries.vertexData;
  73849. if (vertexData !== undefined && vertexData !== null) {
  73850. for (index = 0, cache = vertexData.length; index < cache; index++) {
  73851. var parsedVertexData = vertexData[index];
  73852. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  73853. }
  73854. }
  73855. addedGeometry.forEach(function (g) {
  73856. if (g) {
  73857. container.geometries.push(g);
  73858. }
  73859. });
  73860. }
  73861. // Transform nodes
  73862. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  73863. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  73864. var parsedTransformNode = parsedData.transformNodes[index];
  73865. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  73866. container.transformNodes.push(node);
  73867. }
  73868. }
  73869. // Meshes
  73870. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  73871. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  73872. var parsedMesh = parsedData.meshes[index];
  73873. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  73874. container.meshes.push(mesh);
  73875. log += (index === 0 ? "\n\tMeshes:" : "");
  73876. log += "\n\t\t" + mesh.toString(fullDetails);
  73877. }
  73878. }
  73879. // Cameras
  73880. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  73881. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  73882. var parsedCamera = parsedData.cameras[index];
  73883. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  73884. container.cameras.push(camera);
  73885. log += (index === 0 ? "\n\tCameras:" : "");
  73886. log += "\n\t\t" + camera.toString(fullDetails);
  73887. }
  73888. }
  73889. // Animation Groups
  73890. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  73891. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  73892. var parsedAnimationGroup = parsedData.animationGroups[index];
  73893. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  73894. container.animationGroups.push(animationGroup);
  73895. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  73896. log += "\n\t\t" + animationGroup.toString(fullDetails);
  73897. }
  73898. }
  73899. // Browsing all the graph to connect the dots
  73900. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  73901. var camera = scene.cameras[index];
  73902. if (camera._waitingParentId) {
  73903. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  73904. camera._waitingParentId = null;
  73905. }
  73906. }
  73907. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  73908. var light_1 = scene.lights[index];
  73909. if (light_1 && light_1._waitingParentId) {
  73910. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  73911. light_1._waitingParentId = null;
  73912. }
  73913. }
  73914. // Connect parents & children and parse actions
  73915. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  73916. var transformNode = scene.transformNodes[index];
  73917. if (transformNode._waitingParentId) {
  73918. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  73919. transformNode._waitingParentId = null;
  73920. }
  73921. }
  73922. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73923. var mesh = scene.meshes[index];
  73924. if (mesh._waitingParentId) {
  73925. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  73926. mesh._waitingParentId = null;
  73927. }
  73928. if (mesh._waitingActions) {
  73929. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  73930. mesh._waitingActions = null;
  73931. }
  73932. }
  73933. // freeze world matrix application
  73934. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  73935. var currentMesh = scene.meshes[index];
  73936. if (currentMesh._waitingFreezeWorldMatrix) {
  73937. currentMesh.freezeWorldMatrix();
  73938. currentMesh._waitingFreezeWorldMatrix = null;
  73939. }
  73940. else {
  73941. currentMesh.computeWorldMatrix(true);
  73942. }
  73943. }
  73944. // Lights exclusions / inclusions
  73945. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  73946. var light_2 = scene.lights[index];
  73947. // Excluded check
  73948. if (light_2._excludedMeshesIds.length > 0) {
  73949. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  73950. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  73951. if (excludedMesh) {
  73952. light_2.excludedMeshes.push(excludedMesh);
  73953. }
  73954. }
  73955. light_2._excludedMeshesIds = [];
  73956. }
  73957. // Included check
  73958. if (light_2._includedOnlyMeshesIds.length > 0) {
  73959. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  73960. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  73961. if (includedOnlyMesh) {
  73962. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  73963. }
  73964. }
  73965. light_2._includedOnlyMeshesIds = [];
  73966. }
  73967. }
  73968. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  73969. // Actions (scene)
  73970. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  73971. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  73972. }
  73973. if (!addToScene) {
  73974. container.removeAllFromScene();
  73975. }
  73976. }
  73977. catch (err) {
  73978. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  73979. if (onError) {
  73980. onError(msg, err);
  73981. }
  73982. else {
  73983. BABYLON.Tools.Log(msg);
  73984. throw err;
  73985. }
  73986. }
  73987. finally {
  73988. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  73989. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  73990. }
  73991. }
  73992. return container;
  73993. };
  73994. BABYLON.SceneLoader.RegisterPlugin({
  73995. name: "babylon.js",
  73996. extensions: ".babylon",
  73997. canDirectLoad: function (data) {
  73998. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  73999. return true;
  74000. }
  74001. return false;
  74002. },
  74003. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  74004. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74005. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74006. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74007. // and avoid problems with multiple concurrent .babylon loads.
  74008. var log = "importMesh has failed JSON parse";
  74009. try {
  74010. var parsedData = JSON.parse(data);
  74011. log = "";
  74012. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  74013. if (!meshesNames) {
  74014. meshesNames = null;
  74015. }
  74016. else if (!Array.isArray(meshesNames)) {
  74017. meshesNames = [meshesNames];
  74018. }
  74019. var hierarchyIds = new Array();
  74020. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  74021. var loadedSkeletonsIds = [];
  74022. var loadedMaterialsIds = [];
  74023. var index;
  74024. var cache;
  74025. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  74026. var parsedMesh = parsedData.meshes[index];
  74027. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  74028. if (meshesNames !== null) {
  74029. // Remove found mesh name from list.
  74030. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  74031. }
  74032. //Geometry?
  74033. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  74034. //does the file contain geometries?
  74035. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  74036. //find the correct geometry and add it to the scene
  74037. var found = false;
  74038. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  74039. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  74040. return;
  74041. }
  74042. else {
  74043. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  74044. if (parsedGeometryData.id === parsedMesh.geometryId) {
  74045. switch (geometryType) {
  74046. case "boxes":
  74047. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  74048. break;
  74049. case "spheres":
  74050. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  74051. break;
  74052. case "cylinders":
  74053. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  74054. break;
  74055. case "toruses":
  74056. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  74057. break;
  74058. case "grounds":
  74059. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  74060. break;
  74061. case "planes":
  74062. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  74063. break;
  74064. case "torusKnots":
  74065. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  74066. break;
  74067. case "vertexData":
  74068. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  74069. break;
  74070. }
  74071. found = true;
  74072. }
  74073. });
  74074. }
  74075. });
  74076. if (found === false) {
  74077. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  74078. }
  74079. }
  74080. }
  74081. // Material ?
  74082. if (parsedMesh.materialId) {
  74083. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  74084. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  74085. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  74086. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  74087. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  74088. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  74089. var subMatId = parsedMultiMaterial.materials[matIndex];
  74090. loadedMaterialsIds.push(subMatId);
  74091. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  74092. if (mat) {
  74093. log += "\n\tMaterial " + mat.toString(fullDetails);
  74094. }
  74095. }
  74096. loadedMaterialsIds.push(parsedMultiMaterial.id);
  74097. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  74098. if (mmat) {
  74099. materialFound = true;
  74100. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  74101. }
  74102. break;
  74103. }
  74104. }
  74105. }
  74106. if (materialFound === false) {
  74107. loadedMaterialsIds.push(parsedMesh.materialId);
  74108. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  74109. if (!mat) {
  74110. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  74111. }
  74112. else {
  74113. log += "\n\tMaterial " + mat.toString(fullDetails);
  74114. }
  74115. }
  74116. }
  74117. // Skeleton ?
  74118. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  74119. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  74120. if (skeletonAlreadyLoaded === false) {
  74121. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  74122. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  74123. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  74124. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  74125. skeletons.push(skeleton);
  74126. loadedSkeletonsIds.push(parsedSkeleton.id);
  74127. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  74128. }
  74129. }
  74130. }
  74131. }
  74132. // Morph targets ?
  74133. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  74134. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  74135. var managerData = _a[_i];
  74136. BABYLON.MorphTargetManager.Parse(managerData, scene);
  74137. }
  74138. }
  74139. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  74140. meshes.push(mesh);
  74141. log += "\n\tMesh " + mesh.toString(fullDetails);
  74142. }
  74143. }
  74144. // Connecting parents
  74145. var currentMesh;
  74146. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74147. currentMesh = scene.meshes[index];
  74148. if (currentMesh._waitingParentId) {
  74149. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  74150. currentMesh._waitingParentId = null;
  74151. }
  74152. }
  74153. // freeze and compute world matrix application
  74154. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  74155. currentMesh = scene.meshes[index];
  74156. if (currentMesh._waitingFreezeWorldMatrix) {
  74157. currentMesh.freezeWorldMatrix();
  74158. currentMesh._waitingFreezeWorldMatrix = null;
  74159. }
  74160. else {
  74161. currentMesh.computeWorldMatrix(true);
  74162. }
  74163. }
  74164. }
  74165. // Particles
  74166. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  74167. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  74168. if (parser) {
  74169. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  74170. var parsedParticleSystem = parsedData.particleSystems[index];
  74171. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  74172. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  74173. }
  74174. }
  74175. }
  74176. }
  74177. return true;
  74178. }
  74179. catch (err) {
  74180. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  74181. if (onError) {
  74182. onError(msg, err);
  74183. }
  74184. else {
  74185. BABYLON.Tools.Log(msg);
  74186. throw err;
  74187. }
  74188. }
  74189. finally {
  74190. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74191. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74192. }
  74193. }
  74194. return false;
  74195. },
  74196. load: function (scene, data, rootUrl, onError) {
  74197. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  74198. // when SceneLoader.debugLogging = true (default), or exception encountered.
  74199. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  74200. // and avoid problems with multiple concurrent .babylon loads.
  74201. var log = "importScene has failed JSON parse";
  74202. try {
  74203. var parsedData = JSON.parse(data);
  74204. log = "";
  74205. // Scene
  74206. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  74207. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  74208. }
  74209. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  74210. scene.autoClear = parsedData.autoClear;
  74211. }
  74212. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  74213. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  74214. }
  74215. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  74216. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  74217. }
  74218. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  74219. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  74220. }
  74221. // Fog
  74222. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  74223. scene.fogMode = parsedData.fogMode;
  74224. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  74225. scene.fogStart = parsedData.fogStart;
  74226. scene.fogEnd = parsedData.fogEnd;
  74227. scene.fogDensity = parsedData.fogDensity;
  74228. log += "\tFog mode for scene: ";
  74229. switch (scene.fogMode) {
  74230. // getters not compiling, so using hardcoded
  74231. case 1:
  74232. log += "exp\n";
  74233. break;
  74234. case 2:
  74235. log += "exp2\n";
  74236. break;
  74237. case 3:
  74238. log += "linear\n";
  74239. break;
  74240. }
  74241. }
  74242. //Physics
  74243. if (parsedData.physicsEnabled) {
  74244. var physicsPlugin;
  74245. if (parsedData.physicsEngine === "cannon") {
  74246. physicsPlugin = new BABYLON.CannonJSPlugin();
  74247. }
  74248. else if (parsedData.physicsEngine === "oimo") {
  74249. physicsPlugin = new BABYLON.OimoJSPlugin();
  74250. }
  74251. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  74252. //else - default engine, which is currently oimo
  74253. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  74254. scene.enablePhysics(physicsGravity, physicsPlugin);
  74255. }
  74256. // Metadata
  74257. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  74258. scene.metadata = parsedData.metadata;
  74259. }
  74260. //collisions, if defined. otherwise, default is true
  74261. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  74262. scene.collisionsEnabled = parsedData.collisionsEnabled;
  74263. }
  74264. scene.workerCollisions = !!parsedData.workerCollisions;
  74265. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  74266. if (!container) {
  74267. return false;
  74268. }
  74269. if (parsedData.autoAnimate) {
  74270. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  74271. }
  74272. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  74273. scene.setActiveCameraByID(parsedData.activeCameraID);
  74274. }
  74275. // Environment texture
  74276. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  74277. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  74278. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  74279. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  74280. if (parsedData.environmentTextureRotationY) {
  74281. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  74282. }
  74283. scene.environmentTexture = hdrTexture;
  74284. }
  74285. else {
  74286. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  74287. if (parsedData.environmentTextureRotationY) {
  74288. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  74289. }
  74290. scene.environmentTexture = cubeTexture;
  74291. }
  74292. if (parsedData.createDefaultSkybox === true) {
  74293. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  74294. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  74295. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  74296. }
  74297. }
  74298. // Finish
  74299. return true;
  74300. }
  74301. catch (err) {
  74302. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  74303. if (onError) {
  74304. onError(msg, err);
  74305. }
  74306. else {
  74307. BABYLON.Tools.Log(msg);
  74308. throw err;
  74309. }
  74310. }
  74311. finally {
  74312. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  74313. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  74314. }
  74315. }
  74316. return false;
  74317. },
  74318. loadAssetContainer: function (scene, data, rootUrl, onError) {
  74319. var container = loadAssetContainer(scene, data, rootUrl, onError);
  74320. return container;
  74321. }
  74322. });
  74323. })(BABYLON || (BABYLON = {}));
  74324. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  74325. var BABYLON;
  74326. (function (BABYLON) {
  74327. var FilesInput = /** @class */ (function () {
  74328. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  74329. this.onProcessFileCallback = function () { return true; };
  74330. this._engine = engine;
  74331. this._currentScene = scene;
  74332. this._sceneLoadedCallback = sceneLoadedCallback;
  74333. this._progressCallback = progressCallback;
  74334. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  74335. this._textureLoadingCallback = textureLoadingCallback;
  74336. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  74337. this._onReloadCallback = onReloadCallback;
  74338. this._errorCallback = errorCallback;
  74339. }
  74340. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  74341. var _this = this;
  74342. if (elementToMonitor) {
  74343. this._elementToMonitor = elementToMonitor;
  74344. this._dragEnterHandler = function (e) { _this.drag(e); };
  74345. this._dragOverHandler = function (e) { _this.drag(e); };
  74346. this._dropHandler = function (e) { _this.drop(e); };
  74347. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  74348. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  74349. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  74350. }
  74351. };
  74352. FilesInput.prototype.dispose = function () {
  74353. if (!this._elementToMonitor) {
  74354. return;
  74355. }
  74356. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  74357. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  74358. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  74359. };
  74360. FilesInput.prototype.renderFunction = function () {
  74361. if (this._additionalRenderLoopLogicCallback) {
  74362. this._additionalRenderLoopLogicCallback();
  74363. }
  74364. if (this._currentScene) {
  74365. if (this._textureLoadingCallback) {
  74366. var remaining = this._currentScene.getWaitingItemsCount();
  74367. if (remaining > 0) {
  74368. this._textureLoadingCallback(remaining);
  74369. }
  74370. }
  74371. this._currentScene.render();
  74372. }
  74373. };
  74374. FilesInput.prototype.drag = function (e) {
  74375. e.stopPropagation();
  74376. e.preventDefault();
  74377. };
  74378. FilesInput.prototype.drop = function (eventDrop) {
  74379. eventDrop.stopPropagation();
  74380. eventDrop.preventDefault();
  74381. this.loadFiles(eventDrop);
  74382. };
  74383. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  74384. var _this = this;
  74385. var reader = folder.createReader();
  74386. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  74387. reader.readEntries(function (entries) {
  74388. remaining.count += entries.length;
  74389. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  74390. var entry = entries_1[_i];
  74391. if (entry.isFile) {
  74392. entry.file(function (file) {
  74393. file.correctName = relativePath + file.name;
  74394. files.push(file);
  74395. if (--remaining.count === 0) {
  74396. callback();
  74397. }
  74398. });
  74399. }
  74400. else if (entry.isDirectory) {
  74401. _this._traverseFolder(entry, files, remaining, callback);
  74402. }
  74403. }
  74404. if (--remaining.count) {
  74405. callback();
  74406. }
  74407. });
  74408. };
  74409. FilesInput.prototype._processFiles = function (files) {
  74410. for (var i = 0; i < files.length; i++) {
  74411. var name = files[i].correctName.toLowerCase();
  74412. var extension = name.split('.').pop();
  74413. if (!this.onProcessFileCallback(files[i], name, extension)) {
  74414. continue;
  74415. }
  74416. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  74417. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  74418. this._sceneFileToLoad = files[i];
  74419. }
  74420. FilesInput.FilesToLoad[name] = files[i];
  74421. }
  74422. };
  74423. FilesInput.prototype.loadFiles = function (event) {
  74424. var _this = this;
  74425. // Handling data transfer via drag'n'drop
  74426. if (event && event.dataTransfer && event.dataTransfer.files) {
  74427. this._filesToLoad = event.dataTransfer.files;
  74428. }
  74429. // Handling files from input files
  74430. if (event && event.target && event.target.files) {
  74431. this._filesToLoad = event.target.files;
  74432. }
  74433. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  74434. return;
  74435. }
  74436. if (this._startingProcessingFilesCallback) {
  74437. this._startingProcessingFilesCallback(this._filesToLoad);
  74438. }
  74439. if (this._filesToLoad && this._filesToLoad.length > 0) {
  74440. var files_1 = new Array();
  74441. var folders = [];
  74442. var items = event.dataTransfer ? event.dataTransfer.items : null;
  74443. for (var i = 0; i < this._filesToLoad.length; i++) {
  74444. var fileToLoad = this._filesToLoad[i];
  74445. var name_1 = fileToLoad.name.toLowerCase();
  74446. var entry = void 0;
  74447. fileToLoad.correctName = name_1;
  74448. if (items) {
  74449. var item = items[i];
  74450. if (item.getAsEntry) {
  74451. entry = item.getAsEntry();
  74452. }
  74453. else if (item.webkitGetAsEntry) {
  74454. entry = item.webkitGetAsEntry();
  74455. }
  74456. }
  74457. if (!entry) {
  74458. files_1.push(fileToLoad);
  74459. }
  74460. else {
  74461. if (entry.isDirectory) {
  74462. folders.push(entry);
  74463. }
  74464. else {
  74465. files_1.push(fileToLoad);
  74466. }
  74467. }
  74468. }
  74469. if (folders.length === 0) {
  74470. this._processFiles(files_1);
  74471. this._processReload();
  74472. }
  74473. else {
  74474. var remaining = { count: folders.length };
  74475. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  74476. var folder = folders_1[_i];
  74477. this._traverseFolder(folder, files_1, remaining, function () {
  74478. _this._processFiles(files_1);
  74479. if (remaining.count === 0) {
  74480. _this._processReload();
  74481. }
  74482. });
  74483. }
  74484. }
  74485. }
  74486. };
  74487. FilesInput.prototype._processReload = function () {
  74488. if (this._onReloadCallback) {
  74489. this._onReloadCallback(this._sceneFileToLoad);
  74490. }
  74491. else {
  74492. this.reload();
  74493. }
  74494. };
  74495. FilesInput.prototype.reload = function () {
  74496. var _this = this;
  74497. // If a scene file has been provided
  74498. if (this._sceneFileToLoad) {
  74499. if (this._currentScene) {
  74500. if (BABYLON.Tools.errorsCount > 0) {
  74501. BABYLON.Tools.ClearLogCache();
  74502. }
  74503. this._engine.stopRenderLoop();
  74504. }
  74505. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  74506. if (_this._progressCallback) {
  74507. _this._progressCallback(progress);
  74508. }
  74509. }).then(function (scene) {
  74510. if (_this._currentScene) {
  74511. _this._currentScene.dispose();
  74512. }
  74513. _this._currentScene = scene;
  74514. if (_this._sceneLoadedCallback) {
  74515. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  74516. }
  74517. // Wait for textures and shaders to be ready
  74518. _this._currentScene.executeWhenReady(function () {
  74519. _this._engine.runRenderLoop(function () {
  74520. _this.renderFunction();
  74521. });
  74522. });
  74523. }).catch(function (error) {
  74524. if (_this._errorCallback) {
  74525. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  74526. }
  74527. });
  74528. }
  74529. else {
  74530. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  74531. }
  74532. };
  74533. FilesInput.FilesToLoad = {};
  74534. return FilesInput;
  74535. }());
  74536. BABYLON.FilesInput = FilesInput;
  74537. })(BABYLON || (BABYLON = {}));
  74538. //# sourceMappingURL=babylon.filesInput.js.map
  74539. var BABYLON;
  74540. (function (BABYLON) {
  74541. var Tags = /** @class */ (function () {
  74542. function Tags() {
  74543. }
  74544. Tags.EnableFor = function (obj) {
  74545. obj._tags = obj._tags || {};
  74546. obj.hasTags = function () {
  74547. return Tags.HasTags(obj);
  74548. };
  74549. obj.addTags = function (tagsString) {
  74550. return Tags.AddTagsTo(obj, tagsString);
  74551. };
  74552. obj.removeTags = function (tagsString) {
  74553. return Tags.RemoveTagsFrom(obj, tagsString);
  74554. };
  74555. obj.matchesTagsQuery = function (tagsQuery) {
  74556. return Tags.MatchesQuery(obj, tagsQuery);
  74557. };
  74558. };
  74559. Tags.DisableFor = function (obj) {
  74560. delete obj._tags;
  74561. delete obj.hasTags;
  74562. delete obj.addTags;
  74563. delete obj.removeTags;
  74564. delete obj.matchesTagsQuery;
  74565. };
  74566. Tags.HasTags = function (obj) {
  74567. if (!obj._tags) {
  74568. return false;
  74569. }
  74570. return !BABYLON.Tools.IsEmpty(obj._tags);
  74571. };
  74572. Tags.GetTags = function (obj, asString) {
  74573. if (asString === void 0) { asString = true; }
  74574. if (!obj._tags) {
  74575. return null;
  74576. }
  74577. if (asString) {
  74578. var tagsArray = [];
  74579. for (var tag in obj._tags) {
  74580. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  74581. tagsArray.push(tag);
  74582. }
  74583. }
  74584. return tagsArray.join(" ");
  74585. }
  74586. else {
  74587. return obj._tags;
  74588. }
  74589. };
  74590. // the tags 'true' and 'false' are reserved and cannot be used as tags
  74591. // a tag cannot start with '||', '&&', and '!'
  74592. // it cannot contain whitespaces
  74593. Tags.AddTagsTo = function (obj, tagsString) {
  74594. if (!tagsString) {
  74595. return;
  74596. }
  74597. if (typeof tagsString !== "string") {
  74598. return;
  74599. }
  74600. var tags = tagsString.split(" ");
  74601. tags.forEach(function (tag, index, array) {
  74602. Tags._AddTagTo(obj, tag);
  74603. });
  74604. };
  74605. Tags._AddTagTo = function (obj, tag) {
  74606. tag = tag.trim();
  74607. if (tag === "" || tag === "true" || tag === "false") {
  74608. return;
  74609. }
  74610. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  74611. return;
  74612. }
  74613. Tags.EnableFor(obj);
  74614. obj._tags[tag] = true;
  74615. };
  74616. Tags.RemoveTagsFrom = function (obj, tagsString) {
  74617. if (!Tags.HasTags(obj)) {
  74618. return;
  74619. }
  74620. var tags = tagsString.split(" ");
  74621. for (var t in tags) {
  74622. Tags._RemoveTagFrom(obj, tags[t]);
  74623. }
  74624. };
  74625. Tags._RemoveTagFrom = function (obj, tag) {
  74626. delete obj._tags[tag];
  74627. };
  74628. Tags.MatchesQuery = function (obj, tagsQuery) {
  74629. if (tagsQuery === undefined) {
  74630. return true;
  74631. }
  74632. if (tagsQuery === "") {
  74633. return Tags.HasTags(obj);
  74634. }
  74635. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  74636. };
  74637. return Tags;
  74638. }());
  74639. BABYLON.Tags = Tags;
  74640. })(BABYLON || (BABYLON = {}));
  74641. //# sourceMappingURL=babylon.tags.js.map
  74642. var BABYLON;
  74643. (function (BABYLON) {
  74644. /**
  74645. * Class used to evalaute queries containing `and` and `or` operators
  74646. */
  74647. var AndOrNotEvaluator = /** @class */ (function () {
  74648. function AndOrNotEvaluator() {
  74649. }
  74650. /**
  74651. * Evaluate a query
  74652. * @param query defines the query to evaluate
  74653. * @param evaluateCallback defines the callback used to filter result
  74654. * @returns true if the query matches
  74655. */
  74656. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  74657. if (!query.match(/\([^\(\)]*\)/g)) {
  74658. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  74659. }
  74660. else {
  74661. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  74662. // remove parenthesis
  74663. r = r.slice(1, r.length - 1);
  74664. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  74665. });
  74666. }
  74667. if (query === "true") {
  74668. return true;
  74669. }
  74670. if (query === "false") {
  74671. return false;
  74672. }
  74673. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  74674. };
  74675. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  74676. evaluateCallback = evaluateCallback || (function (r) {
  74677. return r === "true" ? true : false;
  74678. });
  74679. var result;
  74680. var or = parenthesisContent.split("||");
  74681. for (var i in or) {
  74682. if (or.hasOwnProperty(i)) {
  74683. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  74684. var and = ori.split("&&");
  74685. if (and.length > 1) {
  74686. for (var j = 0; j < and.length; ++j) {
  74687. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  74688. if (andj !== "true" && andj !== "false") {
  74689. if (andj[0] === "!") {
  74690. result = !evaluateCallback(andj.substring(1));
  74691. }
  74692. else {
  74693. result = evaluateCallback(andj);
  74694. }
  74695. }
  74696. else {
  74697. result = andj === "true" ? true : false;
  74698. }
  74699. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  74700. ori = "false";
  74701. break;
  74702. }
  74703. }
  74704. }
  74705. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  74706. result = true;
  74707. break;
  74708. }
  74709. // result equals false (or undefined)
  74710. if (ori !== "true" && ori !== "false") {
  74711. if (ori[0] === "!") {
  74712. result = !evaluateCallback(ori.substring(1));
  74713. }
  74714. else {
  74715. result = evaluateCallback(ori);
  74716. }
  74717. }
  74718. else {
  74719. result = ori === "true" ? true : false;
  74720. }
  74721. }
  74722. }
  74723. // the whole parenthesis scope is replaced by 'true' or 'false'
  74724. return result ? "true" : "false";
  74725. };
  74726. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  74727. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  74728. // remove whitespaces
  74729. r = r.replace(/[\s]/g, function () { return ""; });
  74730. return r.length % 2 ? "!" : "";
  74731. });
  74732. booleanString = booleanString.trim();
  74733. if (booleanString === "!true") {
  74734. booleanString = "false";
  74735. }
  74736. else if (booleanString === "!false") {
  74737. booleanString = "true";
  74738. }
  74739. return booleanString;
  74740. };
  74741. return AndOrNotEvaluator;
  74742. }());
  74743. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  74744. })(BABYLON || (BABYLON = {}));
  74745. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  74746. var BABYLON;
  74747. (function (BABYLON) {
  74748. /**
  74749. * Class used to enable access to IndexedDB
  74750. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  74751. */
  74752. var Database = /** @class */ (function () {
  74753. /**
  74754. * Creates a new Database
  74755. * @param urlToScene defines the url to load the scene
  74756. * @param callbackManifestChecked defines the callback to use when manifest is checked
  74757. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  74758. */
  74759. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  74760. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  74761. var _this = this;
  74762. // Handling various flavors of prefixed version of IndexedDB
  74763. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  74764. this.callbackManifestChecked = callbackManifestChecked;
  74765. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  74766. this.db = null;
  74767. this._enableSceneOffline = false;
  74768. this._enableTexturesOffline = false;
  74769. this.manifestVersionFound = 0;
  74770. this.mustUpdateRessources = false;
  74771. this.hasReachedQuota = false;
  74772. if (!Database.IDBStorageEnabled) {
  74773. this.callbackManifestChecked(true);
  74774. }
  74775. else {
  74776. if (disableManifestCheck) {
  74777. this._enableSceneOffline = true;
  74778. this._enableTexturesOffline = true;
  74779. this.manifestVersionFound = 1;
  74780. BABYLON.Tools.SetImmediate(function () {
  74781. _this.callbackManifestChecked(true);
  74782. });
  74783. }
  74784. else {
  74785. this._checkManifestFile();
  74786. }
  74787. }
  74788. }
  74789. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  74790. /**
  74791. * Gets a boolean indicating if scene must be saved in the database
  74792. */
  74793. get: function () {
  74794. return this._enableSceneOffline;
  74795. },
  74796. enumerable: true,
  74797. configurable: true
  74798. });
  74799. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  74800. /**
  74801. * Gets a boolean indicating if textures must be saved in the database
  74802. */
  74803. get: function () {
  74804. return this._enableTexturesOffline;
  74805. },
  74806. enumerable: true,
  74807. configurable: true
  74808. });
  74809. Database.prototype._checkManifestFile = function () {
  74810. var _this = this;
  74811. var noManifestFile = function () {
  74812. _this._enableSceneOffline = false;
  74813. _this._enableTexturesOffline = false;
  74814. _this.callbackManifestChecked(false);
  74815. };
  74816. var timeStampUsed = false;
  74817. var manifestURL = this.currentSceneUrl + ".manifest";
  74818. var xhr = new XMLHttpRequest();
  74819. if (navigator.onLine) {
  74820. // Adding a timestamp to by-pass browsers' cache
  74821. timeStampUsed = true;
  74822. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  74823. }
  74824. xhr.open("GET", manifestURL, true);
  74825. xhr.addEventListener("load", function () {
  74826. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  74827. try {
  74828. var manifestFile = JSON.parse(xhr.response);
  74829. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  74830. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  74831. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  74832. _this.manifestVersionFound = manifestFile.version;
  74833. }
  74834. if (_this.callbackManifestChecked) {
  74835. _this.callbackManifestChecked(true);
  74836. }
  74837. }
  74838. catch (ex) {
  74839. noManifestFile();
  74840. }
  74841. }
  74842. else {
  74843. noManifestFile();
  74844. }
  74845. }, false);
  74846. xhr.addEventListener("error", function (event) {
  74847. if (timeStampUsed) {
  74848. timeStampUsed = false;
  74849. // Let's retry without the timeStamp
  74850. // It could fail when coupled with HTML5 Offline API
  74851. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  74852. xhr.open("GET", retryManifestURL, true);
  74853. xhr.send();
  74854. }
  74855. else {
  74856. noManifestFile();
  74857. }
  74858. }, false);
  74859. try {
  74860. xhr.send();
  74861. }
  74862. catch (ex) {
  74863. BABYLON.Tools.Error("Error on XHR send request.");
  74864. this.callbackManifestChecked(false);
  74865. }
  74866. };
  74867. /**
  74868. * Open the database and make it available
  74869. * @param successCallback defines the callback to call on success
  74870. * @param errorCallback defines the callback to call on error
  74871. */
  74872. Database.prototype.openAsync = function (successCallback, errorCallback) {
  74873. var _this = this;
  74874. var handleError = function () {
  74875. _this.isSupported = false;
  74876. if (errorCallback)
  74877. errorCallback();
  74878. };
  74879. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  74880. // Your browser doesn't support IndexedDB
  74881. this.isSupported = false;
  74882. if (errorCallback)
  74883. errorCallback();
  74884. }
  74885. else {
  74886. // If the DB hasn't been opened or created yet
  74887. if (!this.db) {
  74888. this.hasReachedQuota = false;
  74889. this.isSupported = true;
  74890. var request = this.idbFactory.open("babylonjs", 1);
  74891. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  74892. request.onerror = function (event) {
  74893. handleError();
  74894. };
  74895. // executes when a version change transaction cannot complete due to other active transactions
  74896. request.onblocked = function (event) {
  74897. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  74898. handleError();
  74899. };
  74900. // DB has been opened successfully
  74901. request.onsuccess = function (event) {
  74902. _this.db = request.result;
  74903. successCallback();
  74904. };
  74905. // Initialization of the DB. Creating Scenes & Textures stores
  74906. request.onupgradeneeded = function (event) {
  74907. _this.db = (event.target).result;
  74908. if (_this.db) {
  74909. try {
  74910. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  74911. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  74912. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  74913. }
  74914. catch (ex) {
  74915. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  74916. handleError();
  74917. }
  74918. }
  74919. };
  74920. }
  74921. // DB has already been created and opened
  74922. else {
  74923. if (successCallback)
  74924. successCallback();
  74925. }
  74926. }
  74927. };
  74928. /**
  74929. * Loads an image from the database
  74930. * @param url defines the url to load from
  74931. * @param image defines the target DOM image
  74932. */
  74933. Database.prototype.loadImageFromDB = function (url, image) {
  74934. var _this = this;
  74935. var completeURL = Database._ReturnFullUrlLocation(url);
  74936. var saveAndLoadImage = function () {
  74937. if (!_this.hasReachedQuota && _this.db !== null) {
  74938. // the texture is not yet in the DB, let's try to save it
  74939. _this._saveImageIntoDBAsync(completeURL, image);
  74940. }
  74941. // If the texture is not in the DB and we've reached the DB quota limit
  74942. // let's load it directly from the web
  74943. else {
  74944. image.src = url;
  74945. }
  74946. };
  74947. if (!this.mustUpdateRessources) {
  74948. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  74949. }
  74950. // First time we're download the images or update requested in the manifest file by a version change
  74951. else {
  74952. saveAndLoadImage();
  74953. }
  74954. };
  74955. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  74956. if (this.isSupported && this.db !== null) {
  74957. var texture;
  74958. var transaction = this.db.transaction(["textures"]);
  74959. transaction.onabort = function (event) {
  74960. image.src = url;
  74961. };
  74962. transaction.oncomplete = function (event) {
  74963. var blobTextureURL;
  74964. if (texture) {
  74965. var URL = window.URL || window.webkitURL;
  74966. blobTextureURL = URL.createObjectURL(texture.data);
  74967. image.onerror = function () {
  74968. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  74969. image.src = url;
  74970. };
  74971. image.src = blobTextureURL;
  74972. }
  74973. else {
  74974. notInDBCallback();
  74975. }
  74976. };
  74977. var getRequest = transaction.objectStore("textures").get(url);
  74978. getRequest.onsuccess = function (event) {
  74979. texture = (event.target).result;
  74980. };
  74981. getRequest.onerror = function (event) {
  74982. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  74983. image.src = url;
  74984. };
  74985. }
  74986. else {
  74987. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  74988. image.src = url;
  74989. }
  74990. };
  74991. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  74992. var _this = this;
  74993. if (this.isSupported) {
  74994. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  74995. var generateBlobUrl = function () {
  74996. var blobTextureURL;
  74997. if (blob) {
  74998. var URL = window.URL || window.webkitURL;
  74999. try {
  75000. blobTextureURL = URL.createObjectURL(blob);
  75001. }
  75002. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  75003. catch (ex) {
  75004. blobTextureURL = URL.createObjectURL(blob);
  75005. }
  75006. }
  75007. if (blobTextureURL) {
  75008. image.src = blobTextureURL;
  75009. }
  75010. };
  75011. if (Database.IsUASupportingBlobStorage) { // Create XHR
  75012. var xhr = new XMLHttpRequest(), blob;
  75013. xhr.open("GET", url, true);
  75014. xhr.responseType = "blob";
  75015. xhr.addEventListener("load", function () {
  75016. if (xhr.status === 200 && _this.db) {
  75017. // Blob as response (XHR2)
  75018. blob = xhr.response;
  75019. var transaction = _this.db.transaction(["textures"], "readwrite");
  75020. // the transaction could abort because of a QuotaExceededError error
  75021. transaction.onabort = function (event) {
  75022. try {
  75023. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75024. var srcElement = (event.srcElement || event.target);
  75025. var error = srcElement.error;
  75026. if (error && error.name === "QuotaExceededError") {
  75027. _this.hasReachedQuota = true;
  75028. }
  75029. }
  75030. catch (ex) { }
  75031. generateBlobUrl();
  75032. };
  75033. transaction.oncomplete = function (event) {
  75034. generateBlobUrl();
  75035. };
  75036. var newTexture = { textureUrl: url, data: blob };
  75037. try {
  75038. // Put the blob into the dabase
  75039. var addRequest = transaction.objectStore("textures").put(newTexture);
  75040. addRequest.onsuccess = function (event) {
  75041. };
  75042. addRequest.onerror = function (event) {
  75043. generateBlobUrl();
  75044. };
  75045. }
  75046. catch (ex) {
  75047. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  75048. if (ex.code === 25) {
  75049. Database.IsUASupportingBlobStorage = false;
  75050. }
  75051. image.src = url;
  75052. }
  75053. }
  75054. else {
  75055. image.src = url;
  75056. }
  75057. }, false);
  75058. xhr.addEventListener("error", function (event) {
  75059. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  75060. image.src = url;
  75061. }, false);
  75062. xhr.send();
  75063. }
  75064. else {
  75065. image.src = url;
  75066. }
  75067. }
  75068. else {
  75069. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75070. image.src = url;
  75071. }
  75072. };
  75073. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  75074. var _this = this;
  75075. var updateVersion = function () {
  75076. // the version is not yet in the DB or we need to update it
  75077. _this._saveVersionIntoDBAsync(url, versionLoaded);
  75078. };
  75079. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  75080. };
  75081. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  75082. var _this = this;
  75083. if (this.isSupported && this.db) {
  75084. var version;
  75085. try {
  75086. var transaction = this.db.transaction(["versions"]);
  75087. transaction.oncomplete = function (event) {
  75088. if (version) {
  75089. // If the version in the JSON file is different from the version in DB
  75090. if (_this.manifestVersionFound !== version.data) {
  75091. _this.mustUpdateRessources = true;
  75092. updateInDBCallback();
  75093. }
  75094. else {
  75095. callback(version.data);
  75096. }
  75097. }
  75098. // version was not found in DB
  75099. else {
  75100. _this.mustUpdateRessources = true;
  75101. updateInDBCallback();
  75102. }
  75103. };
  75104. transaction.onabort = function (event) {
  75105. callback(-1);
  75106. };
  75107. var getRequest = transaction.objectStore("versions").get(url);
  75108. getRequest.onsuccess = function (event) {
  75109. version = (event.target).result;
  75110. };
  75111. getRequest.onerror = function (event) {
  75112. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  75113. callback(-1);
  75114. };
  75115. }
  75116. catch (ex) {
  75117. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  75118. callback(-1);
  75119. }
  75120. }
  75121. else {
  75122. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75123. callback(-1);
  75124. }
  75125. };
  75126. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  75127. var _this = this;
  75128. if (this.isSupported && !this.hasReachedQuota && this.db) {
  75129. try {
  75130. // Open a transaction to the database
  75131. var transaction = this.db.transaction(["versions"], "readwrite");
  75132. // the transaction could abort because of a QuotaExceededError error
  75133. transaction.onabort = function (event) {
  75134. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75135. var error = event.srcElement['error'];
  75136. if (error && error.name === "QuotaExceededError") {
  75137. _this.hasReachedQuota = true;
  75138. }
  75139. }
  75140. catch (ex) { }
  75141. callback(-1);
  75142. };
  75143. transaction.oncomplete = function (event) {
  75144. callback(_this.manifestVersionFound);
  75145. };
  75146. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  75147. // Put the scene into the database
  75148. var addRequest = transaction.objectStore("versions").put(newVersion);
  75149. addRequest.onsuccess = function (event) {
  75150. };
  75151. addRequest.onerror = function (event) {
  75152. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  75153. };
  75154. }
  75155. catch (ex) {
  75156. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  75157. callback(-1);
  75158. }
  75159. }
  75160. else {
  75161. callback(-1);
  75162. }
  75163. };
  75164. /**
  75165. * Loads a file from database
  75166. * @param url defines the URL to load from
  75167. * @param sceneLoaded defines a callback to call on success
  75168. * @param progressCallBack defines a callback to call when progress changed
  75169. * @param errorCallback defines a callback to call on error
  75170. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  75171. */
  75172. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  75173. var _this = this;
  75174. var completeUrl = Database._ReturnFullUrlLocation(url);
  75175. var saveAndLoadFile = function () {
  75176. // the scene is not yet in the DB, let's try to save it
  75177. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75178. };
  75179. this._checkVersionFromDB(completeUrl, function (version) {
  75180. if (version !== -1) {
  75181. if (!_this.mustUpdateRessources) {
  75182. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  75183. }
  75184. else {
  75185. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  75186. }
  75187. }
  75188. else {
  75189. if (errorCallback) {
  75190. errorCallback();
  75191. }
  75192. }
  75193. });
  75194. };
  75195. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  75196. if (this.isSupported && this.db) {
  75197. var targetStore;
  75198. if (url.indexOf(".babylon") !== -1) {
  75199. targetStore = "scenes";
  75200. }
  75201. else {
  75202. targetStore = "textures";
  75203. }
  75204. var file;
  75205. var transaction = this.db.transaction([targetStore]);
  75206. transaction.oncomplete = function (event) {
  75207. if (file) {
  75208. callback(file.data);
  75209. }
  75210. // file was not found in DB
  75211. else {
  75212. notInDBCallback();
  75213. }
  75214. };
  75215. transaction.onabort = function (event) {
  75216. notInDBCallback();
  75217. };
  75218. var getRequest = transaction.objectStore(targetStore).get(url);
  75219. getRequest.onsuccess = function (event) {
  75220. file = (event.target).result;
  75221. };
  75222. getRequest.onerror = function (event) {
  75223. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  75224. notInDBCallback();
  75225. };
  75226. }
  75227. else {
  75228. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75229. callback();
  75230. }
  75231. };
  75232. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  75233. var _this = this;
  75234. if (this.isSupported) {
  75235. var targetStore;
  75236. if (url.indexOf(".babylon") !== -1) {
  75237. targetStore = "scenes";
  75238. }
  75239. else {
  75240. targetStore = "textures";
  75241. }
  75242. // Create XHR
  75243. var xhr = new XMLHttpRequest();
  75244. var fileData;
  75245. xhr.open("GET", url + "?" + Date.now(), true);
  75246. if (useArrayBuffer) {
  75247. xhr.responseType = "arraybuffer";
  75248. }
  75249. if (progressCallback) {
  75250. xhr.onprogress = progressCallback;
  75251. }
  75252. xhr.addEventListener("load", function () {
  75253. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  75254. // Blob as response (XHR2)
  75255. //fileData = xhr.responseText;
  75256. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  75257. if (!_this.hasReachedQuota && _this.db) {
  75258. // Open a transaction to the database
  75259. var transaction = _this.db.transaction([targetStore], "readwrite");
  75260. // the transaction could abort because of a QuotaExceededError error
  75261. transaction.onabort = function (event) {
  75262. try {
  75263. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  75264. var error = event.srcElement['error'];
  75265. if (error && error.name === "QuotaExceededError") {
  75266. _this.hasReachedQuota = true;
  75267. }
  75268. }
  75269. catch (ex) { }
  75270. callback(fileData);
  75271. };
  75272. transaction.oncomplete = function (event) {
  75273. callback(fileData);
  75274. };
  75275. var newFile;
  75276. if (targetStore === "scenes") {
  75277. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  75278. }
  75279. else {
  75280. newFile = { textureUrl: url, data: fileData };
  75281. }
  75282. try {
  75283. // Put the scene into the database
  75284. var addRequest = transaction.objectStore(targetStore).put(newFile);
  75285. addRequest.onsuccess = function (event) {
  75286. };
  75287. addRequest.onerror = function (event) {
  75288. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  75289. };
  75290. }
  75291. catch (ex) {
  75292. callback(fileData);
  75293. }
  75294. }
  75295. else {
  75296. callback(fileData);
  75297. }
  75298. }
  75299. else {
  75300. if (xhr.status >= 400 && errorCallback) {
  75301. errorCallback(xhr);
  75302. }
  75303. else {
  75304. callback();
  75305. }
  75306. }
  75307. }, false);
  75308. xhr.addEventListener("error", function (event) {
  75309. BABYLON.Tools.Error("error on XHR request.");
  75310. callback();
  75311. }, false);
  75312. xhr.send();
  75313. }
  75314. else {
  75315. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  75316. callback();
  75317. }
  75318. };
  75319. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  75320. Database.IsUASupportingBlobStorage = true;
  75321. /** Gets a boolean indicating if Database storate is enabled */
  75322. Database.IDBStorageEnabled = true;
  75323. Database._ParseURL = function (url) {
  75324. var a = document.createElement('a');
  75325. a.href = url;
  75326. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  75327. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  75328. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  75329. return absLocation;
  75330. };
  75331. Database._ReturnFullUrlLocation = function (url) {
  75332. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  75333. return (Database._ParseURL(window.location.href) + url);
  75334. }
  75335. else {
  75336. return url;
  75337. }
  75338. };
  75339. return Database;
  75340. }());
  75341. BABYLON.Database = Database;
  75342. })(BABYLON || (BABYLON = {}));
  75343. //# sourceMappingURL=babylon.database.js.map
  75344. var BABYLON;
  75345. (function (BABYLON) {
  75346. var FresnelParameters = /** @class */ (function () {
  75347. function FresnelParameters() {
  75348. this._isEnabled = true;
  75349. this.leftColor = BABYLON.Color3.White();
  75350. this.rightColor = BABYLON.Color3.Black();
  75351. this.bias = 0;
  75352. this.power = 1;
  75353. }
  75354. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  75355. get: function () {
  75356. return this._isEnabled;
  75357. },
  75358. set: function (value) {
  75359. if (this._isEnabled === value) {
  75360. return;
  75361. }
  75362. this._isEnabled = value;
  75363. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  75364. },
  75365. enumerable: true,
  75366. configurable: true
  75367. });
  75368. FresnelParameters.prototype.clone = function () {
  75369. var newFresnelParameters = new FresnelParameters();
  75370. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  75371. return newFresnelParameters;
  75372. };
  75373. FresnelParameters.prototype.serialize = function () {
  75374. var serializationObject = {};
  75375. serializationObject.isEnabled = this.isEnabled;
  75376. serializationObject.leftColor = this.leftColor.asArray();
  75377. serializationObject.rightColor = this.rightColor.asArray();
  75378. serializationObject.bias = this.bias;
  75379. serializationObject.power = this.power;
  75380. return serializationObject;
  75381. };
  75382. FresnelParameters.Parse = function (parsedFresnelParameters) {
  75383. var fresnelParameters = new FresnelParameters();
  75384. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  75385. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  75386. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  75387. fresnelParameters.bias = parsedFresnelParameters.bias;
  75388. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  75389. return fresnelParameters;
  75390. };
  75391. return FresnelParameters;
  75392. }());
  75393. BABYLON.FresnelParameters = FresnelParameters;
  75394. })(BABYLON || (BABYLON = {}));
  75395. //# sourceMappingURL=babylon.fresnelParameters.js.map
  75396. var BABYLON;
  75397. (function (BABYLON) {
  75398. var MultiMaterial = /** @class */ (function (_super) {
  75399. __extends(MultiMaterial, _super);
  75400. function MultiMaterial(name, scene) {
  75401. var _this = _super.call(this, name, scene, true) || this;
  75402. scene.multiMaterials.push(_this);
  75403. _this.subMaterials = new Array();
  75404. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  75405. return _this;
  75406. }
  75407. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  75408. get: function () {
  75409. return this._subMaterials;
  75410. },
  75411. set: function (value) {
  75412. this._subMaterials = value;
  75413. this._hookArray(value);
  75414. },
  75415. enumerable: true,
  75416. configurable: true
  75417. });
  75418. MultiMaterial.prototype._hookArray = function (array) {
  75419. var _this = this;
  75420. var oldPush = array.push;
  75421. array.push = function () {
  75422. var items = [];
  75423. for (var _i = 0; _i < arguments.length; _i++) {
  75424. items[_i] = arguments[_i];
  75425. }
  75426. var result = oldPush.apply(array, items);
  75427. _this._markAllSubMeshesAsTexturesDirty();
  75428. return result;
  75429. };
  75430. var oldSplice = array.splice;
  75431. array.splice = function (index, deleteCount) {
  75432. var deleted = oldSplice.apply(array, [index, deleteCount]);
  75433. _this._markAllSubMeshesAsTexturesDirty();
  75434. return deleted;
  75435. };
  75436. };
  75437. // Properties
  75438. MultiMaterial.prototype.getSubMaterial = function (index) {
  75439. if (index < 0 || index >= this.subMaterials.length) {
  75440. return this.getScene().defaultMaterial;
  75441. }
  75442. return this.subMaterials[index];
  75443. };
  75444. MultiMaterial.prototype.getActiveTextures = function () {
  75445. var _a;
  75446. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  75447. if (subMaterial) {
  75448. return subMaterial.getActiveTextures();
  75449. }
  75450. else {
  75451. return [];
  75452. }
  75453. }));
  75454. };
  75455. // Methods
  75456. MultiMaterial.prototype.getClassName = function () {
  75457. return "MultiMaterial";
  75458. };
  75459. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  75460. for (var index = 0; index < this.subMaterials.length; index++) {
  75461. var subMaterial = this.subMaterials[index];
  75462. if (subMaterial) {
  75463. if (subMaterial.storeEffectOnSubMeshes) {
  75464. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  75465. return false;
  75466. }
  75467. continue;
  75468. }
  75469. if (!subMaterial.isReady(mesh)) {
  75470. return false;
  75471. }
  75472. }
  75473. }
  75474. return true;
  75475. };
  75476. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  75477. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  75478. for (var index = 0; index < this.subMaterials.length; index++) {
  75479. var subMaterial = null;
  75480. var current = this.subMaterials[index];
  75481. if (cloneChildren && current) {
  75482. subMaterial = current.clone(name + "-" + current.name);
  75483. }
  75484. else {
  75485. subMaterial = this.subMaterials[index];
  75486. }
  75487. newMultiMaterial.subMaterials.push(subMaterial);
  75488. }
  75489. return newMultiMaterial;
  75490. };
  75491. MultiMaterial.prototype.serialize = function () {
  75492. var serializationObject = {};
  75493. serializationObject.name = this.name;
  75494. serializationObject.id = this.id;
  75495. if (BABYLON.Tags) {
  75496. serializationObject.tags = BABYLON.Tags.GetTags(this);
  75497. }
  75498. serializationObject.materials = [];
  75499. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  75500. var subMat = this.subMaterials[matIndex];
  75501. if (subMat) {
  75502. serializationObject.materials.push(subMat.id);
  75503. }
  75504. else {
  75505. serializationObject.materials.push(null);
  75506. }
  75507. }
  75508. return serializationObject;
  75509. };
  75510. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  75511. var scene = this.getScene();
  75512. if (!scene) {
  75513. return;
  75514. }
  75515. var index = scene.multiMaterials.indexOf(this);
  75516. if (index >= 0) {
  75517. scene.multiMaterials.splice(index, 1);
  75518. }
  75519. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  75520. };
  75521. return MultiMaterial;
  75522. }(BABYLON.Material));
  75523. BABYLON.MultiMaterial = MultiMaterial;
  75524. })(BABYLON || (BABYLON = {}));
  75525. //# sourceMappingURL=babylon.multiMaterial.js.map
  75526. var BABYLON;
  75527. (function (BABYLON) {
  75528. /**
  75529. * Manage the touch inputs to control the movement of a free camera.
  75530. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  75531. */
  75532. var FreeCameraTouchInput = /** @class */ (function () {
  75533. function FreeCameraTouchInput() {
  75534. /**
  75535. * Defines the touch sensibility for rotation.
  75536. * The higher the faster.
  75537. */
  75538. this.touchAngularSensibility = 200000.0;
  75539. /**
  75540. * Defines the touch sensibility for move.
  75541. * The higher the faster.
  75542. */
  75543. this.touchMoveSensibility = 250.0;
  75544. this._offsetX = null;
  75545. this._offsetY = null;
  75546. this._pointerPressed = new Array();
  75547. }
  75548. /**
  75549. * Attach the input controls to a specific dom element to get the input from.
  75550. * @param element Defines the element the controls should be listened from
  75551. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  75552. */
  75553. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  75554. var _this = this;
  75555. var previousPosition = null;
  75556. if (this._pointerInput === undefined) {
  75557. this._onLostFocus = function (evt) {
  75558. _this._offsetX = null;
  75559. _this._offsetY = null;
  75560. };
  75561. this._pointerInput = function (p, s) {
  75562. var evt = p.event;
  75563. if (evt.pointerType === "mouse") {
  75564. return;
  75565. }
  75566. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  75567. if (!noPreventDefault) {
  75568. evt.preventDefault();
  75569. }
  75570. _this._pointerPressed.push(evt.pointerId);
  75571. if (_this._pointerPressed.length !== 1) {
  75572. return;
  75573. }
  75574. previousPosition = {
  75575. x: evt.clientX,
  75576. y: evt.clientY
  75577. };
  75578. }
  75579. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  75580. if (!noPreventDefault) {
  75581. evt.preventDefault();
  75582. }
  75583. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75584. if (index === -1) {
  75585. return;
  75586. }
  75587. _this._pointerPressed.splice(index, 1);
  75588. if (index != 0) {
  75589. return;
  75590. }
  75591. previousPosition = null;
  75592. _this._offsetX = null;
  75593. _this._offsetY = null;
  75594. }
  75595. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  75596. if (!noPreventDefault) {
  75597. evt.preventDefault();
  75598. }
  75599. if (!previousPosition) {
  75600. return;
  75601. }
  75602. var index = _this._pointerPressed.indexOf(evt.pointerId);
  75603. if (index != 0) {
  75604. return;
  75605. }
  75606. _this._offsetX = evt.clientX - previousPosition.x;
  75607. _this._offsetY = -(evt.clientY - previousPosition.y);
  75608. }
  75609. };
  75610. }
  75611. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  75612. if (this._onLostFocus) {
  75613. element.addEventListener("blur", this._onLostFocus);
  75614. }
  75615. };
  75616. /**
  75617. * Detach the current controls from the specified dom element.
  75618. * @param element Defines the element to stop listening the inputs from
  75619. */
  75620. FreeCameraTouchInput.prototype.detachControl = function (element) {
  75621. if (this._pointerInput && element) {
  75622. if (this._observer) {
  75623. this.camera.getScene().onPointerObservable.remove(this._observer);
  75624. this._observer = null;
  75625. }
  75626. if (this._onLostFocus) {
  75627. element.removeEventListener("blur", this._onLostFocus);
  75628. this._onLostFocus = null;
  75629. }
  75630. this._pointerPressed = [];
  75631. this._offsetX = null;
  75632. this._offsetY = null;
  75633. }
  75634. };
  75635. /**
  75636. * Update the current camera state depending on the inputs that have been used this frame.
  75637. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  75638. */
  75639. FreeCameraTouchInput.prototype.checkInputs = function () {
  75640. if (this._offsetX && this._offsetY) {
  75641. var camera = this.camera;
  75642. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  75643. if (this._pointerPressed.length > 1) {
  75644. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  75645. }
  75646. else {
  75647. var speed = camera._computeLocalCameraSpeed();
  75648. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  75649. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  75650. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  75651. }
  75652. }
  75653. };
  75654. /**
  75655. * Gets the class name of the current intput.
  75656. * @returns the class name
  75657. */
  75658. FreeCameraTouchInput.prototype.getClassName = function () {
  75659. return "FreeCameraTouchInput";
  75660. };
  75661. /**
  75662. * Get the friendly name associated with the input class.
  75663. * @returns the input friendly name
  75664. */
  75665. FreeCameraTouchInput.prototype.getSimpleName = function () {
  75666. return "touch";
  75667. };
  75668. __decorate([
  75669. BABYLON.serialize()
  75670. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  75671. __decorate([
  75672. BABYLON.serialize()
  75673. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  75674. return FreeCameraTouchInput;
  75675. }());
  75676. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  75677. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  75678. })(BABYLON || (BABYLON = {}));
  75679. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  75680. var BABYLON;
  75681. (function (BABYLON) {
  75682. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  75683. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  75684. });
  75685. /**
  75686. * This represents a FPS type of camera controlled by touch.
  75687. * This is like a universal camera minus the Gamepad controls.
  75688. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  75689. */
  75690. var TouchCamera = /** @class */ (function (_super) {
  75691. __extends(TouchCamera, _super);
  75692. /**
  75693. * Instantiates a new touch camera.
  75694. * This represents a FPS type of camera controlled by touch.
  75695. * This is like a universal camera minus the Gamepad controls.
  75696. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  75697. * @param name Define the name of the camera in the scene
  75698. * @param position Define the start position of the camera in the scene
  75699. * @param scene Define the scene the camera belongs to
  75700. */
  75701. function TouchCamera(name, position, scene) {
  75702. var _this = _super.call(this, name, position, scene) || this;
  75703. _this.inputs.addTouch();
  75704. _this._setupInputs();
  75705. return _this;
  75706. }
  75707. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  75708. /**
  75709. * Defines the touch sensibility for rotation.
  75710. * The higher the faster.
  75711. */
  75712. get: function () {
  75713. var touch = this.inputs.attached["touch"];
  75714. if (touch)
  75715. return touch.touchAngularSensibility;
  75716. return 0;
  75717. },
  75718. set: function (value) {
  75719. var touch = this.inputs.attached["touch"];
  75720. if (touch)
  75721. touch.touchAngularSensibility = value;
  75722. },
  75723. enumerable: true,
  75724. configurable: true
  75725. });
  75726. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  75727. /**
  75728. * Defines the touch sensibility for move.
  75729. * The higher the faster.
  75730. */
  75731. get: function () {
  75732. var touch = this.inputs.attached["touch"];
  75733. if (touch)
  75734. return touch.touchMoveSensibility;
  75735. return 0;
  75736. },
  75737. set: function (value) {
  75738. var touch = this.inputs.attached["touch"];
  75739. if (touch)
  75740. touch.touchMoveSensibility = value;
  75741. },
  75742. enumerable: true,
  75743. configurable: true
  75744. });
  75745. /**
  75746. * Gets the current object class name.
  75747. * @return the class name
  75748. */
  75749. TouchCamera.prototype.getClassName = function () {
  75750. return "TouchCamera";
  75751. };
  75752. /** @hidden */
  75753. TouchCamera.prototype._setupInputs = function () {
  75754. var mouse = this.inputs.attached["mouse"];
  75755. if (mouse) {
  75756. mouse.touchEnabled = false;
  75757. }
  75758. };
  75759. return TouchCamera;
  75760. }(BABYLON.FreeCamera));
  75761. BABYLON.TouchCamera = TouchCamera;
  75762. })(BABYLON || (BABYLON = {}));
  75763. //# sourceMappingURL=babylon.touchCamera.js.map
  75764. var BABYLON;
  75765. (function (BABYLON) {
  75766. var ProceduralTexture = /** @class */ (function (_super) {
  75767. __extends(ProceduralTexture, _super);
  75768. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  75769. if (fallbackTexture === void 0) { fallbackTexture = null; }
  75770. if (generateMipMaps === void 0) { generateMipMaps = true; }
  75771. if (isCube === void 0) { isCube = false; }
  75772. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  75773. _this.isCube = isCube;
  75774. _this.isEnabled = true;
  75775. _this._currentRefreshId = -1;
  75776. _this._refreshRate = 1;
  75777. /**
  75778. * Event raised when the texture is generated
  75779. */
  75780. _this.onGeneratedObservable = new BABYLON.Observable();
  75781. _this._vertexBuffers = {};
  75782. _this._uniforms = new Array();
  75783. _this._samplers = new Array();
  75784. /** @hidden */
  75785. _this._textures = {};
  75786. _this._floats = {};
  75787. _this._ints = {};
  75788. _this._floatsArrays = {};
  75789. _this._colors3 = {};
  75790. _this._colors4 = {};
  75791. _this._vectors2 = {};
  75792. _this._vectors3 = {};
  75793. _this._matrices = {};
  75794. _this._fallbackTextureUsed = false;
  75795. _this._cachedDefines = "";
  75796. _this._contentUpdateId = -1;
  75797. scene = _this.getScene();
  75798. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  75799. if (!component) {
  75800. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  75801. scene._addComponent(component);
  75802. }
  75803. scene.proceduralTextures.push(_this);
  75804. _this._engine = scene.getEngine();
  75805. _this.name = name;
  75806. _this.isRenderTarget = true;
  75807. _this._size = size;
  75808. _this._generateMipMaps = generateMipMaps;
  75809. _this.setFragment(fragment);
  75810. _this._fallbackTexture = fallbackTexture;
  75811. if (isCube) {
  75812. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  75813. _this.setFloat("face", 0);
  75814. }
  75815. else {
  75816. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  75817. }
  75818. // VBO
  75819. var vertices = [];
  75820. vertices.push(1, 1);
  75821. vertices.push(-1, 1);
  75822. vertices.push(-1, -1);
  75823. vertices.push(1, -1);
  75824. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75825. _this._createIndexBuffer();
  75826. return _this;
  75827. }
  75828. /**
  75829. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  75830. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  75831. */
  75832. ProceduralTexture.prototype.getContent = function () {
  75833. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  75834. return this._contentData;
  75835. }
  75836. this._contentData = this.readPixels(0, 0, this._contentData);
  75837. this._contentUpdateId = this._currentRefreshId;
  75838. return this._contentData;
  75839. };
  75840. ProceduralTexture.prototype._createIndexBuffer = function () {
  75841. var engine = this._engine;
  75842. // Indices
  75843. var indices = [];
  75844. indices.push(0);
  75845. indices.push(1);
  75846. indices.push(2);
  75847. indices.push(0);
  75848. indices.push(2);
  75849. indices.push(3);
  75850. this._indexBuffer = engine.createIndexBuffer(indices);
  75851. };
  75852. /** @hidden */
  75853. ProceduralTexture.prototype._rebuild = function () {
  75854. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75855. if (vb) {
  75856. vb._rebuild();
  75857. }
  75858. this._createIndexBuffer();
  75859. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  75860. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  75861. }
  75862. };
  75863. ProceduralTexture.prototype.reset = function () {
  75864. if (this._effect === undefined) {
  75865. return;
  75866. }
  75867. var engine = this._engine;
  75868. engine._releaseEffect(this._effect);
  75869. };
  75870. ProceduralTexture.prototype._getDefines = function () {
  75871. return "";
  75872. };
  75873. ProceduralTexture.prototype.isReady = function () {
  75874. var _this = this;
  75875. var engine = this._engine;
  75876. var shaders;
  75877. if (!this._fragment) {
  75878. return false;
  75879. }
  75880. if (this._fallbackTextureUsed) {
  75881. return true;
  75882. }
  75883. var defines = this._getDefines();
  75884. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  75885. return true;
  75886. }
  75887. if (this._fragment.fragmentElement !== undefined) {
  75888. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  75889. }
  75890. else {
  75891. shaders = { vertex: "procedural", fragment: this._fragment };
  75892. }
  75893. this._cachedDefines = defines;
  75894. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  75895. _this.releaseInternalTexture();
  75896. if (_this._fallbackTexture) {
  75897. _this._texture = _this._fallbackTexture._texture;
  75898. if (_this._texture) {
  75899. _this._texture.incrementReferences();
  75900. }
  75901. }
  75902. _this._fallbackTextureUsed = true;
  75903. });
  75904. return this._effect.isReady();
  75905. };
  75906. ProceduralTexture.prototype.resetRefreshCounter = function () {
  75907. this._currentRefreshId = -1;
  75908. };
  75909. ProceduralTexture.prototype.setFragment = function (fragment) {
  75910. this._fragment = fragment;
  75911. };
  75912. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  75913. get: function () {
  75914. return this._refreshRate;
  75915. },
  75916. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  75917. set: function (value) {
  75918. this._refreshRate = value;
  75919. this.resetRefreshCounter();
  75920. },
  75921. enumerable: true,
  75922. configurable: true
  75923. });
  75924. /** @hidden */
  75925. ProceduralTexture.prototype._shouldRender = function () {
  75926. if (!this.isEnabled || !this.isReady() || !this._texture) {
  75927. if (this._texture) {
  75928. this._texture.isReady = false;
  75929. }
  75930. return false;
  75931. }
  75932. if (this._fallbackTextureUsed) {
  75933. return false;
  75934. }
  75935. if (this._currentRefreshId === -1) { // At least render once
  75936. this._currentRefreshId = 1;
  75937. return true;
  75938. }
  75939. if (this.refreshRate === this._currentRefreshId) {
  75940. this._currentRefreshId = 1;
  75941. return true;
  75942. }
  75943. this._currentRefreshId++;
  75944. return false;
  75945. };
  75946. ProceduralTexture.prototype.getRenderSize = function () {
  75947. return this._size;
  75948. };
  75949. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  75950. if (this._fallbackTextureUsed) {
  75951. return;
  75952. }
  75953. this.releaseInternalTexture();
  75954. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  75955. // Update properties
  75956. this._size = size;
  75957. this._generateMipMaps = generateMipMaps;
  75958. };
  75959. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  75960. if (this._uniforms.indexOf(uniformName) === -1) {
  75961. this._uniforms.push(uniformName);
  75962. }
  75963. };
  75964. ProceduralTexture.prototype.setTexture = function (name, texture) {
  75965. if (this._samplers.indexOf(name) === -1) {
  75966. this._samplers.push(name);
  75967. }
  75968. this._textures[name] = texture;
  75969. return this;
  75970. };
  75971. ProceduralTexture.prototype.setFloat = function (name, value) {
  75972. this._checkUniform(name);
  75973. this._floats[name] = value;
  75974. return this;
  75975. };
  75976. /**
  75977. * Set the value of an uniform to an integer value
  75978. * @param name defines the name of the uniform
  75979. * @param value defines the value to set
  75980. * @returns the current procedural texture
  75981. */
  75982. ProceduralTexture.prototype.setInt = function (name, value) {
  75983. this._checkUniform(name);
  75984. this._ints[name] = value;
  75985. return this;
  75986. };
  75987. ProceduralTexture.prototype.setFloats = function (name, value) {
  75988. this._checkUniform(name);
  75989. this._floatsArrays[name] = value;
  75990. return this;
  75991. };
  75992. ProceduralTexture.prototype.setColor3 = function (name, value) {
  75993. this._checkUniform(name);
  75994. this._colors3[name] = value;
  75995. return this;
  75996. };
  75997. ProceduralTexture.prototype.setColor4 = function (name, value) {
  75998. this._checkUniform(name);
  75999. this._colors4[name] = value;
  76000. return this;
  76001. };
  76002. ProceduralTexture.prototype.setVector2 = function (name, value) {
  76003. this._checkUniform(name);
  76004. this._vectors2[name] = value;
  76005. return this;
  76006. };
  76007. ProceduralTexture.prototype.setVector3 = function (name, value) {
  76008. this._checkUniform(name);
  76009. this._vectors3[name] = value;
  76010. return this;
  76011. };
  76012. ProceduralTexture.prototype.setMatrix = function (name, value) {
  76013. this._checkUniform(name);
  76014. this._matrices[name] = value;
  76015. return this;
  76016. };
  76017. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76018. var scene = this.getScene();
  76019. if (!scene) {
  76020. return;
  76021. }
  76022. var engine = this._engine;
  76023. // Render
  76024. engine.enableEffect(this._effect);
  76025. engine.setState(false);
  76026. // Texture
  76027. for (var name in this._textures) {
  76028. this._effect.setTexture(name, this._textures[name]);
  76029. }
  76030. // Float
  76031. for (name in this._ints) {
  76032. this._effect.setInt(name, this._ints[name]);
  76033. }
  76034. // Float
  76035. for (name in this._floats) {
  76036. this._effect.setFloat(name, this._floats[name]);
  76037. }
  76038. // Floats
  76039. for (name in this._floatsArrays) {
  76040. this._effect.setArray(name, this._floatsArrays[name]);
  76041. }
  76042. // Color3
  76043. for (name in this._colors3) {
  76044. this._effect.setColor3(name, this._colors3[name]);
  76045. }
  76046. // Color4
  76047. for (name in this._colors4) {
  76048. var color = this._colors4[name];
  76049. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  76050. }
  76051. // Vector2
  76052. for (name in this._vectors2) {
  76053. this._effect.setVector2(name, this._vectors2[name]);
  76054. }
  76055. // Vector3
  76056. for (name in this._vectors3) {
  76057. this._effect.setVector3(name, this._vectors3[name]);
  76058. }
  76059. // Matrix
  76060. for (name in this._matrices) {
  76061. this._effect.setMatrix(name, this._matrices[name]);
  76062. }
  76063. if (!this._texture) {
  76064. return;
  76065. }
  76066. if (this.isCube) {
  76067. for (var face = 0; face < 6; face++) {
  76068. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  76069. // VBOs
  76070. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76071. this._effect.setFloat("face", face);
  76072. // Clear
  76073. engine.clear(scene.clearColor, true, true, true);
  76074. // Draw order
  76075. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76076. // Mipmaps
  76077. if (face === 5) {
  76078. engine.generateMipMapsForCubemap(this._texture);
  76079. }
  76080. }
  76081. }
  76082. else {
  76083. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  76084. // VBOs
  76085. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76086. // Clear
  76087. engine.clear(scene.clearColor, true, true, true);
  76088. // Draw order
  76089. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76090. }
  76091. // Unbind
  76092. engine.unBindFramebuffer(this._texture, this.isCube);
  76093. if (this.onGenerated) {
  76094. this.onGenerated();
  76095. }
  76096. this.onGeneratedObservable.notifyObservers(this);
  76097. };
  76098. ProceduralTexture.prototype.clone = function () {
  76099. var textureSize = this.getSize();
  76100. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  76101. // Base texture
  76102. newTexture.hasAlpha = this.hasAlpha;
  76103. newTexture.level = this.level;
  76104. // RenderTarget Texture
  76105. newTexture.coordinatesMode = this.coordinatesMode;
  76106. return newTexture;
  76107. };
  76108. ProceduralTexture.prototype.dispose = function () {
  76109. var scene = this.getScene();
  76110. if (!scene) {
  76111. return;
  76112. }
  76113. var index = scene.proceduralTextures.indexOf(this);
  76114. if (index >= 0) {
  76115. scene.proceduralTextures.splice(index, 1);
  76116. }
  76117. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76118. if (vertexBuffer) {
  76119. vertexBuffer.dispose();
  76120. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76121. }
  76122. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  76123. this._indexBuffer = null;
  76124. }
  76125. _super.prototype.dispose.call(this);
  76126. };
  76127. __decorate([
  76128. BABYLON.serialize()
  76129. ], ProceduralTexture.prototype, "_size", void 0);
  76130. __decorate([
  76131. BABYLON.serialize()
  76132. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  76133. __decorate([
  76134. BABYLON.serialize()
  76135. ], ProceduralTexture.prototype, "isEnabled", void 0);
  76136. __decorate([
  76137. BABYLON.serialize()
  76138. ], ProceduralTexture.prototype, "refreshRate", null);
  76139. return ProceduralTexture;
  76140. }(BABYLON.Texture));
  76141. BABYLON.ProceduralTexture = ProceduralTexture;
  76142. })(BABYLON || (BABYLON = {}));
  76143. //# sourceMappingURL=babylon.proceduralTexture.js.map
  76144. var BABYLON;
  76145. (function (BABYLON) {
  76146. /**
  76147. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  76148. * in a given scene.
  76149. */
  76150. var ProceduralTextureSceneComponent = /** @class */ (function () {
  76151. /**
  76152. * Creates a new instance of the component for the given scene
  76153. * @param scene Defines the scene to register the component in
  76154. */
  76155. function ProceduralTextureSceneComponent(scene) {
  76156. /**
  76157. * The component name helpfull to identify the component in the list of scene components.
  76158. */
  76159. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  76160. this.scene = scene;
  76161. this.scene.proceduralTextures = new Array();
  76162. scene.layers = new Array();
  76163. }
  76164. /**
  76165. * Registers the component in a given scene
  76166. */
  76167. ProceduralTextureSceneComponent.prototype.register = function () {
  76168. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  76169. };
  76170. /**
  76171. * Rebuilds the elements related to this component in case of
  76172. * context lost for instance.
  76173. */
  76174. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  76175. // Nothing to do here.
  76176. };
  76177. /**
  76178. * Disposes the component and the associated ressources.
  76179. */
  76180. ProceduralTextureSceneComponent.prototype.dispose = function () {
  76181. // Nothing to do here.
  76182. };
  76183. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  76184. if (this.scene.proceduralTexturesEnabled) {
  76185. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76186. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  76187. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  76188. if (proceduralTexture._shouldRender()) {
  76189. proceduralTexture.render();
  76190. }
  76191. }
  76192. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  76193. }
  76194. };
  76195. return ProceduralTextureSceneComponent;
  76196. }());
  76197. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  76198. })(BABYLON || (BABYLON = {}));
  76199. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  76200. var BABYLON;
  76201. (function (BABYLON) {
  76202. var CustomProceduralTexture = /** @class */ (function (_super) {
  76203. __extends(CustomProceduralTexture, _super);
  76204. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  76205. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  76206. _this._animate = true;
  76207. _this._time = 0;
  76208. _this._texturePath = texturePath;
  76209. //Try to load json
  76210. _this.loadJson(texturePath);
  76211. _this.refreshRate = 1;
  76212. return _this;
  76213. }
  76214. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  76215. var _this = this;
  76216. var noConfigFile = function () {
  76217. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  76218. try {
  76219. _this.setFragment(_this._texturePath);
  76220. }
  76221. catch (ex) {
  76222. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  76223. }
  76224. };
  76225. var configFileUrl = jsonUrl + "/config.json";
  76226. var xhr = new XMLHttpRequest();
  76227. xhr.open("GET", configFileUrl, true);
  76228. xhr.addEventListener("load", function () {
  76229. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  76230. try {
  76231. _this._config = JSON.parse(xhr.response);
  76232. _this.updateShaderUniforms();
  76233. _this.updateTextures();
  76234. _this.setFragment(_this._texturePath + "/custom");
  76235. _this._animate = _this._config.animate;
  76236. _this.refreshRate = _this._config.refreshrate;
  76237. }
  76238. catch (ex) {
  76239. noConfigFile();
  76240. }
  76241. }
  76242. else {
  76243. noConfigFile();
  76244. }
  76245. }, false);
  76246. xhr.addEventListener("error", function () {
  76247. noConfigFile();
  76248. }, false);
  76249. try {
  76250. xhr.send();
  76251. }
  76252. catch (ex) {
  76253. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  76254. }
  76255. };
  76256. CustomProceduralTexture.prototype.isReady = function () {
  76257. if (!_super.prototype.isReady.call(this)) {
  76258. return false;
  76259. }
  76260. for (var name in this._textures) {
  76261. var texture = this._textures[name];
  76262. if (!texture.isReady()) {
  76263. return false;
  76264. }
  76265. }
  76266. return true;
  76267. };
  76268. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  76269. var scene = this.getScene();
  76270. if (this._animate && scene) {
  76271. this._time += scene.getAnimationRatio() * 0.03;
  76272. this.updateShaderUniforms();
  76273. }
  76274. _super.prototype.render.call(this, useCameraPostProcess);
  76275. };
  76276. CustomProceduralTexture.prototype.updateTextures = function () {
  76277. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  76278. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  76279. }
  76280. };
  76281. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  76282. if (this._config) {
  76283. for (var j = 0; j < this._config.uniforms.length; j++) {
  76284. var uniform = this._config.uniforms[j];
  76285. switch (uniform.type) {
  76286. case "float":
  76287. this.setFloat(uniform.name, uniform.value);
  76288. break;
  76289. case "color3":
  76290. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  76291. break;
  76292. case "color4":
  76293. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  76294. break;
  76295. case "vector2":
  76296. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  76297. break;
  76298. case "vector3":
  76299. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  76300. break;
  76301. }
  76302. }
  76303. }
  76304. this.setFloat("time", this._time);
  76305. };
  76306. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  76307. get: function () {
  76308. return this._animate;
  76309. },
  76310. set: function (value) {
  76311. this._animate = value;
  76312. },
  76313. enumerable: true,
  76314. configurable: true
  76315. });
  76316. return CustomProceduralTexture;
  76317. }(BABYLON.ProceduralTexture));
  76318. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  76319. })(BABYLON || (BABYLON = {}));
  76320. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  76321. var BABYLON;
  76322. (function (BABYLON) {
  76323. /**
  76324. * Manage the gamepad inputs to control a free camera.
  76325. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76326. */
  76327. var FreeCameraGamepadInput = /** @class */ (function () {
  76328. function FreeCameraGamepadInput() {
  76329. /**
  76330. * Defines the gamepad rotation sensiblity.
  76331. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76332. */
  76333. this.gamepadAngularSensibility = 200;
  76334. /**
  76335. * Defines the gamepad move sensiblity.
  76336. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76337. */
  76338. this.gamepadMoveSensibility = 40;
  76339. this._cameraTransform = BABYLON.Matrix.Identity();
  76340. this._deltaTransform = BABYLON.Vector3.Zero();
  76341. this._vector3 = BABYLON.Vector3.Zero();
  76342. this._vector2 = BABYLON.Vector2.Zero();
  76343. }
  76344. /**
  76345. * Attach the input controls to a specific dom element to get the input from.
  76346. * @param element Defines the element the controls should be listened from
  76347. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76348. */
  76349. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76350. var _this = this;
  76351. var manager = this.camera.getScene().gamepadManager;
  76352. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76353. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76354. // prioritize XBOX gamepads.
  76355. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76356. _this.gamepad = gamepad;
  76357. }
  76358. }
  76359. });
  76360. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76361. if (_this.gamepad === gamepad) {
  76362. _this.gamepad = null;
  76363. }
  76364. });
  76365. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76366. };
  76367. /**
  76368. * Detach the current controls from the specified dom element.
  76369. * @param element Defines the element to stop listening the inputs from
  76370. */
  76371. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  76372. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76373. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76374. this.gamepad = null;
  76375. };
  76376. /**
  76377. * Update the current camera state depending on the inputs that have been used this frame.
  76378. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76379. */
  76380. FreeCameraGamepadInput.prototype.checkInputs = function () {
  76381. if (this.gamepad && this.gamepad.leftStick) {
  76382. var camera = this.camera;
  76383. var LSValues = this.gamepad.leftStick;
  76384. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  76385. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76386. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  76387. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  76388. var RSValues = this.gamepad.rightStick;
  76389. if (RSValues) {
  76390. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  76391. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  76392. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  76393. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  76394. }
  76395. else {
  76396. RSValues = { x: 0, y: 0 };
  76397. }
  76398. if (!camera.rotationQuaternion) {
  76399. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  76400. }
  76401. else {
  76402. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  76403. }
  76404. var speed = camera._computeLocalCameraSpeed() * 50.0;
  76405. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  76406. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  76407. camera.cameraDirection.addInPlace(this._deltaTransform);
  76408. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  76409. camera.cameraRotation.addInPlace(this._vector2);
  76410. }
  76411. };
  76412. /**
  76413. * Gets the class name of the current intput.
  76414. * @returns the class name
  76415. */
  76416. FreeCameraGamepadInput.prototype.getClassName = function () {
  76417. return "FreeCameraGamepadInput";
  76418. };
  76419. /**
  76420. * Get the friendly name associated with the input class.
  76421. * @returns the input friendly name
  76422. */
  76423. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  76424. return "gamepad";
  76425. };
  76426. __decorate([
  76427. BABYLON.serialize()
  76428. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  76429. __decorate([
  76430. BABYLON.serialize()
  76431. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76432. return FreeCameraGamepadInput;
  76433. }());
  76434. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  76435. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  76436. })(BABYLON || (BABYLON = {}));
  76437. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  76438. var BABYLON;
  76439. (function (BABYLON) {
  76440. /**
  76441. * Manage the gamepad inputs to control an arc rotate camera.
  76442. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  76443. */
  76444. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  76445. function ArcRotateCameraGamepadInput() {
  76446. /**
  76447. * Defines the gamepad rotation sensiblity.
  76448. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  76449. */
  76450. this.gamepadRotationSensibility = 80;
  76451. /**
  76452. * Defines the gamepad move sensiblity.
  76453. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  76454. */
  76455. this.gamepadMoveSensibility = 40;
  76456. }
  76457. /**
  76458. * Attach the input controls to a specific dom element to get the input from.
  76459. * @param element Defines the element the controls should be listened from
  76460. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  76461. */
  76462. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  76463. var _this = this;
  76464. var manager = this.camera.getScene().gamepadManager;
  76465. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  76466. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  76467. // prioritize XBOX gamepads.
  76468. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  76469. _this.gamepad = gamepad;
  76470. }
  76471. }
  76472. });
  76473. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  76474. if (_this.gamepad === gamepad) {
  76475. _this.gamepad = null;
  76476. }
  76477. });
  76478. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  76479. };
  76480. /**
  76481. * Detach the current controls from the specified dom element.
  76482. * @param element Defines the element to stop listening the inputs from
  76483. */
  76484. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  76485. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  76486. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  76487. this.gamepad = null;
  76488. };
  76489. /**
  76490. * Update the current camera state depending on the inputs that have been used this frame.
  76491. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  76492. */
  76493. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  76494. if (this.gamepad) {
  76495. var camera = this.camera;
  76496. var RSValues = this.gamepad.rightStick;
  76497. if (RSValues) {
  76498. if (RSValues.x != 0) {
  76499. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  76500. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  76501. camera.inertialAlphaOffset += normalizedRX;
  76502. }
  76503. }
  76504. if (RSValues.y != 0) {
  76505. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  76506. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  76507. camera.inertialBetaOffset += normalizedRY;
  76508. }
  76509. }
  76510. }
  76511. var LSValues = this.gamepad.leftStick;
  76512. if (LSValues && LSValues.y != 0) {
  76513. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  76514. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  76515. this.camera.inertialRadiusOffset -= normalizedLY;
  76516. }
  76517. }
  76518. }
  76519. };
  76520. /**
  76521. * Gets the class name of the current intput.
  76522. * @returns the class name
  76523. */
  76524. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  76525. return "ArcRotateCameraGamepadInput";
  76526. };
  76527. /**
  76528. * Get the friendly name associated with the input class.
  76529. * @returns the input friendly name
  76530. */
  76531. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  76532. return "gamepad";
  76533. };
  76534. __decorate([
  76535. BABYLON.serialize()
  76536. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  76537. __decorate([
  76538. BABYLON.serialize()
  76539. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  76540. return ArcRotateCameraGamepadInput;
  76541. }());
  76542. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  76543. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  76544. })(BABYLON || (BABYLON = {}));
  76545. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  76546. var BABYLON;
  76547. (function (BABYLON) {
  76548. var GamepadManager = /** @class */ (function () {
  76549. function GamepadManager(_scene) {
  76550. var _this = this;
  76551. this._scene = _scene;
  76552. this._babylonGamepads = [];
  76553. this._oneGamepadConnected = false;
  76554. /** @hidden */
  76555. this._isMonitoring = false;
  76556. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  76557. if (!BABYLON.Tools.IsWindowObjectExist()) {
  76558. this._gamepadEventSupported = false;
  76559. }
  76560. else {
  76561. this._gamepadEventSupported = 'GamepadEvent' in window;
  76562. this._gamepadSupport = (navigator.getGamepads ||
  76563. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  76564. }
  76565. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  76566. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  76567. for (var i in _this._babylonGamepads) {
  76568. var gamepad = _this._babylonGamepads[i];
  76569. if (gamepad && gamepad._isConnected) {
  76570. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  76571. }
  76572. }
  76573. });
  76574. this._onGamepadConnectedEvent = function (evt) {
  76575. var gamepad = evt.gamepad;
  76576. if (gamepad.index in _this._babylonGamepads) {
  76577. if (_this._babylonGamepads[gamepad.index].isConnected) {
  76578. return;
  76579. }
  76580. }
  76581. var newGamepad;
  76582. if (_this._babylonGamepads[gamepad.index]) {
  76583. newGamepad = _this._babylonGamepads[gamepad.index];
  76584. newGamepad.browserGamepad = gamepad;
  76585. newGamepad._isConnected = true;
  76586. }
  76587. else {
  76588. newGamepad = _this._addNewGamepad(gamepad);
  76589. }
  76590. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  76591. _this._startMonitoringGamepads();
  76592. };
  76593. this._onGamepadDisconnectedEvent = function (evt) {
  76594. var gamepad = evt.gamepad;
  76595. // Remove the gamepad from the list of gamepads to monitor.
  76596. for (var i in _this._babylonGamepads) {
  76597. if (_this._babylonGamepads[i].index === gamepad.index) {
  76598. var disconnectedGamepad = _this._babylonGamepads[i];
  76599. disconnectedGamepad._isConnected = false;
  76600. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  76601. break;
  76602. }
  76603. }
  76604. };
  76605. if (this._gamepadSupport) {
  76606. //first add already-connected gamepads
  76607. this._updateGamepadObjects();
  76608. if (this._babylonGamepads.length) {
  76609. this._startMonitoringGamepads();
  76610. }
  76611. // Checking if the gamepad connected event is supported (like in Firefox)
  76612. if (this._gamepadEventSupported) {
  76613. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  76614. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  76615. }
  76616. else {
  76617. this._startMonitoringGamepads();
  76618. }
  76619. }
  76620. }
  76621. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  76622. get: function () {
  76623. return this._babylonGamepads;
  76624. },
  76625. enumerable: true,
  76626. configurable: true
  76627. });
  76628. GamepadManager.prototype.getGamepadByType = function (type) {
  76629. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  76630. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  76631. var gamepad = _a[_i];
  76632. if (gamepad && gamepad.type === type) {
  76633. return gamepad;
  76634. }
  76635. }
  76636. return null;
  76637. };
  76638. GamepadManager.prototype.dispose = function () {
  76639. if (this._gamepadEventSupported) {
  76640. if (this._onGamepadConnectedEvent) {
  76641. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  76642. }
  76643. if (this._onGamepadDisconnectedEvent) {
  76644. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  76645. }
  76646. this._onGamepadConnectedEvent = null;
  76647. this._onGamepadDisconnectedEvent = null;
  76648. }
  76649. this._babylonGamepads.forEach(function (gamepad) {
  76650. gamepad.dispose();
  76651. });
  76652. this.onGamepadConnectedObservable.clear();
  76653. this.onGamepadDisconnectedObservable.clear();
  76654. this._oneGamepadConnected = false;
  76655. this._stopMonitoringGamepads();
  76656. this._babylonGamepads = [];
  76657. };
  76658. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  76659. if (!this._oneGamepadConnected) {
  76660. this._oneGamepadConnected = true;
  76661. }
  76662. var newGamepad;
  76663. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  76664. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  76665. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  76666. }
  76667. // if pose is supported, use the (WebVR) pose enabled controller
  76668. else if (gamepad.pose) {
  76669. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  76670. }
  76671. else {
  76672. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  76673. }
  76674. this._babylonGamepads[newGamepad.index] = newGamepad;
  76675. return newGamepad;
  76676. };
  76677. GamepadManager.prototype._startMonitoringGamepads = function () {
  76678. if (!this._isMonitoring) {
  76679. this._isMonitoring = true;
  76680. //back-comp
  76681. if (!this._scene) {
  76682. this._checkGamepadsStatus();
  76683. }
  76684. }
  76685. };
  76686. GamepadManager.prototype._stopMonitoringGamepads = function () {
  76687. this._isMonitoring = false;
  76688. };
  76689. /** @hidden */
  76690. GamepadManager.prototype._checkGamepadsStatus = function () {
  76691. var _this = this;
  76692. // Hack to be compatible Chrome
  76693. this._updateGamepadObjects();
  76694. for (var i in this._babylonGamepads) {
  76695. var gamepad = this._babylonGamepads[i];
  76696. if (!gamepad || !gamepad.isConnected) {
  76697. continue;
  76698. }
  76699. gamepad.update();
  76700. }
  76701. if (this._isMonitoring && !this._scene) {
  76702. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  76703. }
  76704. };
  76705. // This function is called only on Chrome, which does not properly support
  76706. // connection/disconnection events and forces you to recopy again the gamepad object
  76707. GamepadManager.prototype._updateGamepadObjects = function () {
  76708. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  76709. for (var i = 0; i < gamepads.length; i++) {
  76710. var gamepad = gamepads[i];
  76711. if (gamepad) {
  76712. if (!this._babylonGamepads[gamepad.index]) {
  76713. var newGamepad = this._addNewGamepad(gamepad);
  76714. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  76715. }
  76716. else {
  76717. // Forced to copy again this object for Chrome for unknown reason
  76718. this._babylonGamepads[i].browserGamepad = gamepad;
  76719. if (!this._babylonGamepads[i].isConnected) {
  76720. this._babylonGamepads[i]._isConnected = true;
  76721. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  76722. }
  76723. }
  76724. }
  76725. }
  76726. };
  76727. return GamepadManager;
  76728. }());
  76729. BABYLON.GamepadManager = GamepadManager;
  76730. })(BABYLON || (BABYLON = {}));
  76731. //# sourceMappingURL=babylon.gamepadManager.js.map
  76732. var BABYLON;
  76733. (function (BABYLON) {
  76734. var StickValues = /** @class */ (function () {
  76735. function StickValues(x, y) {
  76736. this.x = x;
  76737. this.y = y;
  76738. }
  76739. return StickValues;
  76740. }());
  76741. BABYLON.StickValues = StickValues;
  76742. var Gamepad = /** @class */ (function () {
  76743. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  76744. if (leftStickX === void 0) { leftStickX = 0; }
  76745. if (leftStickY === void 0) { leftStickY = 1; }
  76746. if (rightStickX === void 0) { rightStickX = 2; }
  76747. if (rightStickY === void 0) { rightStickY = 3; }
  76748. this.id = id;
  76749. this.index = index;
  76750. this.browserGamepad = browserGamepad;
  76751. this._leftStick = { x: 0, y: 0 };
  76752. this._rightStick = { x: 0, y: 0 };
  76753. /** @hidden */
  76754. this._isConnected = true;
  76755. this._invertLeftStickY = false;
  76756. this.type = Gamepad.GAMEPAD;
  76757. this._leftStickAxisX = leftStickX;
  76758. this._leftStickAxisY = leftStickY;
  76759. this._rightStickAxisX = rightStickX;
  76760. this._rightStickAxisY = rightStickY;
  76761. if (this.browserGamepad.axes.length >= 2) {
  76762. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  76763. }
  76764. if (this.browserGamepad.axes.length >= 4) {
  76765. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  76766. }
  76767. }
  76768. Object.defineProperty(Gamepad.prototype, "isConnected", {
  76769. get: function () {
  76770. return this._isConnected;
  76771. },
  76772. enumerable: true,
  76773. configurable: true
  76774. });
  76775. Gamepad.prototype.onleftstickchanged = function (callback) {
  76776. this._onleftstickchanged = callback;
  76777. };
  76778. Gamepad.prototype.onrightstickchanged = function (callback) {
  76779. this._onrightstickchanged = callback;
  76780. };
  76781. Object.defineProperty(Gamepad.prototype, "leftStick", {
  76782. get: function () {
  76783. return this._leftStick;
  76784. },
  76785. set: function (newValues) {
  76786. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  76787. this._onleftstickchanged(newValues);
  76788. }
  76789. this._leftStick = newValues;
  76790. },
  76791. enumerable: true,
  76792. configurable: true
  76793. });
  76794. Object.defineProperty(Gamepad.prototype, "rightStick", {
  76795. get: function () {
  76796. return this._rightStick;
  76797. },
  76798. set: function (newValues) {
  76799. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  76800. this._onrightstickchanged(newValues);
  76801. }
  76802. this._rightStick = newValues;
  76803. },
  76804. enumerable: true,
  76805. configurable: true
  76806. });
  76807. Gamepad.prototype.update = function () {
  76808. if (this._leftStick) {
  76809. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  76810. if (this._invertLeftStickY) {
  76811. this.leftStick.y *= -1;
  76812. }
  76813. }
  76814. if (this._rightStick) {
  76815. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  76816. }
  76817. };
  76818. Gamepad.prototype.dispose = function () {
  76819. };
  76820. Gamepad.GAMEPAD = 0;
  76821. Gamepad.GENERIC = 1;
  76822. Gamepad.XBOX = 2;
  76823. Gamepad.POSE_ENABLED = 3;
  76824. return Gamepad;
  76825. }());
  76826. BABYLON.Gamepad = Gamepad;
  76827. var GenericPad = /** @class */ (function (_super) {
  76828. __extends(GenericPad, _super);
  76829. function GenericPad(id, index, browserGamepad) {
  76830. var _this = _super.call(this, id, index, browserGamepad) || this;
  76831. _this.onButtonDownObservable = new BABYLON.Observable();
  76832. _this.onButtonUpObservable = new BABYLON.Observable();
  76833. _this.type = Gamepad.GENERIC;
  76834. _this._buttons = new Array(browserGamepad.buttons.length);
  76835. return _this;
  76836. }
  76837. GenericPad.prototype.onbuttondown = function (callback) {
  76838. this._onbuttondown = callback;
  76839. };
  76840. GenericPad.prototype.onbuttonup = function (callback) {
  76841. this._onbuttonup = callback;
  76842. };
  76843. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  76844. if (newValue !== currentValue) {
  76845. if (newValue === 1) {
  76846. if (this._onbuttondown) {
  76847. this._onbuttondown(buttonIndex);
  76848. }
  76849. this.onButtonDownObservable.notifyObservers(buttonIndex);
  76850. }
  76851. if (newValue === 0) {
  76852. if (this._onbuttonup) {
  76853. this._onbuttonup(buttonIndex);
  76854. }
  76855. this.onButtonUpObservable.notifyObservers(buttonIndex);
  76856. }
  76857. }
  76858. return newValue;
  76859. };
  76860. GenericPad.prototype.update = function () {
  76861. _super.prototype.update.call(this);
  76862. for (var index = 0; index < this._buttons.length; index++) {
  76863. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  76864. }
  76865. };
  76866. GenericPad.prototype.dispose = function () {
  76867. _super.prototype.dispose.call(this);
  76868. this.onButtonDownObservable.clear();
  76869. this.onButtonUpObservable.clear();
  76870. };
  76871. return GenericPad;
  76872. }(Gamepad));
  76873. BABYLON.GenericPad = GenericPad;
  76874. })(BABYLON || (BABYLON = {}));
  76875. //# sourceMappingURL=babylon.gamepad.js.map
  76876. var BABYLON;
  76877. (function (BABYLON) {
  76878. /**
  76879. * Defines supported buttons for XBox360 compatible gamepads
  76880. */
  76881. var Xbox360Button;
  76882. (function (Xbox360Button) {
  76883. /** A */
  76884. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  76885. /** B */
  76886. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  76887. /** X */
  76888. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  76889. /** Y */
  76890. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  76891. /** Start */
  76892. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  76893. /** Back */
  76894. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  76895. /** Left button */
  76896. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  76897. /** Right button */
  76898. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  76899. /** Left stick */
  76900. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  76901. /** Right stick */
  76902. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  76903. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  76904. /** Defines values for XBox360 DPad */
  76905. var Xbox360Dpad;
  76906. (function (Xbox360Dpad) {
  76907. /** Up */
  76908. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  76909. /** Down */
  76910. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  76911. /** Left */
  76912. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  76913. /** Right */
  76914. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  76915. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  76916. /**
  76917. * Defines a XBox360 gamepad
  76918. */
  76919. var Xbox360Pad = /** @class */ (function (_super) {
  76920. __extends(Xbox360Pad, _super);
  76921. /**
  76922. * Creates a new XBox360 gamepad object
  76923. * @param id defines the id of this gamepad
  76924. * @param index defines its index
  76925. * @param gamepad defines the internal HTML gamepad object
  76926. * @param xboxOne defines if it is a XBox One gamepad
  76927. */
  76928. function Xbox360Pad(id, index, gamepad, xboxOne) {
  76929. if (xboxOne === void 0) { xboxOne = false; }
  76930. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  76931. _this._leftTrigger = 0;
  76932. _this._rightTrigger = 0;
  76933. /** Observable raised when a button is pressed */
  76934. _this.onButtonDownObservable = new BABYLON.Observable();
  76935. /** Observable raised when a button is released */
  76936. _this.onButtonUpObservable = new BABYLON.Observable();
  76937. /** Observable raised when a pad is pressed */
  76938. _this.onPadDownObservable = new BABYLON.Observable();
  76939. /** Observable raised when a pad is released */
  76940. _this.onPadUpObservable = new BABYLON.Observable();
  76941. _this._buttonA = 0;
  76942. _this._buttonB = 0;
  76943. _this._buttonX = 0;
  76944. _this._buttonY = 0;
  76945. _this._buttonBack = 0;
  76946. _this._buttonStart = 0;
  76947. _this._buttonLB = 0;
  76948. _this._buttonRB = 0;
  76949. _this._buttonLeftStick = 0;
  76950. _this._buttonRightStick = 0;
  76951. _this._dPadUp = 0;
  76952. _this._dPadDown = 0;
  76953. _this._dPadLeft = 0;
  76954. _this._dPadRight = 0;
  76955. _this._isXboxOnePad = false;
  76956. _this.type = BABYLON.Gamepad.XBOX;
  76957. _this._isXboxOnePad = xboxOne;
  76958. return _this;
  76959. }
  76960. /**
  76961. * Defines the callback to call when left trigger is pressed
  76962. * @param callback defines the callback to use
  76963. */
  76964. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  76965. this._onlefttriggerchanged = callback;
  76966. };
  76967. /**
  76968. * Defines the callback to call when right trigger is pressed
  76969. * @param callback defines the callback to use
  76970. */
  76971. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  76972. this._onrighttriggerchanged = callback;
  76973. };
  76974. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  76975. /**
  76976. * Gets or sets left trigger value
  76977. */
  76978. get: function () {
  76979. return this._leftTrigger;
  76980. },
  76981. set: function (newValue) {
  76982. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  76983. this._onlefttriggerchanged(newValue);
  76984. }
  76985. this._leftTrigger = newValue;
  76986. },
  76987. enumerable: true,
  76988. configurable: true
  76989. });
  76990. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  76991. /**
  76992. * Gets or sets right trigger value
  76993. */
  76994. get: function () {
  76995. return this._rightTrigger;
  76996. },
  76997. set: function (newValue) {
  76998. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  76999. this._onrighttriggerchanged(newValue);
  77000. }
  77001. this._rightTrigger = newValue;
  77002. },
  77003. enumerable: true,
  77004. configurable: true
  77005. });
  77006. /**
  77007. * Defines the callback to call when a button is pressed
  77008. * @param callback defines the callback to use
  77009. */
  77010. Xbox360Pad.prototype.onbuttondown = function (callback) {
  77011. this._onbuttondown = callback;
  77012. };
  77013. /**
  77014. * Defines the callback to call when a button is released
  77015. * @param callback defines the callback to use
  77016. */
  77017. Xbox360Pad.prototype.onbuttonup = function (callback) {
  77018. this._onbuttonup = callback;
  77019. };
  77020. /**
  77021. * Defines the callback to call when a pad is pressed
  77022. * @param callback defines the callback to use
  77023. */
  77024. Xbox360Pad.prototype.ondpaddown = function (callback) {
  77025. this._ondpaddown = callback;
  77026. };
  77027. /**
  77028. * Defines the callback to call when a pad is released
  77029. * @param callback defines the callback to use
  77030. */
  77031. Xbox360Pad.prototype.ondpadup = function (callback) {
  77032. this._ondpadup = callback;
  77033. };
  77034. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  77035. if (newValue !== currentValue) {
  77036. if (newValue === 1) {
  77037. if (this._onbuttondown) {
  77038. this._onbuttondown(buttonType);
  77039. }
  77040. this.onButtonDownObservable.notifyObservers(buttonType);
  77041. }
  77042. if (newValue === 0) {
  77043. if (this._onbuttonup) {
  77044. this._onbuttonup(buttonType);
  77045. }
  77046. this.onButtonUpObservable.notifyObservers(buttonType);
  77047. }
  77048. }
  77049. return newValue;
  77050. };
  77051. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  77052. if (newValue !== currentValue) {
  77053. if (newValue === 1) {
  77054. if (this._ondpaddown) {
  77055. this._ondpaddown(buttonType);
  77056. }
  77057. this.onPadDownObservable.notifyObservers(buttonType);
  77058. }
  77059. if (newValue === 0) {
  77060. if (this._ondpadup) {
  77061. this._ondpadup(buttonType);
  77062. }
  77063. this.onPadUpObservable.notifyObservers(buttonType);
  77064. }
  77065. }
  77066. return newValue;
  77067. };
  77068. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  77069. /** Gets or sets value of A button */
  77070. get: function () {
  77071. return this._buttonA;
  77072. },
  77073. set: function (value) {
  77074. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  77075. },
  77076. enumerable: true,
  77077. configurable: true
  77078. });
  77079. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  77080. /** Gets or sets value of B button */
  77081. get: function () {
  77082. return this._buttonB;
  77083. },
  77084. set: function (value) {
  77085. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  77086. },
  77087. enumerable: true,
  77088. configurable: true
  77089. });
  77090. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  77091. /** Gets or sets value of X button */
  77092. get: function () {
  77093. return this._buttonX;
  77094. },
  77095. set: function (value) {
  77096. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  77097. },
  77098. enumerable: true,
  77099. configurable: true
  77100. });
  77101. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  77102. /** Gets or sets value of Y button */
  77103. get: function () {
  77104. return this._buttonY;
  77105. },
  77106. set: function (value) {
  77107. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  77108. },
  77109. enumerable: true,
  77110. configurable: true
  77111. });
  77112. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  77113. /** Gets or sets value of Start button */
  77114. get: function () {
  77115. return this._buttonStart;
  77116. },
  77117. set: function (value) {
  77118. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  77119. },
  77120. enumerable: true,
  77121. configurable: true
  77122. });
  77123. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  77124. /** Gets or sets value of Back button */
  77125. get: function () {
  77126. return this._buttonBack;
  77127. },
  77128. set: function (value) {
  77129. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  77130. },
  77131. enumerable: true,
  77132. configurable: true
  77133. });
  77134. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  77135. /** Gets or sets value of Left button */
  77136. get: function () {
  77137. return this._buttonLB;
  77138. },
  77139. set: function (value) {
  77140. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  77141. },
  77142. enumerable: true,
  77143. configurable: true
  77144. });
  77145. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  77146. /** Gets or sets value of Right button */
  77147. get: function () {
  77148. return this._buttonRB;
  77149. },
  77150. set: function (value) {
  77151. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  77152. },
  77153. enumerable: true,
  77154. configurable: true
  77155. });
  77156. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  77157. /** Gets or sets value of left stick */
  77158. get: function () {
  77159. return this._buttonLeftStick;
  77160. },
  77161. set: function (value) {
  77162. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  77163. },
  77164. enumerable: true,
  77165. configurable: true
  77166. });
  77167. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  77168. /** Gets or sets value of right stick */
  77169. get: function () {
  77170. return this._buttonRightStick;
  77171. },
  77172. set: function (value) {
  77173. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  77174. },
  77175. enumerable: true,
  77176. configurable: true
  77177. });
  77178. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  77179. /** Gets or sets value of DPad up */
  77180. get: function () {
  77181. return this._dPadUp;
  77182. },
  77183. set: function (value) {
  77184. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  77185. },
  77186. enumerable: true,
  77187. configurable: true
  77188. });
  77189. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  77190. /** Gets or sets value of DPad down */
  77191. get: function () {
  77192. return this._dPadDown;
  77193. },
  77194. set: function (value) {
  77195. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  77196. },
  77197. enumerable: true,
  77198. configurable: true
  77199. });
  77200. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  77201. /** Gets or sets value of DPad left */
  77202. get: function () {
  77203. return this._dPadLeft;
  77204. },
  77205. set: function (value) {
  77206. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  77207. },
  77208. enumerable: true,
  77209. configurable: true
  77210. });
  77211. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  77212. /** Gets or sets value of DPad right */
  77213. get: function () {
  77214. return this._dPadRight;
  77215. },
  77216. set: function (value) {
  77217. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  77218. },
  77219. enumerable: true,
  77220. configurable: true
  77221. });
  77222. /**
  77223. * Force the gamepad to synchronize with device values
  77224. */
  77225. Xbox360Pad.prototype.update = function () {
  77226. _super.prototype.update.call(this);
  77227. if (this._isXboxOnePad) {
  77228. this.buttonA = this.browserGamepad.buttons[0].value;
  77229. this.buttonB = this.browserGamepad.buttons[1].value;
  77230. this.buttonX = this.browserGamepad.buttons[2].value;
  77231. this.buttonY = this.browserGamepad.buttons[3].value;
  77232. this.buttonLB = this.browserGamepad.buttons[4].value;
  77233. this.buttonRB = this.browserGamepad.buttons[5].value;
  77234. this.leftTrigger = this.browserGamepad.axes[2];
  77235. this.rightTrigger = this.browserGamepad.axes[5];
  77236. this.buttonBack = this.browserGamepad.buttons[9].value;
  77237. this.buttonStart = this.browserGamepad.buttons[8].value;
  77238. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  77239. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  77240. this.dPadUp = this.browserGamepad.buttons[11].value;
  77241. this.dPadDown = this.browserGamepad.buttons[12].value;
  77242. this.dPadLeft = this.browserGamepad.buttons[13].value;
  77243. this.dPadRight = this.browserGamepad.buttons[14].value;
  77244. }
  77245. else {
  77246. this.buttonA = this.browserGamepad.buttons[0].value;
  77247. this.buttonB = this.browserGamepad.buttons[1].value;
  77248. this.buttonX = this.browserGamepad.buttons[2].value;
  77249. this.buttonY = this.browserGamepad.buttons[3].value;
  77250. this.buttonLB = this.browserGamepad.buttons[4].value;
  77251. this.buttonRB = this.browserGamepad.buttons[5].value;
  77252. this.leftTrigger = this.browserGamepad.buttons[6].value;
  77253. this.rightTrigger = this.browserGamepad.buttons[7].value;
  77254. this.buttonBack = this.browserGamepad.buttons[8].value;
  77255. this.buttonStart = this.browserGamepad.buttons[9].value;
  77256. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  77257. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  77258. this.dPadUp = this.browserGamepad.buttons[12].value;
  77259. this.dPadDown = this.browserGamepad.buttons[13].value;
  77260. this.dPadLeft = this.browserGamepad.buttons[14].value;
  77261. this.dPadRight = this.browserGamepad.buttons[15].value;
  77262. }
  77263. };
  77264. Xbox360Pad.prototype.dispose = function () {
  77265. _super.prototype.dispose.call(this);
  77266. this.onButtonDownObservable.clear();
  77267. this.onButtonUpObservable.clear();
  77268. this.onPadDownObservable.clear();
  77269. this.onPadUpObservable.clear();
  77270. };
  77271. return Xbox360Pad;
  77272. }(BABYLON.Gamepad));
  77273. BABYLON.Xbox360Pad = Xbox360Pad;
  77274. })(BABYLON || (BABYLON = {}));
  77275. //# sourceMappingURL=babylon.xboxGamepad.js.map
  77276. var BABYLON;
  77277. (function (BABYLON) {
  77278. /**
  77279. * Defines the types of pose enabled controllers that are supported
  77280. */
  77281. var PoseEnabledControllerType;
  77282. (function (PoseEnabledControllerType) {
  77283. /**
  77284. * HTC Vive
  77285. */
  77286. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  77287. /**
  77288. * Oculus Rift
  77289. */
  77290. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  77291. /**
  77292. * Windows mixed reality
  77293. */
  77294. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  77295. /**
  77296. * Samsung gear VR
  77297. */
  77298. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  77299. /**
  77300. * Google Daydream
  77301. */
  77302. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  77303. /**
  77304. * Generic
  77305. */
  77306. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  77307. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  77308. /**
  77309. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77310. */
  77311. var PoseEnabledControllerHelper = /** @class */ (function () {
  77312. function PoseEnabledControllerHelper() {
  77313. }
  77314. /**
  77315. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  77316. * @param vrGamepad the gamepad to initialized
  77317. * @returns a vr controller of the type the gamepad identified as
  77318. */
  77319. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  77320. // Oculus Touch
  77321. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  77322. return new BABYLON.OculusTouchController(vrGamepad);
  77323. }
  77324. // Windows Mixed Reality controllers
  77325. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  77326. return new BABYLON.WindowsMotionController(vrGamepad);
  77327. }
  77328. // HTC Vive
  77329. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  77330. return new BABYLON.ViveController(vrGamepad);
  77331. }
  77332. // Samsung/Oculus Gear VR or Oculus Go
  77333. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  77334. return new BABYLON.GearVRController(vrGamepad);
  77335. }
  77336. // Google Daydream
  77337. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  77338. return new BABYLON.DaydreamController(vrGamepad);
  77339. }
  77340. // Generic
  77341. else {
  77342. return new BABYLON.GenericController(vrGamepad);
  77343. }
  77344. };
  77345. return PoseEnabledControllerHelper;
  77346. }());
  77347. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  77348. /**
  77349. * Defines the PoseEnabledController object that contains state of a vr capable controller
  77350. */
  77351. var PoseEnabledController = /** @class */ (function (_super) {
  77352. __extends(PoseEnabledController, _super);
  77353. /**
  77354. * Creates a new PoseEnabledController from a gamepad
  77355. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  77356. */
  77357. function PoseEnabledController(browserGamepad) {
  77358. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  77359. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  77360. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  77361. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  77362. /**
  77363. * The device position in babylon space
  77364. */
  77365. _this.devicePosition = BABYLON.Vector3.Zero();
  77366. /**
  77367. * The device rotation in babylon space
  77368. */
  77369. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  77370. /**
  77371. * The scale factor of the device in babylon space
  77372. */
  77373. _this.deviceScaleFactor = 1;
  77374. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  77375. /**
  77376. * Internal, matrix used to convert room space to babylon space
  77377. * @hidden
  77378. */
  77379. _this._deviceToWorld = BABYLON.Matrix.Identity();
  77380. /**
  77381. * Node to be used when casting a ray from the controller
  77382. * @hidden
  77383. */
  77384. _this._pointingPoseNode = null;
  77385. _this._workingMatrix = BABYLON.Matrix.Identity();
  77386. /**
  77387. * @hidden
  77388. */
  77389. _this._meshAttachedObservable = new BABYLON.Observable();
  77390. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  77391. _this.controllerType = PoseEnabledControllerType.GENERIC;
  77392. _this.position = BABYLON.Vector3.Zero();
  77393. _this.rotationQuaternion = new BABYLON.Quaternion();
  77394. _this._calculatedPosition = BABYLON.Vector3.Zero();
  77395. _this._calculatedRotation = new BABYLON.Quaternion();
  77396. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  77397. return _this;
  77398. }
  77399. /**
  77400. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  77401. */
  77402. PoseEnabledController.prototype.update = function () {
  77403. _super.prototype.update.call(this);
  77404. this._updatePoseAndMesh();
  77405. };
  77406. /**
  77407. * Updates only the pose device and mesh without doing any button event checking
  77408. */
  77409. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  77410. var pose = this.browserGamepad.pose;
  77411. this.updateFromDevice(pose);
  77412. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  77413. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  77414. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  77415. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  77416. if (this._mesh) {
  77417. this._mesh.position.copyFrom(this.devicePosition);
  77418. if (this._mesh.rotationQuaternion) {
  77419. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  77420. }
  77421. }
  77422. };
  77423. /**
  77424. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  77425. * @param poseData raw pose fromthe device
  77426. */
  77427. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  77428. if (poseData) {
  77429. this.rawPose = poseData;
  77430. if (poseData.position) {
  77431. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  77432. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  77433. this._deviceRoomPosition.z *= -1;
  77434. }
  77435. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  77436. this._calculatedPosition.addInPlace(this.position);
  77437. }
  77438. var pose = this.rawPose;
  77439. if (poseData.orientation && pose.orientation) {
  77440. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  77441. if (this._mesh) {
  77442. if (this._mesh.getScene().useRightHandedSystem) {
  77443. this._deviceRoomRotationQuaternion.z *= -1;
  77444. this._deviceRoomRotationQuaternion.w *= -1;
  77445. }
  77446. else {
  77447. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  77448. }
  77449. }
  77450. // if the camera is set, rotate to the camera's rotation
  77451. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  77452. }
  77453. }
  77454. };
  77455. /**
  77456. * Attaches a mesh to the controller
  77457. * @param mesh the mesh to be attached
  77458. */
  77459. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  77460. if (this._mesh) {
  77461. this._mesh.parent = null;
  77462. }
  77463. this._mesh = mesh;
  77464. if (this._poseControlledCamera) {
  77465. this._mesh.parent = this._poseControlledCamera;
  77466. }
  77467. if (!this._mesh.rotationQuaternion) {
  77468. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  77469. }
  77470. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  77471. this._updatePoseAndMesh();
  77472. if (this._pointingPoseNode) {
  77473. var parents = [];
  77474. var obj = this._pointingPoseNode;
  77475. while (obj.parent) {
  77476. parents.push(obj.parent);
  77477. obj = obj.parent;
  77478. }
  77479. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  77480. }
  77481. this._meshAttachedObservable.notifyObservers(mesh);
  77482. };
  77483. /**
  77484. * Attaches the controllers mesh to a camera
  77485. * @param camera the camera the mesh should be attached to
  77486. */
  77487. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  77488. this._poseControlledCamera = camera;
  77489. if (this._mesh) {
  77490. this._mesh.parent = this._poseControlledCamera;
  77491. }
  77492. };
  77493. /**
  77494. * Disposes of the controller
  77495. */
  77496. PoseEnabledController.prototype.dispose = function () {
  77497. if (this._mesh) {
  77498. this._mesh.dispose();
  77499. }
  77500. this._mesh = null;
  77501. _super.prototype.dispose.call(this);
  77502. };
  77503. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  77504. /**
  77505. * The mesh that is attached to the controller
  77506. */
  77507. get: function () {
  77508. return this._mesh;
  77509. },
  77510. enumerable: true,
  77511. configurable: true
  77512. });
  77513. /**
  77514. * Gets the ray of the controller in the direction the controller is pointing
  77515. * @param length the length the resulting ray should be
  77516. * @returns a ray in the direction the controller is pointing
  77517. */
  77518. PoseEnabledController.prototype.getForwardRay = function (length) {
  77519. if (length === void 0) { length = 100; }
  77520. if (!this.mesh) {
  77521. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  77522. }
  77523. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  77524. var origin = m.getTranslation();
  77525. var forward = new BABYLON.Vector3(0, 0, -1);
  77526. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  77527. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  77528. return new BABYLON.Ray(origin, direction, length);
  77529. };
  77530. /**
  77531. * Name of the child mesh that can be used to cast a ray from the controller
  77532. */
  77533. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  77534. return PoseEnabledController;
  77535. }(BABYLON.Gamepad));
  77536. BABYLON.PoseEnabledController = PoseEnabledController;
  77537. })(BABYLON || (BABYLON = {}));
  77538. //# sourceMappingURL=babylon.poseEnabledController.js.map
  77539. var BABYLON;
  77540. (function (BABYLON) {
  77541. /**
  77542. * Defines the WebVRController object that represents controllers tracked in 3D space
  77543. */
  77544. var WebVRController = /** @class */ (function (_super) {
  77545. __extends(WebVRController, _super);
  77546. /**
  77547. * Creates a new WebVRController from a gamepad
  77548. * @param vrGamepad the gamepad that the WebVRController should be created from
  77549. */
  77550. function WebVRController(vrGamepad) {
  77551. var _this = _super.call(this, vrGamepad) || this;
  77552. // Observables
  77553. /**
  77554. * Fired when the trigger state has changed
  77555. */
  77556. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  77557. /**
  77558. * Fired when the main button state has changed
  77559. */
  77560. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  77561. /**
  77562. * Fired when the secondary button state has changed
  77563. */
  77564. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  77565. /**
  77566. * Fired when the pad state has changed
  77567. */
  77568. _this.onPadStateChangedObservable = new BABYLON.Observable();
  77569. /**
  77570. * Fired when controllers stick values have changed
  77571. */
  77572. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  77573. /**
  77574. * X and Y axis corrisponding to the controllers joystick
  77575. */
  77576. _this.pad = { x: 0, y: 0 };
  77577. // avoid GC, store state in a tmp object
  77578. _this._changes = {
  77579. pressChanged: false,
  77580. touchChanged: false,
  77581. valueChanged: false,
  77582. changed: false
  77583. };
  77584. _this._buttons = new Array(vrGamepad.buttons.length);
  77585. _this.hand = vrGamepad.hand;
  77586. return _this;
  77587. }
  77588. /**
  77589. * Fired when a controller button's state has changed
  77590. * @param callback the callback containing the button that was modified
  77591. */
  77592. WebVRController.prototype.onButtonStateChange = function (callback) {
  77593. this._onButtonStateChange = callback;
  77594. };
  77595. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  77596. /**
  77597. * The default controller model for the controller
  77598. */
  77599. get: function () {
  77600. return this._defaultModel;
  77601. },
  77602. enumerable: true,
  77603. configurable: true
  77604. });
  77605. /**
  77606. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  77607. */
  77608. WebVRController.prototype.update = function () {
  77609. _super.prototype.update.call(this);
  77610. for (var index = 0; index < this._buttons.length; index++) {
  77611. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  77612. }
  77613. ;
  77614. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  77615. this.pad.x = this.leftStick.x;
  77616. this.pad.y = this.leftStick.y;
  77617. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  77618. }
  77619. };
  77620. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  77621. if (!newState) {
  77622. newState = {
  77623. pressed: false,
  77624. touched: false,
  77625. value: 0
  77626. };
  77627. }
  77628. if (!currentState) {
  77629. this._buttons[buttonIndex] = {
  77630. pressed: newState.pressed,
  77631. touched: newState.touched,
  77632. value: newState.value
  77633. };
  77634. return;
  77635. }
  77636. this._checkChanges(newState, currentState);
  77637. if (this._changes.changed) {
  77638. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  77639. this._handleButtonChange(buttonIndex, newState, this._changes);
  77640. }
  77641. this._buttons[buttonIndex].pressed = newState.pressed;
  77642. this._buttons[buttonIndex].touched = newState.touched;
  77643. // oculus triggers are never 0, thou not touched.
  77644. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  77645. };
  77646. WebVRController.prototype._checkChanges = function (newState, currentState) {
  77647. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  77648. this._changes.touchChanged = newState.touched !== currentState.touched;
  77649. this._changes.valueChanged = newState.value !== currentState.value;
  77650. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  77651. return this._changes;
  77652. };
  77653. /**
  77654. * Disposes of th webVRCOntroller
  77655. */
  77656. WebVRController.prototype.dispose = function () {
  77657. _super.prototype.dispose.call(this);
  77658. this.onTriggerStateChangedObservable.clear();
  77659. this.onMainButtonStateChangedObservable.clear();
  77660. this.onSecondaryButtonStateChangedObservable.clear();
  77661. this.onPadStateChangedObservable.clear();
  77662. this.onPadValuesChangedObservable.clear();
  77663. };
  77664. return WebVRController;
  77665. }(BABYLON.PoseEnabledController));
  77666. BABYLON.WebVRController = WebVRController;
  77667. })(BABYLON || (BABYLON = {}));
  77668. //# sourceMappingURL=babylon.webVRController.js.map
  77669. var BABYLON;
  77670. (function (BABYLON) {
  77671. /**
  77672. * Oculus Touch Controller
  77673. */
  77674. var OculusTouchController = /** @class */ (function (_super) {
  77675. __extends(OculusTouchController, _super);
  77676. /**
  77677. * Creates a new OculusTouchController from a gamepad
  77678. * @param vrGamepad the gamepad that the controller should be created from
  77679. */
  77680. function OculusTouchController(vrGamepad) {
  77681. var _this = _super.call(this, vrGamepad) || this;
  77682. /**
  77683. * Fired when the secondary trigger on this controller is modified
  77684. */
  77685. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  77686. /**
  77687. * Fired when the thumb rest on this controller is modified
  77688. */
  77689. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  77690. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  77691. return _this;
  77692. }
  77693. /**
  77694. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77695. * @param scene scene in which to add meshes
  77696. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77697. */
  77698. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77699. var _this = this;
  77700. var meshName;
  77701. // Hand
  77702. if (this.hand === 'left') {
  77703. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  77704. }
  77705. else { // Right is the default if no hand is specified
  77706. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  77707. }
  77708. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  77709. /*
  77710. Parent Mesh name: oculus_touch_left
  77711. - body
  77712. - trigger
  77713. - thumbstick
  77714. - grip
  77715. - button_y
  77716. - button_x
  77717. - button_enter
  77718. */
  77719. _this._defaultModel = newMeshes[1];
  77720. _this.attachToMesh(_this._defaultModel);
  77721. if (meshLoaded) {
  77722. meshLoaded(_this._defaultModel);
  77723. }
  77724. });
  77725. };
  77726. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  77727. /**
  77728. * Fired when the A button on this controller is modified
  77729. */
  77730. get: function () {
  77731. if (this.hand === 'right') {
  77732. return this.onMainButtonStateChangedObservable;
  77733. }
  77734. else {
  77735. throw new Error('No A button on left hand');
  77736. }
  77737. },
  77738. enumerable: true,
  77739. configurable: true
  77740. });
  77741. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  77742. /**
  77743. * Fired when the B button on this controller is modified
  77744. */
  77745. get: function () {
  77746. if (this.hand === 'right') {
  77747. return this.onSecondaryButtonStateChangedObservable;
  77748. }
  77749. else {
  77750. throw new Error('No B button on left hand');
  77751. }
  77752. },
  77753. enumerable: true,
  77754. configurable: true
  77755. });
  77756. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  77757. /**
  77758. * Fired when the X button on this controller is modified
  77759. */
  77760. get: function () {
  77761. if (this.hand === 'left') {
  77762. return this.onMainButtonStateChangedObservable;
  77763. }
  77764. else {
  77765. throw new Error('No X button on right hand');
  77766. }
  77767. },
  77768. enumerable: true,
  77769. configurable: true
  77770. });
  77771. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  77772. /**
  77773. * Fired when the Y button on this controller is modified
  77774. */
  77775. get: function () {
  77776. if (this.hand === 'left') {
  77777. return this.onSecondaryButtonStateChangedObservable;
  77778. }
  77779. else {
  77780. throw new Error('No Y button on right hand');
  77781. }
  77782. },
  77783. enumerable: true,
  77784. configurable: true
  77785. });
  77786. /**
  77787. * Called once for each button that changed state since the last frame
  77788. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  77789. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  77790. * 2) secondary trigger (same)
  77791. * 3) A (right) X (left), touch, pressed = value
  77792. * 4) B / Y
  77793. * 5) thumb rest
  77794. * @param buttonIdx Which button index changed
  77795. * @param state New state of the button
  77796. * @param changes Which properties on the state changed since last frame
  77797. */
  77798. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77799. var notifyObject = state; //{ state: state, changes: changes };
  77800. var triggerDirection = this.hand === 'right' ? -1 : 1;
  77801. switch (buttonIdx) {
  77802. case 0:
  77803. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  77804. return;
  77805. case 1: // index trigger
  77806. if (this._defaultModel) {
  77807. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  77808. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  77809. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  77810. }
  77811. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  77812. return;
  77813. case 2: // secondary trigger
  77814. if (this._defaultModel) {
  77815. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  77816. }
  77817. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  77818. return;
  77819. case 3:
  77820. if (this._defaultModel) {
  77821. if (notifyObject.pressed) {
  77822. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  77823. }
  77824. else {
  77825. (this._defaultModel.getChildren()[1]).position.y = 0;
  77826. }
  77827. }
  77828. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  77829. return;
  77830. case 4:
  77831. if (this._defaultModel) {
  77832. if (notifyObject.pressed) {
  77833. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  77834. }
  77835. else {
  77836. (this._defaultModel.getChildren()[2]).position.y = 0;
  77837. }
  77838. }
  77839. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  77840. return;
  77841. case 5:
  77842. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  77843. return;
  77844. }
  77845. };
  77846. /**
  77847. * Base Url for the controller model.
  77848. */
  77849. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  77850. /**
  77851. * File name for the left controller model.
  77852. */
  77853. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  77854. /**
  77855. * File name for the right controller model.
  77856. */
  77857. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  77858. return OculusTouchController;
  77859. }(BABYLON.WebVRController));
  77860. BABYLON.OculusTouchController = OculusTouchController;
  77861. })(BABYLON || (BABYLON = {}));
  77862. //# sourceMappingURL=babylon.oculusTouchController.js.map
  77863. var BABYLON;
  77864. (function (BABYLON) {
  77865. /**
  77866. * Vive Controller
  77867. */
  77868. var ViveController = /** @class */ (function (_super) {
  77869. __extends(ViveController, _super);
  77870. /**
  77871. * Creates a new ViveController from a gamepad
  77872. * @param vrGamepad the gamepad that the controller should be created from
  77873. */
  77874. function ViveController(vrGamepad) {
  77875. var _this = _super.call(this, vrGamepad) || this;
  77876. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  77877. _this._invertLeftStickY = true;
  77878. return _this;
  77879. }
  77880. /**
  77881. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  77882. * @param scene scene in which to add meshes
  77883. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  77884. */
  77885. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  77886. var _this = this;
  77887. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  77888. /*
  77889. Parent Mesh name: ViveWand
  77890. - body
  77891. - r_gripper
  77892. - l_gripper
  77893. - menu_button
  77894. - system_button
  77895. - trackpad
  77896. - trigger
  77897. - LED
  77898. */
  77899. _this._defaultModel = newMeshes[1];
  77900. _this.attachToMesh(_this._defaultModel);
  77901. if (meshLoaded) {
  77902. meshLoaded(_this._defaultModel);
  77903. }
  77904. });
  77905. };
  77906. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  77907. /**
  77908. * Fired when the left button on this controller is modified
  77909. */
  77910. get: function () {
  77911. return this.onMainButtonStateChangedObservable;
  77912. },
  77913. enumerable: true,
  77914. configurable: true
  77915. });
  77916. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  77917. /**
  77918. * Fired when the right button on this controller is modified
  77919. */
  77920. get: function () {
  77921. return this.onMainButtonStateChangedObservable;
  77922. },
  77923. enumerable: true,
  77924. configurable: true
  77925. });
  77926. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  77927. /**
  77928. * Fired when the menu button on this controller is modified
  77929. */
  77930. get: function () {
  77931. return this.onSecondaryButtonStateChangedObservable;
  77932. },
  77933. enumerable: true,
  77934. configurable: true
  77935. });
  77936. /**
  77937. * Called once for each button that changed state since the last frame
  77938. * Vive mapping:
  77939. * 0: touchpad
  77940. * 1: trigger
  77941. * 2: left AND right buttons
  77942. * 3: menu button
  77943. * @param buttonIdx Which button index changed
  77944. * @param state New state of the button
  77945. * @param changes Which properties on the state changed since last frame
  77946. */
  77947. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  77948. var notifyObject = state; //{ state: state, changes: changes };
  77949. switch (buttonIdx) {
  77950. case 0:
  77951. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  77952. return;
  77953. case 1: // index trigger
  77954. if (this._defaultModel) {
  77955. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  77956. }
  77957. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  77958. return;
  77959. case 2: // left AND right button
  77960. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  77961. return;
  77962. case 3:
  77963. if (this._defaultModel) {
  77964. if (notifyObject.pressed) {
  77965. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  77966. }
  77967. else {
  77968. (this._defaultModel.getChildren()[2]).position.y = 0;
  77969. }
  77970. }
  77971. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  77972. return;
  77973. }
  77974. };
  77975. /**
  77976. * Base Url for the controller model.
  77977. */
  77978. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  77979. /**
  77980. * File name for the controller model.
  77981. */
  77982. ViveController.MODEL_FILENAME = 'wand.babylon';
  77983. return ViveController;
  77984. }(BABYLON.WebVRController));
  77985. BABYLON.ViveController = ViveController;
  77986. })(BABYLON || (BABYLON = {}));
  77987. //# sourceMappingURL=babylon.viveController.js.map
  77988. var BABYLON;
  77989. (function (BABYLON) {
  77990. /**
  77991. * Generic Controller
  77992. */
  77993. var GenericController = /** @class */ (function (_super) {
  77994. __extends(GenericController, _super);
  77995. /**
  77996. * Creates a new GenericController from a gamepad
  77997. * @param vrGamepad the gamepad that the controller should be created from
  77998. */
  77999. function GenericController(vrGamepad) {
  78000. return _super.call(this, vrGamepad) || this;
  78001. }
  78002. /**
  78003. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78004. * @param scene scene in which to add meshes
  78005. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78006. */
  78007. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78008. var _this = this;
  78009. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  78010. _this._defaultModel = newMeshes[1];
  78011. _this.attachToMesh(_this._defaultModel);
  78012. if (meshLoaded) {
  78013. meshLoaded(_this._defaultModel);
  78014. }
  78015. });
  78016. };
  78017. /**
  78018. * Called once for each button that changed state since the last frame
  78019. * @param buttonIdx Which button index changed
  78020. * @param state New state of the button
  78021. * @param changes Which properties on the state changed since last frame
  78022. */
  78023. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78024. console.log("Button id: " + buttonIdx + "state: ");
  78025. console.dir(state);
  78026. };
  78027. /**
  78028. * Base Url for the controller model.
  78029. */
  78030. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78031. /**
  78032. * File name for the controller model.
  78033. */
  78034. GenericController.MODEL_FILENAME = 'generic.babylon';
  78035. return GenericController;
  78036. }(BABYLON.WebVRController));
  78037. BABYLON.GenericController = GenericController;
  78038. })(BABYLON || (BABYLON = {}));
  78039. //# sourceMappingURL=babylon.genericController.js.map
  78040. var BABYLON;
  78041. (function (BABYLON) {
  78042. /**
  78043. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  78044. */
  78045. var LoadedMeshInfo = /** @class */ (function () {
  78046. function LoadedMeshInfo() {
  78047. /**
  78048. * Map of the button meshes contained in the controller
  78049. */
  78050. this.buttonMeshes = {};
  78051. /**
  78052. * Map of the axis meshes contained in the controller
  78053. */
  78054. this.axisMeshes = {};
  78055. }
  78056. return LoadedMeshInfo;
  78057. }());
  78058. /**
  78059. * Defines the WindowsMotionController object that the state of the windows motion controller
  78060. */
  78061. var WindowsMotionController = /** @class */ (function (_super) {
  78062. __extends(WindowsMotionController, _super);
  78063. /**
  78064. * Creates a new WindowsMotionController from a gamepad
  78065. * @param vrGamepad the gamepad that the controller should be created from
  78066. */
  78067. function WindowsMotionController(vrGamepad) {
  78068. var _this = _super.call(this, vrGamepad) || this;
  78069. _this._mapping = {
  78070. // Semantic button names
  78071. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  78072. // A mapping of the button name to glTF model node name
  78073. // that should be transformed by button value.
  78074. buttonMeshNames: {
  78075. 'trigger': 'SELECT',
  78076. 'menu': 'MENU',
  78077. 'grip': 'GRASP',
  78078. 'thumbstick': 'THUMBSTICK_PRESS',
  78079. 'trackpad': 'TOUCHPAD_PRESS'
  78080. },
  78081. // This mapping is used to translate from the Motion Controller to Babylon semantics
  78082. buttonObservableNames: {
  78083. 'trigger': 'onTriggerStateChangedObservable',
  78084. 'menu': 'onSecondaryButtonStateChangedObservable',
  78085. 'grip': 'onMainButtonStateChangedObservable',
  78086. 'thumbstick': 'onPadStateChangedObservable',
  78087. 'trackpad': 'onTrackpadChangedObservable'
  78088. },
  78089. // A mapping of the axis name to glTF model node name
  78090. // that should be transformed by axis value.
  78091. // This array mirrors the browserGamepad.axes array, such that
  78092. // the mesh corresponding to axis 0 is in this array index 0.
  78093. axisMeshNames: [
  78094. 'THUMBSTICK_X',
  78095. 'THUMBSTICK_Y',
  78096. 'TOUCHPAD_TOUCH_X',
  78097. 'TOUCHPAD_TOUCH_Y'
  78098. ],
  78099. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  78100. };
  78101. /**
  78102. * Fired when the trackpad on this controller is clicked
  78103. */
  78104. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  78105. /**
  78106. * Fired when the trackpad on this controller is modified
  78107. */
  78108. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  78109. /**
  78110. * The current x and y values of this controller's trackpad
  78111. */
  78112. _this.trackpad = { x: 0, y: 0 };
  78113. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  78114. _this._loadedMeshInfo = null;
  78115. return _this;
  78116. }
  78117. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  78118. /**
  78119. * Fired when the trigger on this controller is modified
  78120. */
  78121. get: function () {
  78122. return this.onTriggerStateChangedObservable;
  78123. },
  78124. enumerable: true,
  78125. configurable: true
  78126. });
  78127. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  78128. /**
  78129. * Fired when the menu button on this controller is modified
  78130. */
  78131. get: function () {
  78132. return this.onSecondaryButtonStateChangedObservable;
  78133. },
  78134. enumerable: true,
  78135. configurable: true
  78136. });
  78137. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  78138. /**
  78139. * Fired when the grip button on this controller is modified
  78140. */
  78141. get: function () {
  78142. return this.onMainButtonStateChangedObservable;
  78143. },
  78144. enumerable: true,
  78145. configurable: true
  78146. });
  78147. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  78148. /**
  78149. * Fired when the thumbstick button on this controller is modified
  78150. */
  78151. get: function () {
  78152. return this.onPadStateChangedObservable;
  78153. },
  78154. enumerable: true,
  78155. configurable: true
  78156. });
  78157. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  78158. /**
  78159. * Fired when the touchpad button on this controller is modified
  78160. */
  78161. get: function () {
  78162. return this.onTrackpadChangedObservable;
  78163. },
  78164. enumerable: true,
  78165. configurable: true
  78166. });
  78167. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  78168. /**
  78169. * Fired when the touchpad values on this controller are modified
  78170. */
  78171. get: function () {
  78172. return this.onTrackpadValuesChangedObservable;
  78173. },
  78174. enumerable: true,
  78175. configurable: true
  78176. });
  78177. WindowsMotionController.prototype._updateTrackpad = function () {
  78178. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  78179. this.trackpad.x = this.browserGamepad["axes"][2];
  78180. this.trackpad.y = this.browserGamepad["axes"][3];
  78181. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  78182. }
  78183. };
  78184. /**
  78185. * Called once per frame by the engine.
  78186. */
  78187. WindowsMotionController.prototype.update = function () {
  78188. _super.prototype.update.call(this);
  78189. if (this.browserGamepad.axes) {
  78190. this._updateTrackpad();
  78191. // Only need to animate axes if there is a loaded mesh
  78192. if (this._loadedMeshInfo) {
  78193. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  78194. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  78195. }
  78196. }
  78197. }
  78198. };
  78199. /**
  78200. * Called once for each button that changed state since the last frame
  78201. * @param buttonIdx Which button index changed
  78202. * @param state New state of the button
  78203. * @param changes Which properties on the state changed since last frame
  78204. */
  78205. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78206. var buttonName = this._mapping.buttons[buttonIdx];
  78207. if (!buttonName) {
  78208. return;
  78209. }
  78210. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  78211. this._updateTrackpad();
  78212. // Only emit events for buttons that we know how to map from index to name
  78213. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  78214. if (observable) {
  78215. observable.notifyObservers(state);
  78216. }
  78217. this._lerpButtonTransform(buttonName, state.value);
  78218. };
  78219. /**
  78220. * Moves the buttons on the controller mesh based on their current state
  78221. * @param buttonName the name of the button to move
  78222. * @param buttonValue the value of the button which determines the buttons new position
  78223. */
  78224. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  78225. // If there is no loaded mesh, there is nothing to transform.
  78226. if (!this._loadedMeshInfo) {
  78227. return;
  78228. }
  78229. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  78230. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78231. return;
  78232. }
  78233. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  78234. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  78235. };
  78236. /**
  78237. * Moves the axis on the controller mesh based on its current state
  78238. * @param axis the index of the axis
  78239. * @param axisValue the value of the axis which determines the meshes new position
  78240. * @hidden
  78241. */
  78242. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  78243. if (!this._loadedMeshInfo) {
  78244. return;
  78245. }
  78246. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  78247. if (!meshInfo) {
  78248. return;
  78249. }
  78250. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  78251. return;
  78252. }
  78253. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  78254. var lerpValue = axisValue * 0.5 + 0.5;
  78255. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  78256. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  78257. };
  78258. /**
  78259. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78260. * @param scene scene in which to add meshes
  78261. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78262. */
  78263. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  78264. var _this = this;
  78265. if (forceDefault === void 0) { forceDefault = false; }
  78266. var path;
  78267. var filename;
  78268. // Checking if GLB loader is present
  78269. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  78270. // Determine the device specific folder based on the ID suffix
  78271. var device = 'default';
  78272. if (this.id && !forceDefault) {
  78273. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  78274. device = ((match && match[0]) || device);
  78275. }
  78276. // Hand
  78277. if (this.hand === 'left') {
  78278. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  78279. }
  78280. else { // Right is the default if no hand is specified
  78281. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  78282. }
  78283. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  78284. }
  78285. else {
  78286. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  78287. path = BABYLON.GenericController.MODEL_BASE_URL;
  78288. filename = BABYLON.GenericController.MODEL_FILENAME;
  78289. }
  78290. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  78291. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  78292. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  78293. if (!_this._loadedMeshInfo) {
  78294. return;
  78295. }
  78296. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  78297. _this.attachToMesh(_this._defaultModel);
  78298. if (meshLoaded) {
  78299. meshLoaded(_this._defaultModel);
  78300. }
  78301. }, null, function (scene, message) {
  78302. BABYLON.Tools.Log(message);
  78303. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  78304. if (!forceDefault) {
  78305. _this.initControllerMesh(scene, meshLoaded, true);
  78306. }
  78307. });
  78308. };
  78309. /**
  78310. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  78311. * can be transformed by button presses and axes values, based on this._mapping.
  78312. *
  78313. * @param scene scene in which the meshes exist
  78314. * @param meshes list of meshes that make up the controller model to process
  78315. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  78316. */
  78317. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  78318. var loadedMeshInfo = null;
  78319. // Create a new mesh to contain the glTF hierarchy
  78320. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  78321. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  78322. var childMesh = null;
  78323. for (var i = 0; i < meshes.length; i++) {
  78324. var mesh = meshes[i];
  78325. if (!mesh.parent) {
  78326. // Exclude controller meshes from picking results
  78327. mesh.isPickable = false;
  78328. // Handle root node, attach to the new parentMesh
  78329. childMesh = mesh;
  78330. break;
  78331. }
  78332. }
  78333. if (childMesh) {
  78334. childMesh.setParent(parentMesh);
  78335. // Create our mesh info. Note that this method will always return non-null.
  78336. loadedMeshInfo = this.createMeshInfo(parentMesh);
  78337. }
  78338. else {
  78339. BABYLON.Tools.Warn('Could not find root node in model file.');
  78340. }
  78341. return loadedMeshInfo;
  78342. };
  78343. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  78344. var loadedMeshInfo = new LoadedMeshInfo();
  78345. var i;
  78346. loadedMeshInfo.rootNode = rootNode;
  78347. // Reset the caches
  78348. loadedMeshInfo.buttonMeshes = {};
  78349. loadedMeshInfo.axisMeshes = {};
  78350. // Button Meshes
  78351. for (i = 0; i < this._mapping.buttons.length; i++) {
  78352. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  78353. if (!buttonMeshName) {
  78354. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  78355. continue;
  78356. }
  78357. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  78358. if (!buttonMesh) {
  78359. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  78360. continue;
  78361. }
  78362. var buttonMeshInfo = {
  78363. index: i,
  78364. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  78365. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  78366. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  78367. };
  78368. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  78369. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  78370. }
  78371. else {
  78372. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  78373. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  78374. '(VALUE: ' + !!buttonMeshInfo.value +
  78375. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  78376. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  78377. ')');
  78378. }
  78379. }
  78380. // Axis Meshes
  78381. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  78382. var axisMeshName = this._mapping.axisMeshNames[i];
  78383. if (!axisMeshName) {
  78384. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  78385. continue;
  78386. }
  78387. var axisMesh = getChildByName(rootNode, axisMeshName);
  78388. if (!axisMesh) {
  78389. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  78390. continue;
  78391. }
  78392. var axisMeshInfo = {
  78393. index: i,
  78394. value: getImmediateChildByName(axisMesh, 'VALUE'),
  78395. min: getImmediateChildByName(axisMesh, 'MIN'),
  78396. max: getImmediateChildByName(axisMesh, 'MAX')
  78397. };
  78398. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  78399. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  78400. }
  78401. else {
  78402. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  78403. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  78404. '(VALUE: ' + !!axisMeshInfo.value +
  78405. ', MIN: ' + !!axisMeshInfo.min +
  78406. ', MAX:' + !!axisMeshInfo.max +
  78407. ')');
  78408. }
  78409. }
  78410. // Pointing Ray
  78411. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  78412. if (!loadedMeshInfo.pointingPoseNode) {
  78413. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  78414. }
  78415. else {
  78416. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  78417. }
  78418. return loadedMeshInfo;
  78419. // Look through all children recursively. This will return null if no mesh exists with the given name.
  78420. function getChildByName(node, name) {
  78421. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  78422. }
  78423. // Look through only immediate children. This will return null if no mesh exists with the given name.
  78424. function getImmediateChildByName(node, name) {
  78425. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  78426. }
  78427. };
  78428. /**
  78429. * Gets the ray of the controller in the direction the controller is pointing
  78430. * @param length the length the resulting ray should be
  78431. * @returns a ray in the direction the controller is pointing
  78432. */
  78433. WindowsMotionController.prototype.getForwardRay = function (length) {
  78434. if (length === void 0) { length = 100; }
  78435. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  78436. return _super.prototype.getForwardRay.call(this, length);
  78437. }
  78438. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  78439. var origin = m.getTranslation();
  78440. var forward = new BABYLON.Vector3(0, 0, -1);
  78441. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  78442. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  78443. return new BABYLON.Ray(origin, direction, length);
  78444. };
  78445. /**
  78446. * Disposes of the controller
  78447. */
  78448. WindowsMotionController.prototype.dispose = function () {
  78449. _super.prototype.dispose.call(this);
  78450. this.onTrackpadChangedObservable.clear();
  78451. };
  78452. /**
  78453. * The base url used to load the left and right controller models
  78454. */
  78455. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  78456. /**
  78457. * The name of the left controller model file
  78458. */
  78459. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  78460. /**
  78461. * The name of the right controller model file
  78462. */
  78463. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  78464. /**
  78465. * The controller name prefix for this controller type
  78466. */
  78467. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  78468. /**
  78469. * The controller id pattern for this controller type
  78470. */
  78471. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  78472. return WindowsMotionController;
  78473. }(BABYLON.WebVRController));
  78474. BABYLON.WindowsMotionController = WindowsMotionController;
  78475. })(BABYLON || (BABYLON = {}));
  78476. //# sourceMappingURL=babylon.windowsMotionController.js.map
  78477. var BABYLON;
  78478. (function (BABYLON) {
  78479. /**
  78480. * Gear VR Controller
  78481. */
  78482. var GearVRController = /** @class */ (function (_super) {
  78483. __extends(GearVRController, _super);
  78484. /**
  78485. * Creates a new GearVRController from a gamepad
  78486. * @param vrGamepad the gamepad that the controller should be created from
  78487. */
  78488. function GearVRController(vrGamepad) {
  78489. var _this = _super.call(this, vrGamepad) || this;
  78490. _this._maxRotationDistFromHeadset = Math.PI / 5;
  78491. _this._draggedRoomRotation = 0;
  78492. _this._tmpVector = new BABYLON.Vector3();
  78493. _this._buttonIndexToObservableNameMap = [
  78494. 'onTrackpadChangedObservable',
  78495. 'onTriggerStateChangedObservable' // Trigger
  78496. ];
  78497. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  78498. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  78499. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  78500. return _this;
  78501. }
  78502. /**
  78503. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  78504. * @param poseData raw pose fromthe device
  78505. */
  78506. GearVRController.prototype.updateFromDevice = function (poseData) {
  78507. _super.prototype.updateFromDevice.call(this, poseData);
  78508. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  78509. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  78510. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  78511. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  78512. // Find the radian distance away that the headset is from the controllers rotation
  78513. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  78514. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  78515. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  78516. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  78517. this._draggedRoomRotation += rotationAmount;
  78518. // Rotate controller around headset
  78519. var sin = Math.sin(-rotationAmount);
  78520. var cos = Math.cos(-rotationAmount);
  78521. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  78522. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  78523. }
  78524. }
  78525. }
  78526. };
  78527. /**
  78528. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78529. * @param scene scene in which to add meshes
  78530. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78531. */
  78532. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78533. var _this = this;
  78534. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  78535. // Offset the controller so it will rotate around the users wrist
  78536. var mesh = new BABYLON.Mesh("", scene);
  78537. newMeshes[1].parent = mesh;
  78538. newMeshes[1].position.z = -0.15;
  78539. _this._defaultModel = mesh;
  78540. _this.attachToMesh(_this._defaultModel);
  78541. if (meshLoaded) {
  78542. meshLoaded(_this._defaultModel);
  78543. }
  78544. });
  78545. };
  78546. /**
  78547. * Called once for each button that changed state since the last frame
  78548. * @param buttonIdx Which button index changed
  78549. * @param state New state of the button
  78550. * @param changes Which properties on the state changed since last frame
  78551. */
  78552. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78553. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  78554. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  78555. // Only emit events for buttons that we know how to map from index to observable
  78556. var observable = this[observableName];
  78557. if (observable) {
  78558. observable.notifyObservers(state);
  78559. }
  78560. }
  78561. };
  78562. /**
  78563. * Base Url for the controller model.
  78564. */
  78565. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78566. /**
  78567. * File name for the controller model.
  78568. */
  78569. GearVRController.MODEL_FILENAME = 'generic.babylon';
  78570. /**
  78571. * Gamepad Id prefix used to identify this controller.
  78572. */
  78573. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  78574. return GearVRController;
  78575. }(BABYLON.WebVRController));
  78576. BABYLON.GearVRController = GearVRController;
  78577. })(BABYLON || (BABYLON = {}));
  78578. //# sourceMappingURL=babylon.gearVRController.js.map
  78579. var BABYLON;
  78580. (function (BABYLON) {
  78581. /**
  78582. * Google Daydream controller
  78583. */
  78584. var DaydreamController = /** @class */ (function (_super) {
  78585. __extends(DaydreamController, _super);
  78586. /**
  78587. * Creates a new DaydreamController from a gamepad
  78588. * @param vrGamepad the gamepad that the controller should be created from
  78589. */
  78590. function DaydreamController(vrGamepad) {
  78591. var _this = _super.call(this, vrGamepad) || this;
  78592. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  78593. return _this;
  78594. }
  78595. /**
  78596. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  78597. * @param scene scene in which to add meshes
  78598. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  78599. */
  78600. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  78601. var _this = this;
  78602. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  78603. _this._defaultModel = newMeshes[1];
  78604. _this.attachToMesh(_this._defaultModel);
  78605. if (meshLoaded) {
  78606. meshLoaded(_this._defaultModel);
  78607. }
  78608. });
  78609. };
  78610. /**
  78611. * Called once for each button that changed state since the last frame
  78612. * @param buttonIdx Which button index changed
  78613. * @param state New state of the button
  78614. * @param changes Which properties on the state changed since last frame
  78615. */
  78616. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  78617. // Daydream controller only has 1 GamepadButton (on the trackpad).
  78618. if (buttonIdx === 0) {
  78619. var observable = this.onTriggerStateChangedObservable;
  78620. if (observable) {
  78621. observable.notifyObservers(state);
  78622. }
  78623. }
  78624. else {
  78625. // If the app or home buttons are ever made available
  78626. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  78627. }
  78628. };
  78629. /**
  78630. * Base Url for the controller model.
  78631. */
  78632. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  78633. /**
  78634. * File name for the controller model.
  78635. */
  78636. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  78637. /**
  78638. * Gamepad Id prefix used to identify Daydream Controller.
  78639. */
  78640. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  78641. return DaydreamController;
  78642. }(BABYLON.WebVRController));
  78643. BABYLON.DaydreamController = DaydreamController;
  78644. })(BABYLON || (BABYLON = {}));
  78645. //# sourceMappingURL=babylon.daydreamController.js.map
  78646. var BABYLON;
  78647. (function (BABYLON) {
  78648. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  78649. get: function () {
  78650. if (!this._gamepadManager) {
  78651. this._gamepadManager = new BABYLON.GamepadManager(this);
  78652. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  78653. if (!component) {
  78654. component = new GamepadSystemSceneComponent(this);
  78655. this._addComponent(component);
  78656. }
  78657. }
  78658. return this._gamepadManager;
  78659. },
  78660. enumerable: true,
  78661. configurable: true
  78662. });
  78663. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  78664. this.add(new BABYLON.FreeCameraGamepadInput());
  78665. return this;
  78666. };
  78667. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  78668. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  78669. return this;
  78670. };
  78671. /**
  78672. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  78673. */
  78674. var GamepadSystemSceneComponent = /** @class */ (function () {
  78675. /**
  78676. * Creates a new instance of the component for the given scene
  78677. * @param scene Defines the scene to register the component in
  78678. */
  78679. function GamepadSystemSceneComponent(scene) {
  78680. /**
  78681. * The component name helpfull to identify the component in the list of scene components.
  78682. */
  78683. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  78684. this.scene = scene;
  78685. }
  78686. /**
  78687. * Registers the component in a given scene
  78688. */
  78689. GamepadSystemSceneComponent.prototype.register = function () {
  78690. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  78691. };
  78692. /**
  78693. * Rebuilds the elements related to this component in case of
  78694. * context lost for instance.
  78695. */
  78696. GamepadSystemSceneComponent.prototype.rebuild = function () {
  78697. // Nothing to do for gamepads
  78698. };
  78699. /**
  78700. * Disposes the component and the associated ressources
  78701. */
  78702. GamepadSystemSceneComponent.prototype.dispose = function () {
  78703. var gamepadManager = this.scene._gamepadManager;
  78704. if (gamepadManager) {
  78705. gamepadManager.dispose();
  78706. this.scene._gamepadManager = null;
  78707. }
  78708. };
  78709. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  78710. var gamepadManager = this.scene._gamepadManager;
  78711. if (gamepadManager && gamepadManager._isMonitoring) {
  78712. gamepadManager._checkGamepadsStatus();
  78713. }
  78714. };
  78715. return GamepadSystemSceneComponent;
  78716. }());
  78717. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  78718. })(BABYLON || (BABYLON = {}));
  78719. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  78720. var BABYLON;
  78721. (function (BABYLON) {
  78722. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  78723. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  78724. });
  78725. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  78726. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  78727. });
  78728. /**
  78729. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  78730. * an arc rotate version arcFollowCamera are available.
  78731. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78732. */
  78733. var FollowCamera = /** @class */ (function (_super) {
  78734. __extends(FollowCamera, _super);
  78735. /**
  78736. * Instantiates the follow camera.
  78737. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78738. * @param name Define the name of the camera in the scene
  78739. * @param position Define the position of the camera
  78740. * @param scene Define the scene the camera belong to
  78741. * @param lockedTarget Define the target of the camera
  78742. */
  78743. function FollowCamera(name, position, scene, lockedTarget) {
  78744. if (lockedTarget === void 0) { lockedTarget = null; }
  78745. var _this = _super.call(this, name, position, scene) || this;
  78746. /**
  78747. * Distance the follow camera should follow an object at
  78748. */
  78749. _this.radius = 12;
  78750. /**
  78751. * Define a rotation offset between the camera and the object it follows
  78752. */
  78753. _this.rotationOffset = 0;
  78754. /**
  78755. * Define a height offset between the camera and the object it follows.
  78756. * It can help following an object from the top (like a car chaing a plane)
  78757. */
  78758. _this.heightOffset = 4;
  78759. /**
  78760. * Define how fast the camera can accelerate to follow it s target.
  78761. */
  78762. _this.cameraAcceleration = 0.05;
  78763. /**
  78764. * Define the speed limit of the camera following an object.
  78765. */
  78766. _this.maxCameraSpeed = 20;
  78767. _this.lockedTarget = lockedTarget;
  78768. return _this;
  78769. }
  78770. FollowCamera.prototype._follow = function (cameraTarget) {
  78771. if (!cameraTarget)
  78772. return;
  78773. var yRotation;
  78774. if (cameraTarget.rotationQuaternion) {
  78775. var rotMatrix = new BABYLON.Matrix();
  78776. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  78777. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  78778. }
  78779. else {
  78780. yRotation = cameraTarget.rotation.y;
  78781. }
  78782. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  78783. var targetPosition = cameraTarget.getAbsolutePosition();
  78784. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  78785. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  78786. var dx = targetX - this.position.x;
  78787. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  78788. var dz = (targetZ) - this.position.z;
  78789. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  78790. var vy = dy * this.cameraAcceleration;
  78791. var vz = dz * this.cameraAcceleration * 2;
  78792. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  78793. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78794. }
  78795. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  78796. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78797. }
  78798. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  78799. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  78800. }
  78801. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  78802. this.setTarget(targetPosition);
  78803. };
  78804. /** @hidden */
  78805. FollowCamera.prototype._checkInputs = function () {
  78806. _super.prototype._checkInputs.call(this);
  78807. if (this.lockedTarget) {
  78808. this._follow(this.lockedTarget);
  78809. }
  78810. };
  78811. /**
  78812. * Gets the camera class name.
  78813. * @returns the class name
  78814. */
  78815. FollowCamera.prototype.getClassName = function () {
  78816. return "FollowCamera";
  78817. };
  78818. __decorate([
  78819. BABYLON.serialize()
  78820. ], FollowCamera.prototype, "radius", void 0);
  78821. __decorate([
  78822. BABYLON.serialize()
  78823. ], FollowCamera.prototype, "rotationOffset", void 0);
  78824. __decorate([
  78825. BABYLON.serialize()
  78826. ], FollowCamera.prototype, "heightOffset", void 0);
  78827. __decorate([
  78828. BABYLON.serialize()
  78829. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  78830. __decorate([
  78831. BABYLON.serialize()
  78832. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  78833. __decorate([
  78834. BABYLON.serializeAsMeshReference("lockedTargetId")
  78835. ], FollowCamera.prototype, "lockedTarget", void 0);
  78836. return FollowCamera;
  78837. }(BABYLON.TargetCamera));
  78838. BABYLON.FollowCamera = FollowCamera;
  78839. /**
  78840. * Arc Rotate version of the follow camera.
  78841. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  78842. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78843. */
  78844. var ArcFollowCamera = /** @class */ (function (_super) {
  78845. __extends(ArcFollowCamera, _super);
  78846. /**
  78847. * Instantiates a new ArcFollowCamera
  78848. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  78849. * @param name Define the name of the camera
  78850. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  78851. * @param beta Define the rotation angle of the camera around the elevation axis
  78852. * @param radius Define the radius of the camera from its target point
  78853. * @param target Define the target of the camera
  78854. * @param scene Define the scene the camera belongs to
  78855. */
  78856. function ArcFollowCamera(name,
  78857. /** The longitudinal angle of the camera */
  78858. alpha,
  78859. /** The latitudinal angle of the camera */
  78860. beta,
  78861. /** The radius of the camera from its target */
  78862. radius,
  78863. /** Define the camera target (the messh it should follow) */
  78864. target, scene) {
  78865. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  78866. _this.alpha = alpha;
  78867. _this.beta = beta;
  78868. _this.radius = radius;
  78869. _this.target = target;
  78870. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  78871. _this._follow();
  78872. return _this;
  78873. }
  78874. ArcFollowCamera.prototype._follow = function () {
  78875. if (!this.target) {
  78876. return;
  78877. }
  78878. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  78879. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  78880. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  78881. var targetPosition = this.target.getAbsolutePosition();
  78882. this.position = targetPosition.add(this._cartesianCoordinates);
  78883. this.setTarget(targetPosition);
  78884. };
  78885. /** @hidden */
  78886. ArcFollowCamera.prototype._checkInputs = function () {
  78887. _super.prototype._checkInputs.call(this);
  78888. this._follow();
  78889. };
  78890. /**
  78891. * Returns the class name of the object.
  78892. * It is mostly used internally for serialization purposes.
  78893. */
  78894. ArcFollowCamera.prototype.getClassName = function () {
  78895. return "ArcFollowCamera";
  78896. };
  78897. return ArcFollowCamera;
  78898. }(BABYLON.TargetCamera));
  78899. BABYLON.ArcFollowCamera = ArcFollowCamera;
  78900. })(BABYLON || (BABYLON = {}));
  78901. //# sourceMappingURL=babylon.followCamera.js.map
  78902. var BABYLON;
  78903. (function (BABYLON) {
  78904. /**
  78905. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  78906. * which still works and will still be found in many Playgrounds.
  78907. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78908. */
  78909. var UniversalCamera = /** @class */ (function (_super) {
  78910. __extends(UniversalCamera, _super);
  78911. /**
  78912. * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
  78913. * which still works and will still be found in many Playgrounds.
  78914. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78915. * @param name Define the name of the camera in the scene
  78916. * @param position Define the start position of the camera in the scene
  78917. * @param scene Define the scene the camera belongs to
  78918. */
  78919. function UniversalCamera(name, position, scene) {
  78920. var _this = _super.call(this, name, position, scene) || this;
  78921. _this.inputs.addGamepad();
  78922. return _this;
  78923. }
  78924. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  78925. /**
  78926. * Defines the gamepad rotation sensiblity.
  78927. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  78928. */
  78929. get: function () {
  78930. var gamepad = this.inputs.attached["gamepad"];
  78931. if (gamepad)
  78932. return gamepad.gamepadAngularSensibility;
  78933. return 0;
  78934. },
  78935. set: function (value) {
  78936. var gamepad = this.inputs.attached["gamepad"];
  78937. if (gamepad)
  78938. gamepad.gamepadAngularSensibility = value;
  78939. },
  78940. enumerable: true,
  78941. configurable: true
  78942. });
  78943. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  78944. /**
  78945. * Defines the gamepad move sensiblity.
  78946. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  78947. */
  78948. get: function () {
  78949. var gamepad = this.inputs.attached["gamepad"];
  78950. if (gamepad)
  78951. return gamepad.gamepadMoveSensibility;
  78952. return 0;
  78953. },
  78954. set: function (value) {
  78955. var gamepad = this.inputs.attached["gamepad"];
  78956. if (gamepad)
  78957. gamepad.gamepadMoveSensibility = value;
  78958. },
  78959. enumerable: true,
  78960. configurable: true
  78961. });
  78962. /**
  78963. * Gets the current object class name.
  78964. * @return the class name
  78965. */
  78966. UniversalCamera.prototype.getClassName = function () {
  78967. return "UniversalCamera";
  78968. };
  78969. return UniversalCamera;
  78970. }(BABYLON.TouchCamera));
  78971. BABYLON.UniversalCamera = UniversalCamera;
  78972. })(BABYLON || (BABYLON = {}));
  78973. //# sourceMappingURL=babylon.universalCamera.js.map
  78974. var BABYLON;
  78975. (function (BABYLON) {
  78976. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  78977. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  78978. });
  78979. /**
  78980. * This represents a FPS type of camera. This is only here for back compat purpose.
  78981. * Please use the UniversalCamera instead as both are identical.
  78982. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78983. */
  78984. var GamepadCamera = /** @class */ (function (_super) {
  78985. __extends(GamepadCamera, _super);
  78986. /**
  78987. * Instantiates a new Gamepad Camera
  78988. * This represents a FPS type of camera. This is only here for back compat purpose.
  78989. * Please use the UniversalCamera instead as both are identical.
  78990. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78991. * @param name Define the name of the camera in the scene
  78992. * @param position Define the start position of the camera in the scene
  78993. * @param scene Define the scene the camera belongs to
  78994. */
  78995. function GamepadCamera(name, position, scene) {
  78996. return _super.call(this, name, position, scene) || this;
  78997. }
  78998. /**
  78999. * Gets the current object class name.
  79000. * @return the class name
  79001. */
  79002. GamepadCamera.prototype.getClassName = function () {
  79003. return "GamepadCamera";
  79004. };
  79005. return GamepadCamera;
  79006. }(BABYLON.UniversalCamera));
  79007. BABYLON.GamepadCamera = GamepadCamera;
  79008. })(BABYLON || (BABYLON = {}));
  79009. //# sourceMappingURL=babylon.gamepadCamera.js.map
  79010. var BABYLON;
  79011. (function (BABYLON) {
  79012. var PostProcessRenderPipelineManager = /** @class */ (function () {
  79013. function PostProcessRenderPipelineManager() {
  79014. this._renderPipelines = {};
  79015. }
  79016. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  79017. this._renderPipelines[renderPipeline._name] = renderPipeline;
  79018. };
  79019. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  79020. if (unique === void 0) { unique = false; }
  79021. var renderPipeline = this._renderPipelines[renderPipelineName];
  79022. if (!renderPipeline) {
  79023. return;
  79024. }
  79025. renderPipeline._attachCameras(cameras, unique);
  79026. };
  79027. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  79028. var renderPipeline = this._renderPipelines[renderPipelineName];
  79029. if (!renderPipeline) {
  79030. return;
  79031. }
  79032. renderPipeline._detachCameras(cameras);
  79033. };
  79034. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79035. var renderPipeline = this._renderPipelines[renderPipelineName];
  79036. if (!renderPipeline) {
  79037. return;
  79038. }
  79039. renderPipeline._enableEffect(renderEffectName, cameras);
  79040. };
  79041. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  79042. var renderPipeline = this._renderPipelines[renderPipelineName];
  79043. if (!renderPipeline) {
  79044. return;
  79045. }
  79046. renderPipeline._disableEffect(renderEffectName, cameras);
  79047. };
  79048. PostProcessRenderPipelineManager.prototype.update = function () {
  79049. for (var renderPipelineName in this._renderPipelines) {
  79050. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79051. var pipeline = this._renderPipelines[renderPipelineName];
  79052. if (!pipeline.isSupported) {
  79053. pipeline.dispose();
  79054. delete this._renderPipelines[renderPipelineName];
  79055. }
  79056. else {
  79057. pipeline._update();
  79058. }
  79059. }
  79060. }
  79061. };
  79062. /** @hidden */
  79063. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  79064. for (var renderPipelineName in this._renderPipelines) {
  79065. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79066. var pipeline = this._renderPipelines[renderPipelineName];
  79067. pipeline._rebuild();
  79068. }
  79069. }
  79070. };
  79071. PostProcessRenderPipelineManager.prototype.dispose = function () {
  79072. for (var renderPipelineName in this._renderPipelines) {
  79073. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  79074. var pipeline = this._renderPipelines[renderPipelineName];
  79075. pipeline.dispose();
  79076. }
  79077. }
  79078. };
  79079. return PostProcessRenderPipelineManager;
  79080. }());
  79081. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  79082. })(BABYLON || (BABYLON = {}));
  79083. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  79084. var BABYLON;
  79085. (function (BABYLON) {
  79086. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  79087. get: function () {
  79088. if (!this._postProcessRenderPipelineManager) {
  79089. // Register the G Buffer component to the scene.
  79090. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  79091. if (!component) {
  79092. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  79093. this._addComponent(component);
  79094. }
  79095. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  79096. }
  79097. return this._postProcessRenderPipelineManager;
  79098. },
  79099. enumerable: true,
  79100. configurable: true
  79101. });
  79102. /**
  79103. * Defines the Render Pipeline scene component responsible to rendering pipelines
  79104. */
  79105. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  79106. /**
  79107. * Creates a new instance of the component for the given scene
  79108. * @param scene Defines the scene to register the component in
  79109. */
  79110. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  79111. /**
  79112. * The component name helpfull to identify the component in the list of scene components.
  79113. */
  79114. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  79115. this.scene = scene;
  79116. }
  79117. /**
  79118. * Registers the component in a given scene
  79119. */
  79120. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  79121. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  79122. };
  79123. /**
  79124. * Rebuilds the elements related to this component in case of
  79125. * context lost for instance.
  79126. */
  79127. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  79128. if (this.scene._postProcessRenderPipelineManager) {
  79129. this.scene._postProcessRenderPipelineManager._rebuild();
  79130. }
  79131. };
  79132. /**
  79133. * Disposes the component and the associated ressources
  79134. */
  79135. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  79136. if (this.scene._postProcessRenderPipelineManager) {
  79137. this.scene._postProcessRenderPipelineManager.dispose();
  79138. }
  79139. };
  79140. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  79141. if (this.scene._postProcessRenderPipelineManager) {
  79142. this.scene._postProcessRenderPipelineManager.update();
  79143. }
  79144. };
  79145. return PostProcessRenderPipelineManagerSceneComponent;
  79146. }());
  79147. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  79148. })(BABYLON || (BABYLON = {}));
  79149. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  79150. var BABYLON;
  79151. (function (BABYLON) {
  79152. /**
  79153. * This represents a set of one or more post processes in Babylon.
  79154. * A post process can be used to apply a shader to a texture after it is rendered.
  79155. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  79156. */
  79157. var PostProcessRenderEffect = /** @class */ (function () {
  79158. /**
  79159. * Instantiates a post process render effect.
  79160. * A post process can be used to apply a shader to a texture after it is rendered.
  79161. * @param engine The engine the effect is tied to
  79162. * @param name The name of the effect
  79163. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  79164. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  79165. */
  79166. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  79167. this._name = name;
  79168. this._singleInstance = singleInstance || true;
  79169. this._getPostProcesses = getPostProcesses;
  79170. this._cameras = {};
  79171. this._indicesForCamera = {};
  79172. this._postProcesses = {};
  79173. }
  79174. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  79175. /**
  79176. * Checks if all the post processes in the effect are supported.
  79177. */
  79178. get: function () {
  79179. for (var index in this._postProcesses) {
  79180. if (this._postProcesses.hasOwnProperty(index)) {
  79181. var pps = this._postProcesses[index];
  79182. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  79183. if (!pps[ppIndex].isSupported) {
  79184. return false;
  79185. }
  79186. }
  79187. }
  79188. }
  79189. return true;
  79190. },
  79191. enumerable: true,
  79192. configurable: true
  79193. });
  79194. /**
  79195. * Updates the current state of the effect
  79196. * @hidden
  79197. */
  79198. PostProcessRenderEffect.prototype._update = function () {
  79199. };
  79200. /**
  79201. * Attaches the effect on cameras
  79202. * @param cameras The camera to attach to.
  79203. * @hidden
  79204. */
  79205. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  79206. var _this = this;
  79207. var cameraKey;
  79208. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79209. if (!cams) {
  79210. return;
  79211. }
  79212. for (var i = 0; i < cams.length; i++) {
  79213. var camera = cams[i];
  79214. var cameraName = camera.name;
  79215. if (this._singleInstance) {
  79216. cameraKey = 0;
  79217. }
  79218. else {
  79219. cameraKey = cameraName;
  79220. }
  79221. if (!this._postProcesses[cameraKey]) {
  79222. var postProcess = this._getPostProcesses();
  79223. if (postProcess) {
  79224. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  79225. }
  79226. }
  79227. if (!this._indicesForCamera[cameraName]) {
  79228. this._indicesForCamera[cameraName] = [];
  79229. }
  79230. this._postProcesses[cameraKey].forEach(function (postProcess) {
  79231. var index = camera.attachPostProcess(postProcess);
  79232. _this._indicesForCamera[cameraName].push(index);
  79233. });
  79234. if (!this._cameras[cameraName]) {
  79235. this._cameras[cameraName] = camera;
  79236. }
  79237. }
  79238. };
  79239. /**
  79240. * Detatches the effect on cameras
  79241. * @param cameras The camera to detatch from.
  79242. * @hidden
  79243. */
  79244. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  79245. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79246. if (!cams) {
  79247. return;
  79248. }
  79249. for (var i = 0; i < cams.length; i++) {
  79250. var camera = cams[i];
  79251. var cameraName = camera.name;
  79252. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79253. camera.detachPostProcess(postProcess);
  79254. });
  79255. if (this._cameras[cameraName]) {
  79256. //this._indicesForCamera.splice(index, 1);
  79257. this._cameras[cameraName] = null;
  79258. }
  79259. }
  79260. };
  79261. /**
  79262. * Enables the effect on given cameras
  79263. * @param cameras The camera to enable.
  79264. * @hidden
  79265. */
  79266. PostProcessRenderEffect.prototype._enable = function (cameras) {
  79267. var _this = this;
  79268. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79269. if (!cams) {
  79270. return;
  79271. }
  79272. for (var i = 0; i < cams.length; i++) {
  79273. var camera = cams[i];
  79274. var cameraName = camera.name;
  79275. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  79276. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  79277. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79278. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  79279. });
  79280. }
  79281. }
  79282. }
  79283. };
  79284. /**
  79285. * Disables the effect on the given cameras
  79286. * @param cameras The camera to disable.
  79287. * @hidden
  79288. */
  79289. PostProcessRenderEffect.prototype._disable = function (cameras) {
  79290. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79291. if (!cams) {
  79292. return;
  79293. }
  79294. for (var i = 0; i < cams.length; i++) {
  79295. var camera = cams[i];
  79296. var cameraName = camera.name;
  79297. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  79298. camera.detachPostProcess(postProcess);
  79299. });
  79300. }
  79301. };
  79302. /**
  79303. * Gets a list of the post processes contained in the effect.
  79304. * @param camera The camera to get the post processes on.
  79305. * @returns The list of the post processes in the effect.
  79306. */
  79307. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  79308. if (this._singleInstance) {
  79309. return this._postProcesses[0];
  79310. }
  79311. else {
  79312. if (!camera) {
  79313. return null;
  79314. }
  79315. return this._postProcesses[camera.name];
  79316. }
  79317. };
  79318. return PostProcessRenderEffect;
  79319. }());
  79320. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  79321. })(BABYLON || (BABYLON = {}));
  79322. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  79323. var BABYLON;
  79324. (function (BABYLON) {
  79325. var PostProcessRenderPipeline = /** @class */ (function () {
  79326. function PostProcessRenderPipeline(engine, name) {
  79327. this.engine = engine;
  79328. this._name = name;
  79329. this._renderEffects = {};
  79330. this._renderEffectsForIsolatedPass = new Array();
  79331. this._cameras = [];
  79332. }
  79333. PostProcessRenderPipeline.prototype.getClassName = function () {
  79334. return "PostProcessRenderPipeline";
  79335. };
  79336. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  79337. get: function () {
  79338. for (var renderEffectName in this._renderEffects) {
  79339. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79340. if (!this._renderEffects[renderEffectName].isSupported) {
  79341. return false;
  79342. }
  79343. }
  79344. }
  79345. return true;
  79346. },
  79347. enumerable: true,
  79348. configurable: true
  79349. });
  79350. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  79351. this._renderEffects[renderEffect._name] = renderEffect;
  79352. };
  79353. // private
  79354. /** @hidden */
  79355. PostProcessRenderPipeline.prototype._rebuild = function () {
  79356. };
  79357. /** @hidden */
  79358. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  79359. var renderEffects = this._renderEffects[renderEffectName];
  79360. if (!renderEffects) {
  79361. return;
  79362. }
  79363. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79364. };
  79365. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  79366. var renderEffects = this._renderEffects[renderEffectName];
  79367. if (!renderEffects) {
  79368. return;
  79369. }
  79370. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  79371. };
  79372. /** @hidden */
  79373. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  79374. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79375. if (!cams) {
  79376. return;
  79377. }
  79378. var indicesToDelete = [];
  79379. var i;
  79380. for (i = 0; i < cams.length; i++) {
  79381. var camera = cams[i];
  79382. var cameraName = camera.name;
  79383. if (this._cameras.indexOf(camera) === -1) {
  79384. this._cameras[cameraName] = camera;
  79385. }
  79386. else if (unique) {
  79387. indicesToDelete.push(i);
  79388. }
  79389. }
  79390. for (i = 0; i < indicesToDelete.length; i++) {
  79391. cameras.splice(indicesToDelete[i], 1);
  79392. }
  79393. for (var renderEffectName in this._renderEffects) {
  79394. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79395. this._renderEffects[renderEffectName]._attachCameras(cams);
  79396. }
  79397. }
  79398. };
  79399. /** @hidden */
  79400. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  79401. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  79402. if (!cams) {
  79403. return;
  79404. }
  79405. for (var renderEffectName in this._renderEffects) {
  79406. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79407. this._renderEffects[renderEffectName]._detachCameras(cams);
  79408. }
  79409. }
  79410. for (var i = 0; i < cams.length; i++) {
  79411. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  79412. }
  79413. };
  79414. /** @hidden */
  79415. PostProcessRenderPipeline.prototype._update = function () {
  79416. for (var renderEffectName in this._renderEffects) {
  79417. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  79418. this._renderEffects[renderEffectName]._update();
  79419. }
  79420. }
  79421. for (var i = 0; i < this._cameras.length; i++) {
  79422. var cameraName = this._cameras[i].name;
  79423. if (this._renderEffectsForIsolatedPass[cameraName]) {
  79424. this._renderEffectsForIsolatedPass[cameraName]._update();
  79425. }
  79426. }
  79427. };
  79428. /** @hidden */
  79429. PostProcessRenderPipeline.prototype._reset = function () {
  79430. this._renderEffects = {};
  79431. this._renderEffectsForIsolatedPass = new Array();
  79432. };
  79433. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  79434. // 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)
  79435. var effectKeys = Object.keys(this._renderEffects);
  79436. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  79437. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  79438. if (postProcesses) {
  79439. postProcesses[0].samples = sampleCount;
  79440. return true;
  79441. }
  79442. }
  79443. return false;
  79444. };
  79445. PostProcessRenderPipeline.prototype.dispose = function () {
  79446. // Must be implemented by children
  79447. };
  79448. __decorate([
  79449. BABYLON.serialize()
  79450. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  79451. return PostProcessRenderPipeline;
  79452. }());
  79453. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  79454. })(BABYLON || (BABYLON = {}));
  79455. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  79456. var BABYLON;
  79457. (function (BABYLON) {
  79458. /**
  79459. * This represents a depth renderer in Babylon.
  79460. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  79461. */
  79462. var DepthRenderer = /** @class */ (function () {
  79463. /**
  79464. * Instantiates a depth renderer
  79465. * @param scene The scene the renderer belongs to
  79466. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  79467. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  79468. */
  79469. function DepthRenderer(scene, type, camera) {
  79470. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  79471. if (camera === void 0) { camera = null; }
  79472. var _this = this;
  79473. /**
  79474. * Specifiess that the depth renderer will only be used within
  79475. * the camera it is created for.
  79476. * This can help forcing its rendering during the camera processing.
  79477. */
  79478. this.useOnlyInActiveCamera = false;
  79479. this._scene = scene;
  79480. // Register the G Buffer component to the scene.
  79481. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  79482. if (!component) {
  79483. component = new BABYLON.DepthRendererSceneComponent(scene);
  79484. scene._addComponent(component);
  79485. }
  79486. this._camera = camera;
  79487. var engine = scene.getEngine();
  79488. // Render target
  79489. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  79490. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79491. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79492. this._depthMap.refreshRate = 1;
  79493. this._depthMap.renderParticles = false;
  79494. this._depthMap.renderList = null;
  79495. // Camera to get depth map from to support multiple concurrent cameras
  79496. this._depthMap.activeCamera = this._camera;
  79497. this._depthMap.ignoreCameraViewport = true;
  79498. this._depthMap.useCameraPostProcesses = false;
  79499. // set default depth value to 1.0 (far away)
  79500. this._depthMap.onClearObservable.add(function (engine) {
  79501. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  79502. });
  79503. // Custom render function
  79504. var renderSubMesh = function (subMesh) {
  79505. var mesh = subMesh.getRenderingMesh();
  79506. var scene = _this._scene;
  79507. var engine = scene.getEngine();
  79508. var material = subMesh.getMaterial();
  79509. if (!material) {
  79510. return;
  79511. }
  79512. // Culling and reverse (right handed system)
  79513. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79514. // Managing instances
  79515. var batch = mesh._getInstancesRenderList(subMesh._id);
  79516. if (batch.mustReturn) {
  79517. return;
  79518. }
  79519. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79520. var camera = _this._camera || scene.activeCamera;
  79521. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  79522. engine.enableEffect(_this._effect);
  79523. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79524. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79525. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  79526. // Alpha test
  79527. if (material && material.needAlphaTesting()) {
  79528. var alphaTexture = material.getAlphaTestTexture();
  79529. if (alphaTexture) {
  79530. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79531. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79532. }
  79533. }
  79534. // Bones
  79535. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79536. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79537. }
  79538. // Draw
  79539. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79540. }
  79541. };
  79542. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79543. var index;
  79544. if (depthOnlySubMeshes.length) {
  79545. engine.setColorWrite(false);
  79546. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79547. renderSubMesh(depthOnlySubMeshes.data[index]);
  79548. }
  79549. engine.setColorWrite(true);
  79550. }
  79551. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79552. renderSubMesh(opaqueSubMeshes.data[index]);
  79553. }
  79554. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79555. renderSubMesh(alphaTestSubMeshes.data[index]);
  79556. }
  79557. };
  79558. }
  79559. /**
  79560. * Creates the depth rendering effect and checks if the effect is ready.
  79561. * @param subMesh The submesh to be used to render the depth map of
  79562. * @param useInstances If multiple world instances should be used
  79563. * @returns if the depth renderer is ready to render the depth map
  79564. */
  79565. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  79566. var material = subMesh.getMaterial();
  79567. if (material.disableDepthWrite) {
  79568. return false;
  79569. }
  79570. var defines = [];
  79571. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79572. var mesh = subMesh.getMesh();
  79573. // Alpha test
  79574. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  79575. defines.push("#define ALPHATEST");
  79576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79577. attribs.push(BABYLON.VertexBuffer.UVKind);
  79578. defines.push("#define UV1");
  79579. }
  79580. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79581. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79582. defines.push("#define UV2");
  79583. }
  79584. }
  79585. // Bones
  79586. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79587. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79588. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79589. if (mesh.numBoneInfluencers > 4) {
  79590. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79591. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79592. }
  79593. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79594. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79595. }
  79596. else {
  79597. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79598. }
  79599. // Instances
  79600. if (useInstances) {
  79601. defines.push("#define INSTANCES");
  79602. attribs.push("world0");
  79603. attribs.push("world1");
  79604. attribs.push("world2");
  79605. attribs.push("world3");
  79606. }
  79607. // Get correct effect
  79608. var join = defines.join("\n");
  79609. if (this._cachedDefines !== join) {
  79610. this._cachedDefines = join;
  79611. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  79612. }
  79613. return this._effect.isReady();
  79614. };
  79615. /**
  79616. * Gets the texture which the depth map will be written to.
  79617. * @returns The depth map texture
  79618. */
  79619. DepthRenderer.prototype.getDepthMap = function () {
  79620. return this._depthMap;
  79621. };
  79622. /**
  79623. * Disposes of the depth renderer.
  79624. */
  79625. DepthRenderer.prototype.dispose = function () {
  79626. this._depthMap.dispose();
  79627. };
  79628. return DepthRenderer;
  79629. }());
  79630. BABYLON.DepthRenderer = DepthRenderer;
  79631. })(BABYLON || (BABYLON = {}));
  79632. //# sourceMappingURL=babylon.depthRenderer.js.map
  79633. var BABYLON;
  79634. (function (BABYLON) {
  79635. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  79636. camera = camera || this.activeCamera;
  79637. if (!camera) {
  79638. throw "No camera available to enable depth renderer";
  79639. }
  79640. if (!this._depthRenderer) {
  79641. this._depthRenderer = {};
  79642. }
  79643. if (!this._depthRenderer[camera.id]) {
  79644. var textureType = 0;
  79645. if (this.getEngine().getCaps().textureHalfFloatRender) {
  79646. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79647. }
  79648. else if (this.getEngine().getCaps().textureFloatRender) {
  79649. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79650. }
  79651. else {
  79652. throw "Depth renderer does not support int texture type";
  79653. }
  79654. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  79655. }
  79656. return this._depthRenderer[camera.id];
  79657. };
  79658. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  79659. camera = camera || this.activeCamera;
  79660. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  79661. return;
  79662. }
  79663. this._depthRenderer[camera.id].dispose();
  79664. delete this._depthRenderer[camera.id];
  79665. };
  79666. /**
  79667. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  79668. * in several rendering techniques.
  79669. */
  79670. var DepthRendererSceneComponent = /** @class */ (function () {
  79671. /**
  79672. * Creates a new instance of the component for the given scene
  79673. * @param scene Defines the scene to register the component in
  79674. */
  79675. function DepthRendererSceneComponent(scene) {
  79676. /**
  79677. * The component name helpfull to identify the component in the list of scene components.
  79678. */
  79679. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  79680. this.scene = scene;
  79681. }
  79682. /**
  79683. * Registers the component in a given scene
  79684. */
  79685. DepthRendererSceneComponent.prototype.register = function () {
  79686. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  79687. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  79688. };
  79689. /**
  79690. * Rebuilds the elements related to this component in case of
  79691. * context lost for instance.
  79692. */
  79693. DepthRendererSceneComponent.prototype.rebuild = function () {
  79694. // Nothing to do for this component
  79695. };
  79696. /**
  79697. * Disposes the component and the associated ressources
  79698. */
  79699. DepthRendererSceneComponent.prototype.dispose = function () {
  79700. for (var key in this.scene._depthRenderer) {
  79701. this.scene._depthRenderer[key].dispose();
  79702. }
  79703. };
  79704. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  79705. if (this.scene._depthRenderer) {
  79706. for (var key in this.scene._depthRenderer) {
  79707. var depthRenderer = this.scene._depthRenderer[key];
  79708. if (!depthRenderer.useOnlyInActiveCamera) {
  79709. renderTargets.push(depthRenderer.getDepthMap());
  79710. }
  79711. }
  79712. }
  79713. };
  79714. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  79715. if (this.scene._depthRenderer) {
  79716. for (var key in this.scene._depthRenderer) {
  79717. var depthRenderer = this.scene._depthRenderer[key];
  79718. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  79719. renderTargets.push(depthRenderer.getDepthMap());
  79720. }
  79721. }
  79722. }
  79723. };
  79724. return DepthRendererSceneComponent;
  79725. }());
  79726. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  79727. })(BABYLON || (BABYLON = {}));
  79728. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  79729. var BABYLON;
  79730. (function (BABYLON) {
  79731. /**
  79732. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  79733. */
  79734. var GeometryBufferRenderer = /** @class */ (function () {
  79735. /**
  79736. * Creates a new G Buffer for the scene
  79737. * @param scene The scene the buffer belongs to
  79738. * @param ratio How big is the buffer related to the main canvas.
  79739. */
  79740. function GeometryBufferRenderer(scene, ratio) {
  79741. if (ratio === void 0) { ratio = 1; }
  79742. this._enablePosition = false;
  79743. this._scene = scene;
  79744. this._ratio = ratio;
  79745. // Register the G Buffer component to the scene.
  79746. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  79747. if (!component) {
  79748. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  79749. scene._addComponent(component);
  79750. }
  79751. // Render target
  79752. this._createRenderTargets();
  79753. }
  79754. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  79755. /**
  79756. * Set the render list (meshes to be rendered) used in the G buffer.
  79757. */
  79758. set: function (meshes) {
  79759. this._multiRenderTarget.renderList = meshes;
  79760. },
  79761. enumerable: true,
  79762. configurable: true
  79763. });
  79764. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  79765. /**
  79766. * Gets wether or not G buffer are supported by the running hardware.
  79767. * This requires draw buffer supports
  79768. */
  79769. get: function () {
  79770. return this._multiRenderTarget.isSupported;
  79771. },
  79772. enumerable: true,
  79773. configurable: true
  79774. });
  79775. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  79776. /**
  79777. * Gets wether or not position are enabled for the G buffer.
  79778. */
  79779. get: function () {
  79780. return this._enablePosition;
  79781. },
  79782. /**
  79783. * Sets wether or not position are enabled for the G buffer.
  79784. */
  79785. set: function (enable) {
  79786. this._enablePosition = enable;
  79787. this.dispose();
  79788. this._createRenderTargets();
  79789. },
  79790. enumerable: true,
  79791. configurable: true
  79792. });
  79793. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  79794. /**
  79795. * Gets the scene associated with the buffer.
  79796. */
  79797. get: function () {
  79798. return this._scene;
  79799. },
  79800. enumerable: true,
  79801. configurable: true
  79802. });
  79803. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  79804. /**
  79805. * Gets the ratio used by the buffer during its creation.
  79806. * How big is the buffer related to the main canvas.
  79807. */
  79808. get: function () {
  79809. return this._ratio;
  79810. },
  79811. enumerable: true,
  79812. configurable: true
  79813. });
  79814. /**
  79815. * Checks wether everything is ready to render a submesh to the G buffer.
  79816. * @param subMesh the submesh to check readiness for
  79817. * @param useInstances is the mesh drawn using instance or not
  79818. * @returns true if ready otherwise false
  79819. */
  79820. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  79821. var material = subMesh.getMaterial();
  79822. if (material && material.disableDepthWrite) {
  79823. return false;
  79824. }
  79825. var defines = [];
  79826. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79827. var mesh = subMesh.getMesh();
  79828. // Alpha test
  79829. if (material && material.needAlphaTesting()) {
  79830. defines.push("#define ALPHATEST");
  79831. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79832. attribs.push(BABYLON.VertexBuffer.UVKind);
  79833. defines.push("#define UV1");
  79834. }
  79835. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79836. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79837. defines.push("#define UV2");
  79838. }
  79839. }
  79840. // Buffers
  79841. if (this._enablePosition) {
  79842. defines.push("#define POSITION");
  79843. }
  79844. // Bones
  79845. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79846. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79847. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79848. if (mesh.numBoneInfluencers > 4) {
  79849. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79850. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79851. }
  79852. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79853. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79854. }
  79855. else {
  79856. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79857. }
  79858. // Instances
  79859. if (useInstances) {
  79860. defines.push("#define INSTANCES");
  79861. attribs.push("world0");
  79862. attribs.push("world1");
  79863. attribs.push("world2");
  79864. attribs.push("world3");
  79865. }
  79866. // Get correct effect
  79867. var join = defines.join("\n");
  79868. if (this._cachedDefines !== join) {
  79869. this._cachedDefines = join;
  79870. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  79871. }
  79872. return this._effect.isReady();
  79873. };
  79874. /**
  79875. * Gets the current underlying G Buffer.
  79876. * @returns the buffer
  79877. */
  79878. GeometryBufferRenderer.prototype.getGBuffer = function () {
  79879. return this._multiRenderTarget;
  79880. };
  79881. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  79882. /**
  79883. * Gets the number of samples used to render the buffer (anti aliasing).
  79884. */
  79885. get: function () {
  79886. return this._multiRenderTarget.samples;
  79887. },
  79888. /**
  79889. * Sets the number of samples used to render the buffer (anti aliasing).
  79890. */
  79891. set: function (value) {
  79892. this._multiRenderTarget.samples = value;
  79893. },
  79894. enumerable: true,
  79895. configurable: true
  79896. });
  79897. /**
  79898. * Disposes the renderer and frees up associated resources.
  79899. */
  79900. GeometryBufferRenderer.prototype.dispose = function () {
  79901. this.getGBuffer().dispose();
  79902. };
  79903. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  79904. var _this = this;
  79905. var engine = this._scene.getEngine();
  79906. var count = this._enablePosition ? 3 : 2;
  79907. 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 });
  79908. if (!this.isSupported) {
  79909. return;
  79910. }
  79911. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79912. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79913. this._multiRenderTarget.refreshRate = 1;
  79914. this._multiRenderTarget.renderParticles = false;
  79915. this._multiRenderTarget.renderList = null;
  79916. // set default depth value to 1.0 (far away)
  79917. this._multiRenderTarget.onClearObservable.add(function (engine) {
  79918. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  79919. });
  79920. // Custom render function
  79921. var renderSubMesh = function (subMesh) {
  79922. var mesh = subMesh.getRenderingMesh();
  79923. var scene = _this._scene;
  79924. var engine = scene.getEngine();
  79925. var material = subMesh.getMaterial();
  79926. if (!material) {
  79927. return;
  79928. }
  79929. // Culling
  79930. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79931. // Managing instances
  79932. var batch = mesh._getInstancesRenderList(subMesh._id);
  79933. if (batch.mustReturn) {
  79934. return;
  79935. }
  79936. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79937. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  79938. engine.enableEffect(_this._effect);
  79939. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79940. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79941. _this._effect.setMatrix("view", scene.getViewMatrix());
  79942. // Alpha test
  79943. if (material && material.needAlphaTesting()) {
  79944. var alphaTexture = material.getAlphaTestTexture();
  79945. if (alphaTexture) {
  79946. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79947. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79948. }
  79949. }
  79950. // Bones
  79951. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79952. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79953. }
  79954. // Draw
  79955. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79956. }
  79957. };
  79958. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79959. var index;
  79960. if (depthOnlySubMeshes.length) {
  79961. engine.setColorWrite(false);
  79962. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79963. renderSubMesh(depthOnlySubMeshes.data[index]);
  79964. }
  79965. engine.setColorWrite(true);
  79966. }
  79967. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79968. renderSubMesh(opaqueSubMeshes.data[index]);
  79969. }
  79970. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79971. renderSubMesh(alphaTestSubMeshes.data[index]);
  79972. }
  79973. };
  79974. };
  79975. return GeometryBufferRenderer;
  79976. }());
  79977. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  79978. })(BABYLON || (BABYLON = {}));
  79979. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  79980. var BABYLON;
  79981. (function (BABYLON) {
  79982. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  79983. get: function () {
  79984. this._geometryBufferRenderer;
  79985. },
  79986. set: function (value) {
  79987. if (value && value.isSupported) {
  79988. this._geometryBufferRenderer = value;
  79989. }
  79990. ;
  79991. },
  79992. enumerable: true,
  79993. configurable: true
  79994. });
  79995. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  79996. if (ratio === void 0) { ratio = 1; }
  79997. if (this._geometryBufferRenderer) {
  79998. return this._geometryBufferRenderer;
  79999. }
  80000. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  80001. if (!this._geometryBufferRenderer.isSupported) {
  80002. this._geometryBufferRenderer = null;
  80003. }
  80004. return this._geometryBufferRenderer;
  80005. };
  80006. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  80007. if (!this._geometryBufferRenderer) {
  80008. return;
  80009. }
  80010. this._geometryBufferRenderer.dispose();
  80011. this._geometryBufferRenderer = null;
  80012. };
  80013. /**
  80014. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  80015. * in several rendering techniques.
  80016. */
  80017. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  80018. /**
  80019. * Creates a new instance of the component for the given scene
  80020. * @param scene Defines the scene to register the component in
  80021. */
  80022. function GeometryBufferRendererSceneComponent(scene) {
  80023. /**
  80024. * The component name helpful to identify the component in the list of scene components.
  80025. */
  80026. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  80027. this.scene = scene;
  80028. }
  80029. /**
  80030. * Registers the component in a given scene
  80031. */
  80032. GeometryBufferRendererSceneComponent.prototype.register = function () {
  80033. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  80034. };
  80035. /**
  80036. * Rebuilds the elements related to this component in case of
  80037. * context lost for instance.
  80038. */
  80039. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  80040. // Nothing to do for this component
  80041. };
  80042. /**
  80043. * Disposes the component and the associated ressources
  80044. */
  80045. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  80046. // Nothing to do for this component
  80047. };
  80048. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  80049. if (this.scene._geometryBufferRenderer) {
  80050. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  80051. }
  80052. };
  80053. return GeometryBufferRendererSceneComponent;
  80054. }());
  80055. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  80056. })(BABYLON || (BABYLON = {}));
  80057. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  80058. var BABYLON;
  80059. (function (BABYLON) {
  80060. var SSAORenderingPipeline = /** @class */ (function (_super) {
  80061. __extends(SSAORenderingPipeline, _super);
  80062. /**
  80063. * @constructor
  80064. * @param {string} name - The rendering pipeline name
  80065. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80066. * @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 }
  80067. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80068. */
  80069. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  80070. var _this = _super.call(this, scene.getEngine(), name) || this;
  80071. // Members
  80072. /**
  80073. * The PassPostProcess id in the pipeline that contains the original scene color
  80074. */
  80075. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80076. /**
  80077. * The SSAO PostProcess id in the pipeline
  80078. */
  80079. _this.SSAORenderEffect = "SSAORenderEffect";
  80080. /**
  80081. * The horizontal blur PostProcess id in the pipeline
  80082. */
  80083. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80084. /**
  80085. * The vertical blur PostProcess id in the pipeline
  80086. */
  80087. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80088. /**
  80089. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80090. */
  80091. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80092. /**
  80093. * The output strength of the SSAO post-process. Default value is 1.0.
  80094. */
  80095. _this.totalStrength = 1.0;
  80096. /**
  80097. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  80098. */
  80099. _this.radius = 0.0001;
  80100. /**
  80101. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  80102. * Must not be equal to fallOff and superior to fallOff.
  80103. * Default value is 0.975
  80104. */
  80105. _this.area = 0.0075;
  80106. /**
  80107. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  80108. * Must not be equal to area and inferior to area.
  80109. * Default value is 0.0
  80110. */
  80111. _this.fallOff = 0.000001;
  80112. /**
  80113. * The base color of the SSAO post-process
  80114. * The final result is "base + ssao" between [0, 1]
  80115. */
  80116. _this.base = 0.5;
  80117. _this._firstUpdate = true;
  80118. _this._scene = scene;
  80119. // Set up assets
  80120. _this._createRandomTexture();
  80121. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  80122. var ssaoRatio = ratio.ssaoRatio || ratio;
  80123. var combineRatio = ratio.combineRatio || ratio;
  80124. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80125. _this._createSSAOPostProcess(ssaoRatio);
  80126. _this._createBlurPostProcess(ssaoRatio);
  80127. _this._createSSAOCombinePostProcess(combineRatio);
  80128. // Set up pipeline
  80129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80130. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80131. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80132. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80134. // Finish
  80135. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80136. if (cameras)
  80137. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80138. return _this;
  80139. }
  80140. // Public Methods
  80141. /**
  80142. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80143. */
  80144. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  80145. if (disableDepthRender === void 0) { disableDepthRender = false; }
  80146. for (var i = 0; i < this._scene.cameras.length; i++) {
  80147. var camera = this._scene.cameras[i];
  80148. this._originalColorPostProcess.dispose(camera);
  80149. this._ssaoPostProcess.dispose(camera);
  80150. this._blurHPostProcess.dispose(camera);
  80151. this._blurVPostProcess.dispose(camera);
  80152. this._ssaoCombinePostProcess.dispose(camera);
  80153. }
  80154. this._randomTexture.dispose();
  80155. if (disableDepthRender)
  80156. this._scene.disableDepthRenderer();
  80157. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80158. _super.prototype.dispose.call(this);
  80159. };
  80160. // Private Methods
  80161. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  80162. var _this = this;
  80163. var size = 16;
  80164. 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);
  80165. 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);
  80166. this._blurHPostProcess.onActivateObservable.add(function () {
  80167. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  80168. _this._blurHPostProcess.kernel = size * dw;
  80169. });
  80170. this._blurVPostProcess.onActivateObservable.add(function () {
  80171. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  80172. _this._blurVPostProcess.kernel = size * dw;
  80173. });
  80174. };
  80175. /** @hidden */
  80176. SSAORenderingPipeline.prototype._rebuild = function () {
  80177. this._firstUpdate = true;
  80178. _super.prototype._rebuild.call(this);
  80179. };
  80180. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80181. var _this = this;
  80182. var numSamples = 16;
  80183. var sampleSphere = [
  80184. 0.5381, 0.1856, -0.4319,
  80185. 0.1379, 0.2486, 0.4430,
  80186. 0.3371, 0.5679, -0.0057,
  80187. -0.6999, -0.0451, -0.0019,
  80188. 0.0689, -0.1598, -0.8547,
  80189. 0.0560, 0.0069, -0.1843,
  80190. -0.0146, 0.1402, 0.0762,
  80191. 0.0100, -0.1924, -0.0344,
  80192. -0.3577, -0.5301, -0.4358,
  80193. -0.3169, 0.1063, 0.0158,
  80194. 0.0103, -0.5869, 0.0046,
  80195. -0.0897, -0.4940, 0.3287,
  80196. 0.7119, -0.0154, -0.0918,
  80197. -0.0533, 0.0596, -0.5411,
  80198. 0.0352, -0.0631, 0.5460,
  80199. -0.4776, 0.2847, -0.0271
  80200. ];
  80201. var samplesFactor = 1.0 / numSamples;
  80202. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  80203. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80204. "area", "fallOff", "base", "range", "viewport"
  80205. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80206. this._ssaoPostProcess.onApply = function (effect) {
  80207. if (_this._firstUpdate) {
  80208. effect.setArray3("sampleSphere", sampleSphere);
  80209. effect.setFloat("samplesFactor", samplesFactor);
  80210. effect.setFloat("randTextureTiles", 4.0);
  80211. }
  80212. effect.setFloat("totalStrength", _this.totalStrength);
  80213. effect.setFloat("radius", _this.radius);
  80214. effect.setFloat("area", _this.area);
  80215. effect.setFloat("fallOff", _this.fallOff);
  80216. effect.setFloat("base", _this.base);
  80217. effect.setTexture("textureSampler", _this._depthTexture);
  80218. effect.setTexture("randomSampler", _this._randomTexture);
  80219. };
  80220. };
  80221. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80222. var _this = this;
  80223. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80224. this._ssaoCombinePostProcess.onApply = function (effect) {
  80225. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  80226. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80227. };
  80228. };
  80229. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  80230. var size = 512;
  80231. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80232. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80233. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80234. var context = this._randomTexture.getContext();
  80235. var rand = function (min, max) {
  80236. return Math.random() * (max - min) + min;
  80237. };
  80238. var randVector = BABYLON.Vector3.Zero();
  80239. for (var x = 0; x < size; x++) {
  80240. for (var y = 0; y < size; y++) {
  80241. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  80242. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  80243. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  80244. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80245. context.fillRect(x, y, 1, 1);
  80246. }
  80247. }
  80248. this._randomTexture.update(false);
  80249. };
  80250. __decorate([
  80251. BABYLON.serialize()
  80252. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  80253. __decorate([
  80254. BABYLON.serialize()
  80255. ], SSAORenderingPipeline.prototype, "radius", void 0);
  80256. __decorate([
  80257. BABYLON.serialize()
  80258. ], SSAORenderingPipeline.prototype, "area", void 0);
  80259. __decorate([
  80260. BABYLON.serialize()
  80261. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  80262. __decorate([
  80263. BABYLON.serialize()
  80264. ], SSAORenderingPipeline.prototype, "base", void 0);
  80265. return SSAORenderingPipeline;
  80266. }(BABYLON.PostProcessRenderPipeline));
  80267. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  80268. })(BABYLON || (BABYLON = {}));
  80269. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  80270. var BABYLON;
  80271. (function (BABYLON) {
  80272. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  80273. __extends(SSAO2RenderingPipeline, _super);
  80274. /**
  80275. * @constructor
  80276. * @param {string} name - The rendering pipeline name
  80277. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80278. * @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 }
  80279. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80280. */
  80281. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  80282. var _this = _super.call(this, scene.getEngine(), name) || this;
  80283. // Members
  80284. /**
  80285. * The PassPostProcess id in the pipeline that contains the original scene color
  80286. */
  80287. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  80288. /**
  80289. * The SSAO PostProcess id in the pipeline
  80290. */
  80291. _this.SSAORenderEffect = "SSAORenderEffect";
  80292. /**
  80293. * The horizontal blur PostProcess id in the pipeline
  80294. */
  80295. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  80296. /**
  80297. * The vertical blur PostProcess id in the pipeline
  80298. */
  80299. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  80300. /**
  80301. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  80302. */
  80303. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  80304. /**
  80305. * The output strength of the SSAO post-process. Default value is 1.0.
  80306. */
  80307. _this.totalStrength = 1.0;
  80308. /**
  80309. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  80310. */
  80311. _this.maxZ = 100.0;
  80312. /**
  80313. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  80314. */
  80315. _this.minZAspect = 0.2;
  80316. _this._samples = 8;
  80317. _this._textureSamples = 1;
  80318. /**
  80319. * Are we using bilateral blur ?
  80320. */
  80321. _this._expensiveBlur = true;
  80322. /**
  80323. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  80324. */
  80325. _this.radius = 2.0;
  80326. /**
  80327. * The base color of the SSAO post-process
  80328. * The final result is "base + ssao" between [0, 1]
  80329. */
  80330. _this.base = 0;
  80331. _this._firstUpdate = true;
  80332. _this._bits = new Uint32Array(1);
  80333. _this._scene = scene;
  80334. _this._ratio = ratio;
  80335. if (!_this.isSupported) {
  80336. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  80337. return _this;
  80338. }
  80339. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  80340. var blurRatio = _this._ratio.blurRatio || ratio;
  80341. // Set up assets
  80342. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  80343. _this._createRandomTexture();
  80344. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  80345. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  80346. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  80347. _this._originalColorPostProcess.samples = _this.textureSamples;
  80348. _this._createSSAOPostProcess(1.0);
  80349. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  80350. _this._createSSAOCombinePostProcess(blurRatio);
  80351. // Set up pipeline
  80352. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  80353. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  80354. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  80355. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  80356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  80357. // Finish
  80358. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80359. if (cameras)
  80360. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80361. return _this;
  80362. }
  80363. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  80364. get: function () {
  80365. return this._samples;
  80366. },
  80367. /**
  80368. * Number of samples used for the SSAO calculations. Default value is 8
  80369. */
  80370. set: function (n) {
  80371. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  80372. this._samples = n;
  80373. this._sampleSphere = this._generateHemisphere();
  80374. this._firstUpdate = true;
  80375. },
  80376. enumerable: true,
  80377. configurable: true
  80378. });
  80379. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  80380. get: function () {
  80381. return this._textureSamples;
  80382. },
  80383. /**
  80384. * Number of samples to use for antialiasing
  80385. */
  80386. set: function (n) {
  80387. this._textureSamples = n;
  80388. this._originalColorPostProcess.samples = n;
  80389. this._blurHPostProcess.samples = n;
  80390. this._blurVPostProcess.samples = n;
  80391. this._ssaoPostProcess.samples = n;
  80392. this._ssaoCombinePostProcess.samples = n;
  80393. },
  80394. enumerable: true,
  80395. configurable: true
  80396. });
  80397. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  80398. get: function () {
  80399. return this._expensiveBlur;
  80400. },
  80401. set: function (b) {
  80402. 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"]);
  80403. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  80404. this._expensiveBlur = b;
  80405. this._firstUpdate = true;
  80406. },
  80407. enumerable: true,
  80408. configurable: true
  80409. });
  80410. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  80411. /**
  80412. * Support test.
  80413. */
  80414. get: function () {
  80415. var engine = BABYLON.Engine.LastCreatedEngine;
  80416. if (!engine) {
  80417. return false;
  80418. }
  80419. return engine.getCaps().drawBuffersExtension;
  80420. },
  80421. enumerable: true,
  80422. configurable: true
  80423. });
  80424. // Public Methods
  80425. /**
  80426. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  80427. */
  80428. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  80429. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  80430. for (var i = 0; i < this._scene.cameras.length; i++) {
  80431. var camera = this._scene.cameras[i];
  80432. this._originalColorPostProcess.dispose(camera);
  80433. this._ssaoPostProcess.dispose(camera);
  80434. this._blurHPostProcess.dispose(camera);
  80435. this._blurVPostProcess.dispose(camera);
  80436. this._ssaoCombinePostProcess.dispose(camera);
  80437. }
  80438. this._randomTexture.dispose();
  80439. if (disableGeometryBufferRenderer)
  80440. this._scene.disableGeometryBufferRenderer();
  80441. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80442. _super.prototype.dispose.call(this);
  80443. };
  80444. // Private Methods
  80445. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  80446. var _this = this;
  80447. this._samplerOffsets = [];
  80448. var expensive = this.expensiveBlur;
  80449. for (var i = -8; i < 8; i++) {
  80450. this._samplerOffsets.push(i * 2 + 0.5);
  80451. }
  80452. 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");
  80453. this._blurHPostProcess.onApply = function (effect) {
  80454. if (!_this._scene.activeCamera) {
  80455. return;
  80456. }
  80457. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  80458. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80459. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80460. effect.setFloat("radius", _this.radius);
  80461. effect.setTexture("depthSampler", _this._depthTexture);
  80462. if (_this._firstUpdate) {
  80463. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80464. }
  80465. };
  80466. 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");
  80467. this._blurVPostProcess.onApply = function (effect) {
  80468. if (!_this._scene.activeCamera) {
  80469. return;
  80470. }
  80471. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  80472. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80473. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80474. effect.setFloat("radius", _this.radius);
  80475. effect.setTexture("depthSampler", _this._depthTexture);
  80476. if (_this._firstUpdate) {
  80477. effect.setArray("samplerOffsets", _this._samplerOffsets);
  80478. _this._firstUpdate = false;
  80479. }
  80480. };
  80481. this._blurHPostProcess.samples = this.textureSamples;
  80482. this._blurVPostProcess.samples = this.textureSamples;
  80483. };
  80484. /** @hidden */
  80485. SSAO2RenderingPipeline.prototype._rebuild = function () {
  80486. this._firstUpdate = true;
  80487. _super.prototype._rebuild.call(this);
  80488. };
  80489. //Van der Corput radical inverse
  80490. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  80491. this._bits[0] = i;
  80492. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  80493. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  80494. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  80495. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  80496. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  80497. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  80498. };
  80499. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  80500. return [i / n, this._radicalInverse_VdC(i)];
  80501. };
  80502. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  80503. var phi = v * 2.0 * Math.PI;
  80504. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  80505. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  80506. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  80507. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  80508. };
  80509. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  80510. var numSamples = this.samples;
  80511. var result = [];
  80512. var vector;
  80513. var i = 0;
  80514. while (i < numSamples) {
  80515. if (numSamples < 16) {
  80516. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  80517. }
  80518. else {
  80519. var rand = this._hammersley(i, numSamples);
  80520. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  80521. }
  80522. result.push(vector.x, vector.y, vector.z);
  80523. i++;
  80524. }
  80525. return result;
  80526. };
  80527. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  80528. var _this = this;
  80529. var numSamples = this.samples;
  80530. this._sampleSphere = this._generateHemisphere();
  80531. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  80532. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  80533. "base", "range", "projection", "near", "far", "texelSize",
  80534. "xViewport", "yViewport", "maxZ", "minZAspect"
  80535. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  80536. this._ssaoPostProcess.onApply = function (effect) {
  80537. if (_this._firstUpdate) {
  80538. effect.setArray3("sampleSphere", _this._sampleSphere);
  80539. effect.setFloat("randTextureTiles", 32.0);
  80540. }
  80541. if (!_this._scene.activeCamera) {
  80542. return;
  80543. }
  80544. effect.setFloat("samplesFactor", 1 / _this.samples);
  80545. effect.setFloat("totalStrength", _this.totalStrength);
  80546. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  80547. effect.setFloat("radius", _this.radius);
  80548. effect.setFloat("maxZ", _this.maxZ);
  80549. effect.setFloat("minZAspect", _this.minZAspect);
  80550. effect.setFloat("base", _this.base);
  80551. effect.setFloat("near", _this._scene.activeCamera.minZ);
  80552. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  80553. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  80554. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  80555. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  80556. effect.setTexture("textureSampler", _this._depthTexture);
  80557. effect.setTexture("normalSampler", _this._normalTexture);
  80558. effect.setTexture("randomSampler", _this._randomTexture);
  80559. };
  80560. this._ssaoPostProcess.samples = this.textureSamples;
  80561. };
  80562. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  80563. var _this = this;
  80564. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80565. this._ssaoCombinePostProcess.onApply = function (effect) {
  80566. var viewport = _this._scene.activeCamera.viewport;
  80567. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  80568. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  80569. };
  80570. this._ssaoCombinePostProcess.samples = this.textureSamples;
  80571. };
  80572. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  80573. var size = 128;
  80574. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  80575. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80576. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80577. var context = this._randomTexture.getContext();
  80578. var rand = function (min, max) {
  80579. return Math.random() * (max - min) + min;
  80580. };
  80581. var randVector = BABYLON.Vector3.Zero();
  80582. for (var x = 0; x < size; x++) {
  80583. for (var y = 0; y < size; y++) {
  80584. randVector.x = rand(0.0, 1.0);
  80585. randVector.y = rand(0.0, 1.0);
  80586. randVector.z = 0.0;
  80587. randVector.normalize();
  80588. randVector.scaleInPlace(255);
  80589. randVector.x = Math.floor(randVector.x);
  80590. randVector.y = Math.floor(randVector.y);
  80591. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  80592. context.fillRect(x, y, 1, 1);
  80593. }
  80594. }
  80595. this._randomTexture.update(false);
  80596. };
  80597. /**
  80598. * Serialize the rendering pipeline (Used when exporting)
  80599. * @returns the serialized object
  80600. */
  80601. SSAO2RenderingPipeline.prototype.serialize = function () {
  80602. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80603. serializationObject.customType = "SSAO2RenderingPipeline";
  80604. return serializationObject;
  80605. };
  80606. /**
  80607. * Parse the serialized pipeline
  80608. * @param source Source pipeline.
  80609. * @param scene The scene to load the pipeline to.
  80610. * @param rootUrl The URL of the serialized pipeline.
  80611. * @returns An instantiated pipeline from the serialized object.
  80612. */
  80613. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  80614. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  80615. };
  80616. __decorate([
  80617. BABYLON.serialize()
  80618. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  80619. __decorate([
  80620. BABYLON.serialize()
  80621. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  80622. __decorate([
  80623. BABYLON.serialize()
  80624. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  80625. __decorate([
  80626. BABYLON.serialize("samples")
  80627. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  80628. __decorate([
  80629. BABYLON.serialize("textureSamples")
  80630. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  80631. __decorate([
  80632. BABYLON.serialize()
  80633. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  80634. __decorate([
  80635. BABYLON.serialize("expensiveBlur")
  80636. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  80637. __decorate([
  80638. BABYLON.serialize()
  80639. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  80640. __decorate([
  80641. BABYLON.serialize()
  80642. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  80643. return SSAO2RenderingPipeline;
  80644. }(BABYLON.PostProcessRenderPipeline));
  80645. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  80646. })(BABYLON || (BABYLON = {}));
  80647. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  80648. // BABYLON.JS Chromatic Aberration GLSL Shader
  80649. // Author: Olivier Guyot
  80650. // Separates very slightly R, G and B colors on the edges of the screen
  80651. // Inspired by Francois Tarlier & Martins Upitis
  80652. var BABYLON;
  80653. (function (BABYLON) {
  80654. var LensRenderingPipeline = /** @class */ (function (_super) {
  80655. __extends(LensRenderingPipeline, _super);
  80656. /**
  80657. * @constructor
  80658. *
  80659. * Effect parameters are as follow:
  80660. * {
  80661. * chromatic_aberration: number; // from 0 to x (1 for realism)
  80662. * edge_blur: number; // from 0 to x (1 for realism)
  80663. * distortion: number; // from 0 to x (1 for realism)
  80664. * grain_amount: number; // from 0 to 1
  80665. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  80666. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  80667. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  80668. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  80669. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  80670. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  80671. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  80672. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  80673. * }
  80674. * Note: if an effect parameter is unset, effect is disabled
  80675. *
  80676. * @param {string} name - The rendering pipeline name
  80677. * @param {object} parameters - An object containing all parameters (see above)
  80678. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80679. * @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)
  80680. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80681. */
  80682. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  80683. if (ratio === void 0) { ratio = 1.0; }
  80684. var _this = _super.call(this, scene.getEngine(), name) || this;
  80685. // Lens effects can be of the following:
  80686. // - chromatic aberration (slight shift of RGB colors)
  80687. // - blur on the edge of the lens
  80688. // - lens distortion
  80689. // - depth-of-field blur & highlights enhancing
  80690. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  80691. // - grain effect (noise or custom texture)
  80692. // Two additional texture samplers are needed:
  80693. // - depth map (for depth-of-field)
  80694. // - grain texture
  80695. /**
  80696. * The chromatic aberration PostProcess id in the pipeline
  80697. */
  80698. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  80699. /**
  80700. * The highlights enhancing PostProcess id in the pipeline
  80701. */
  80702. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  80703. /**
  80704. * The depth-of-field PostProcess id in the pipeline
  80705. */
  80706. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  80707. _this._scene = scene;
  80708. // Fetch texture samplers
  80709. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  80710. if (parameters.grain_texture) {
  80711. _this._grainTexture = parameters.grain_texture;
  80712. }
  80713. else {
  80714. _this._createGrainTexture();
  80715. }
  80716. // save parameters
  80717. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  80718. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  80719. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  80720. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  80721. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  80722. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  80723. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  80724. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  80725. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  80726. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  80727. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  80728. // Create effects
  80729. _this._createChromaticAberrationPostProcess(ratio);
  80730. _this._createHighlightsPostProcess(ratio);
  80731. _this._createDepthOfFieldPostProcess(ratio / 4);
  80732. // Set up pipeline
  80733. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  80734. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  80735. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  80736. if (_this._highlightsGain === -1) {
  80737. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  80738. }
  80739. // Finish
  80740. scene.postProcessRenderPipelineManager.addPipeline(_this);
  80741. if (cameras) {
  80742. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  80743. }
  80744. return _this;
  80745. }
  80746. // public methods (self explanatory)
  80747. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  80748. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  80749. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  80750. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  80751. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  80752. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  80753. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  80754. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  80755. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  80756. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  80757. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  80758. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  80759. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  80760. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  80761. };
  80762. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  80763. this._highlightsPostProcess.updateEffect();
  80764. };
  80765. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  80766. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  80767. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  80768. this._highlightsGain = amount;
  80769. };
  80770. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  80771. if (this._highlightsGain === -1) {
  80772. this._highlightsGain = 1.0;
  80773. }
  80774. this._highlightsThreshold = amount;
  80775. };
  80776. LensRenderingPipeline.prototype.disableHighlights = function () {
  80777. this._highlightsGain = -1;
  80778. };
  80779. /**
  80780. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  80781. */
  80782. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  80783. if (disableDepthRender === void 0) { disableDepthRender = false; }
  80784. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  80785. this._chromaticAberrationPostProcess = null;
  80786. this._highlightsPostProcess = null;
  80787. this._depthOfFieldPostProcess = null;
  80788. this._grainTexture.dispose();
  80789. if (disableDepthRender)
  80790. this._scene.disableDepthRenderer();
  80791. };
  80792. // colors shifting and distortion
  80793. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  80794. var _this = this;
  80795. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  80796. [], // samplers
  80797. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80798. this._chromaticAberrationPostProcess.onApply = function (effect) {
  80799. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  80800. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  80801. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  80802. effect.setFloat('radialIntensity', 1);
  80803. effect.setFloat2('direction', 17, 17);
  80804. effect.setFloat2('centerPosition', 0.5, 0.5);
  80805. };
  80806. };
  80807. // highlights enhancing
  80808. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  80809. var _this = this;
  80810. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  80811. [], // samplers
  80812. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  80813. this._highlightsPostProcess.onApply = function (effect) {
  80814. effect.setFloat('gain', _this._highlightsGain);
  80815. effect.setFloat('threshold', _this._highlightsThreshold);
  80816. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  80817. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  80818. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  80819. };
  80820. };
  80821. // colors shifting and distortion
  80822. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  80823. var _this = this;
  80824. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  80825. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  80826. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  80827. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  80828. this._depthOfFieldPostProcess.onApply = function (effect) {
  80829. effect.setTexture("depthSampler", _this._depthTexture);
  80830. effect.setTexture("grainSampler", _this._grainTexture);
  80831. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  80832. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  80833. effect.setFloat('grain_amount', _this._grainAmount);
  80834. effect.setBool('blur_noise', _this._blurNoise);
  80835. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  80836. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  80837. effect.setFloat('distortion', _this._distortion);
  80838. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  80839. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  80840. effect.setFloat('aperture', _this._dofAperture);
  80841. effect.setFloat('darken', _this._dofDarken);
  80842. effect.setFloat('edge_blur', _this._edgeBlur);
  80843. effect.setBool('highlights', (_this._highlightsGain !== -1));
  80844. if (_this._scene.activeCamera) {
  80845. effect.setFloat('near', _this._scene.activeCamera.minZ);
  80846. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  80847. }
  80848. };
  80849. };
  80850. // creates a black and white random noise texture, 512x512
  80851. LensRenderingPipeline.prototype._createGrainTexture = function () {
  80852. var size = 512;
  80853. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80854. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  80855. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  80856. var context = this._grainTexture.getContext();
  80857. var rand = function (min, max) {
  80858. return Math.random() * (max - min) + min;
  80859. };
  80860. var value;
  80861. for (var x = 0; x < size; x++) {
  80862. for (var y = 0; y < size; y++) {
  80863. value = Math.floor(rand(0.42, 0.58) * 255);
  80864. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  80865. context.fillRect(x, y, 1, 1);
  80866. }
  80867. }
  80868. this._grainTexture.update(false);
  80869. };
  80870. return LensRenderingPipeline;
  80871. }(BABYLON.PostProcessRenderPipeline));
  80872. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  80873. })(BABYLON || (BABYLON = {}));
  80874. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  80875. var BABYLON;
  80876. (function (BABYLON) {
  80877. var StandardRenderingPipeline = /** @class */ (function (_super) {
  80878. __extends(StandardRenderingPipeline, _super);
  80879. /**
  80880. * @constructor
  80881. * @param {string} name - The rendering pipeline name
  80882. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  80883. * @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)
  80884. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  80885. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  80886. */
  80887. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  80888. if (originalPostProcess === void 0) { originalPostProcess = null; }
  80889. var _this = _super.call(this, scene.getEngine(), name) || this;
  80890. /**
  80891. * Post-process used to down scale an image x4
  80892. */
  80893. _this.downSampleX4PostProcess = null;
  80894. /**
  80895. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  80896. */
  80897. _this.brightPassPostProcess = null;
  80898. /**
  80899. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  80900. */
  80901. _this.blurHPostProcesses = [];
  80902. /**
  80903. * Post-process array storing all the vertical blur post-processes used by the pipeline
  80904. */
  80905. _this.blurVPostProcesses = [];
  80906. /**
  80907. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  80908. */
  80909. _this.textureAdderPostProcess = null;
  80910. /**
  80911. * Post-process used to create volumetric lighting effect
  80912. */
  80913. _this.volumetricLightPostProcess = null;
  80914. /**
  80915. * Post-process used to smooth the previous volumetric light post-process on the X axis
  80916. */
  80917. _this.volumetricLightSmoothXPostProcess = null;
  80918. /**
  80919. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  80920. */
  80921. _this.volumetricLightSmoothYPostProcess = null;
  80922. /**
  80923. * Post-process used to merge the volumetric light effect and the real scene color
  80924. */
  80925. _this.volumetricLightMergePostProces = null;
  80926. /**
  80927. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  80928. */
  80929. _this.volumetricLightFinalPostProcess = null;
  80930. /**
  80931. * Base post-process used to calculate the average luminance of the final image for HDR
  80932. */
  80933. _this.luminancePostProcess = null;
  80934. /**
  80935. * Post-processes used to create down sample post-processes in order to get
  80936. * the average luminance of the final image for HDR
  80937. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  80938. */
  80939. _this.luminanceDownSamplePostProcesses = [];
  80940. /**
  80941. * Post-process used to create a HDR effect (light adaptation)
  80942. */
  80943. _this.hdrPostProcess = null;
  80944. /**
  80945. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  80946. */
  80947. _this.textureAdderFinalPostProcess = null;
  80948. /**
  80949. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  80950. */
  80951. _this.lensFlareFinalPostProcess = null;
  80952. /**
  80953. * Post-process used to merge the final HDR post-process and the real scene color
  80954. */
  80955. _this.hdrFinalPostProcess = null;
  80956. /**
  80957. * Post-process used to create a lens flare effect
  80958. */
  80959. _this.lensFlarePostProcess = null;
  80960. /**
  80961. * Post-process that merges the result of the lens flare post-process and the real scene color
  80962. */
  80963. _this.lensFlareComposePostProcess = null;
  80964. /**
  80965. * Post-process used to create a motion blur effect
  80966. */
  80967. _this.motionBlurPostProcess = null;
  80968. /**
  80969. * Post-process used to create a depth of field effect
  80970. */
  80971. _this.depthOfFieldPostProcess = null;
  80972. /**
  80973. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  80974. */
  80975. _this.fxaaPostProcess = null;
  80976. // Values
  80977. /**
  80978. * Represents the brightness threshold in order to configure the illuminated surfaces
  80979. */
  80980. _this.brightThreshold = 1.0;
  80981. /**
  80982. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  80983. */
  80984. _this.blurWidth = 512.0;
  80985. /**
  80986. * Sets if the blur for highlighted surfaces must be only horizontal
  80987. */
  80988. _this.horizontalBlur = false;
  80989. /**
  80990. * Sets the overall exposure used by the pipeline
  80991. */
  80992. _this.exposure = 1.0;
  80993. /**
  80994. * Texture used typically to simulate "dirty" on camera lens
  80995. */
  80996. _this.lensTexture = null;
  80997. /**
  80998. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  80999. */
  81000. _this.volumetricLightCoefficient = 0.2;
  81001. /**
  81002. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  81003. */
  81004. _this.volumetricLightPower = 4.0;
  81005. /**
  81006. * Used the set the blur intensity to smooth the volumetric lights
  81007. */
  81008. _this.volumetricLightBlurScale = 64.0;
  81009. /**
  81010. * Light (spot or directional) used to generate the volumetric lights rays
  81011. * The source light must have a shadow generate so the pipeline can get its
  81012. * depth map
  81013. */
  81014. _this.sourceLight = null;
  81015. /**
  81016. * For eye adaptation, represents the minimum luminance the eye can see
  81017. */
  81018. _this.hdrMinimumLuminance = 1.0;
  81019. /**
  81020. * For eye adaptation, represents the decrease luminance speed
  81021. */
  81022. _this.hdrDecreaseRate = 0.5;
  81023. /**
  81024. * For eye adaptation, represents the increase luminance speed
  81025. */
  81026. _this.hdrIncreaseRate = 0.5;
  81027. /**
  81028. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  81029. */
  81030. _this.lensColorTexture = null;
  81031. /**
  81032. * The overall strengh for the lens flare effect
  81033. */
  81034. _this.lensFlareStrength = 20.0;
  81035. /**
  81036. * Dispersion coefficient for lens flare ghosts
  81037. */
  81038. _this.lensFlareGhostDispersal = 1.4;
  81039. /**
  81040. * Main lens flare halo width
  81041. */
  81042. _this.lensFlareHaloWidth = 0.7;
  81043. /**
  81044. * Based on the lens distortion effect, defines how much the lens flare result
  81045. * is distorted
  81046. */
  81047. _this.lensFlareDistortionStrength = 16.0;
  81048. /**
  81049. * Lens star texture must be used to simulate rays on the flares and is available
  81050. * in the documentation
  81051. */
  81052. _this.lensStarTexture = null;
  81053. /**
  81054. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  81055. * flare effect by taking account of the dirt texture
  81056. */
  81057. _this.lensFlareDirtTexture = null;
  81058. /**
  81059. * Represents the focal length for the depth of field effect
  81060. */
  81061. _this.depthOfFieldDistance = 10.0;
  81062. /**
  81063. * Represents the blur intensity for the blurred part of the depth of field effect
  81064. */
  81065. _this.depthOfFieldBlurWidth = 64.0;
  81066. /**
  81067. * For motion blur, defines how much the image is blurred by the movement
  81068. */
  81069. _this.motionStrength = 1.0;
  81070. /**
  81071. * List of animations for the pipeline (IAnimatable implementation)
  81072. */
  81073. _this.animations = [];
  81074. _this._currentDepthOfFieldSource = null;
  81075. _this._hdrCurrentLuminance = 1.0;
  81076. // Getters and setters
  81077. _this._bloomEnabled = false;
  81078. _this._depthOfFieldEnabled = false;
  81079. _this._vlsEnabled = false;
  81080. _this._lensFlareEnabled = false;
  81081. _this._hdrEnabled = false;
  81082. _this._motionBlurEnabled = false;
  81083. _this._fxaaEnabled = false;
  81084. _this._motionBlurSamples = 64.0;
  81085. _this._volumetricLightStepsCount = 50.0;
  81086. _this._samples = 1;
  81087. _this._cameras = cameras || [];
  81088. // Initialize
  81089. _this._scene = scene;
  81090. _this._basePostProcess = originalPostProcess;
  81091. _this._ratio = ratio;
  81092. // Misc
  81093. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81094. // Finish
  81095. scene.postProcessRenderPipelineManager.addPipeline(_this);
  81096. _this._buildPipeline();
  81097. return _this;
  81098. }
  81099. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  81100. /**
  81101. * Specifies if the bloom pipeline is enabled
  81102. */
  81103. get: function () {
  81104. return this._bloomEnabled;
  81105. },
  81106. set: function (enabled) {
  81107. if (this._bloomEnabled === enabled) {
  81108. return;
  81109. }
  81110. this._bloomEnabled = enabled;
  81111. this._buildPipeline();
  81112. },
  81113. enumerable: true,
  81114. configurable: true
  81115. });
  81116. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  81117. /**
  81118. * Specifies if the depth of field pipeline is enabed
  81119. */
  81120. get: function () {
  81121. return this._depthOfFieldEnabled;
  81122. },
  81123. set: function (enabled) {
  81124. if (this._depthOfFieldEnabled === enabled) {
  81125. return;
  81126. }
  81127. this._depthOfFieldEnabled = enabled;
  81128. this._buildPipeline();
  81129. },
  81130. enumerable: true,
  81131. configurable: true
  81132. });
  81133. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  81134. /**
  81135. * Specifies if the lens flare pipeline is enabed
  81136. */
  81137. get: function () {
  81138. return this._lensFlareEnabled;
  81139. },
  81140. set: function (enabled) {
  81141. if (this._lensFlareEnabled === enabled) {
  81142. return;
  81143. }
  81144. this._lensFlareEnabled = enabled;
  81145. this._buildPipeline();
  81146. },
  81147. enumerable: true,
  81148. configurable: true
  81149. });
  81150. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  81151. /**
  81152. * Specifies if the HDR pipeline is enabled
  81153. */
  81154. get: function () {
  81155. return this._hdrEnabled;
  81156. },
  81157. set: function (enabled) {
  81158. if (this._hdrEnabled === enabled) {
  81159. return;
  81160. }
  81161. this._hdrEnabled = enabled;
  81162. this._buildPipeline();
  81163. },
  81164. enumerable: true,
  81165. configurable: true
  81166. });
  81167. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  81168. /**
  81169. * Specifies if the volumetric lights scattering effect is enabled
  81170. */
  81171. get: function () {
  81172. return this._vlsEnabled;
  81173. },
  81174. set: function (enabled) {
  81175. if (this._vlsEnabled === enabled) {
  81176. return;
  81177. }
  81178. if (enabled) {
  81179. var geometry = this._scene.enableGeometryBufferRenderer();
  81180. if (!geometry) {
  81181. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  81182. return;
  81183. }
  81184. }
  81185. this._vlsEnabled = enabled;
  81186. this._buildPipeline();
  81187. },
  81188. enumerable: true,
  81189. configurable: true
  81190. });
  81191. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  81192. /**
  81193. * Specifies if the motion blur effect is enabled
  81194. */
  81195. get: function () {
  81196. return this._motionBlurEnabled;
  81197. },
  81198. set: function (enabled) {
  81199. if (this._motionBlurEnabled === enabled) {
  81200. return;
  81201. }
  81202. this._motionBlurEnabled = enabled;
  81203. this._buildPipeline();
  81204. },
  81205. enumerable: true,
  81206. configurable: true
  81207. });
  81208. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  81209. /**
  81210. * Specifies if anti-aliasing is enabled
  81211. */
  81212. get: function () {
  81213. return this._fxaaEnabled;
  81214. },
  81215. set: function (enabled) {
  81216. if (this._fxaaEnabled === enabled) {
  81217. return;
  81218. }
  81219. this._fxaaEnabled = enabled;
  81220. this._buildPipeline();
  81221. },
  81222. enumerable: true,
  81223. configurable: true
  81224. });
  81225. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  81226. /**
  81227. * Specifies the number of steps used to calculate the volumetric lights
  81228. * Typically in interval [50, 200]
  81229. */
  81230. get: function () {
  81231. return this._volumetricLightStepsCount;
  81232. },
  81233. set: function (count) {
  81234. if (this.volumetricLightPostProcess) {
  81235. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  81236. }
  81237. this._volumetricLightStepsCount = count;
  81238. },
  81239. enumerable: true,
  81240. configurable: true
  81241. });
  81242. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  81243. /**
  81244. * Specifies the number of samples used for the motion blur effect
  81245. * Typically in interval [16, 64]
  81246. */
  81247. get: function () {
  81248. return this._motionBlurSamples;
  81249. },
  81250. set: function (samples) {
  81251. if (this.motionBlurPostProcess) {
  81252. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  81253. }
  81254. this._motionBlurSamples = samples;
  81255. },
  81256. enumerable: true,
  81257. configurable: true
  81258. });
  81259. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  81260. /**
  81261. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  81262. */
  81263. get: function () {
  81264. return this._samples;
  81265. },
  81266. set: function (sampleCount) {
  81267. if (this._samples === sampleCount) {
  81268. return;
  81269. }
  81270. this._samples = sampleCount;
  81271. this._buildPipeline();
  81272. },
  81273. enumerable: true,
  81274. configurable: true
  81275. });
  81276. StandardRenderingPipeline.prototype._buildPipeline = function () {
  81277. var _this = this;
  81278. var ratio = this._ratio;
  81279. var scene = this._scene;
  81280. this._disposePostProcesses();
  81281. this._reset();
  81282. // Create pass post-process
  81283. if (!this._basePostProcess) {
  81284. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  81285. this.originalPostProcess.onApply = function (effect) {
  81286. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  81287. };
  81288. }
  81289. else {
  81290. this.originalPostProcess = this._basePostProcess;
  81291. }
  81292. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  81293. this._currentDepthOfFieldSource = this.originalPostProcess;
  81294. if (this._bloomEnabled) {
  81295. // Create down sample X4 post-process
  81296. this._createDownSampleX4PostProcess(scene, ratio / 2);
  81297. // Create bright pass post-process
  81298. this._createBrightPassPostProcess(scene, ratio / 2);
  81299. // Create gaussian blur post-processes (down sampling blurs)
  81300. this._createBlurPostProcesses(scene, ratio / 4, 1);
  81301. // Create texture adder post-process
  81302. this._createTextureAdderPostProcess(scene, ratio);
  81303. // Create depth-of-field source post-process
  81304. 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);
  81305. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  81306. }
  81307. if (this._vlsEnabled) {
  81308. // Create volumetric light
  81309. this._createVolumetricLightPostProcess(scene, ratio);
  81310. // Create volumetric light final post-process
  81311. 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);
  81312. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  81313. }
  81314. if (this._lensFlareEnabled) {
  81315. // Create lens flare post-process
  81316. this._createLensFlarePostProcess(scene, ratio);
  81317. // Create depth-of-field source post-process post lens-flare and disable it now
  81318. 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);
  81319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  81320. }
  81321. if (this._hdrEnabled) {
  81322. // Create luminance
  81323. this._createLuminancePostProcesses(scene, this._floatTextureType);
  81324. // Create HDR
  81325. this._createHdrPostProcess(scene, ratio);
  81326. // Create depth-of-field source post-process post hdr and disable it now
  81327. 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);
  81328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  81329. }
  81330. if (this._depthOfFieldEnabled) {
  81331. // Create gaussian blur used by depth-of-field
  81332. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  81333. // Create depth-of-field post-process
  81334. this._createDepthOfFieldPostProcess(scene, ratio);
  81335. }
  81336. if (this._motionBlurEnabled) {
  81337. // Create motion blur post-process
  81338. this._createMotionBlurPostProcess(scene, ratio);
  81339. }
  81340. if (this._fxaaEnabled) {
  81341. // Create fxaa post-process
  81342. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  81344. }
  81345. if (this._cameras !== null) {
  81346. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  81347. }
  81348. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  81349. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  81350. }
  81351. };
  81352. // Down Sample X4 Post-Processs
  81353. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  81354. var _this = this;
  81355. var downSampleX4Offsets = new Array(32);
  81356. 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);
  81357. this.downSampleX4PostProcess.onApply = function (effect) {
  81358. var id = 0;
  81359. var width = _this.downSampleX4PostProcess.width;
  81360. var height = _this.downSampleX4PostProcess.height;
  81361. for (var i = -2; i < 2; i++) {
  81362. for (var j = -2; j < 2; j++) {
  81363. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  81364. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  81365. id += 2;
  81366. }
  81367. }
  81368. effect.setArray2("dsOffsets", downSampleX4Offsets);
  81369. };
  81370. // Add to pipeline
  81371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  81372. };
  81373. // Brightpass Post-Process
  81374. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  81375. var _this = this;
  81376. var brightOffsets = new Array(8);
  81377. 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);
  81378. this.brightPassPostProcess.onApply = function (effect) {
  81379. var sU = (1.0 / _this.brightPassPostProcess.width);
  81380. var sV = (1.0 / _this.brightPassPostProcess.height);
  81381. brightOffsets[0] = -0.5 * sU;
  81382. brightOffsets[1] = 0.5 * sV;
  81383. brightOffsets[2] = 0.5 * sU;
  81384. brightOffsets[3] = 0.5 * sV;
  81385. brightOffsets[4] = -0.5 * sU;
  81386. brightOffsets[5] = -0.5 * sV;
  81387. brightOffsets[6] = 0.5 * sU;
  81388. brightOffsets[7] = -0.5 * sV;
  81389. effect.setArray2("dsOffsets", brightOffsets);
  81390. effect.setFloat("brightThreshold", _this.brightThreshold);
  81391. };
  81392. // Add to pipeline
  81393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  81394. };
  81395. // Create blur H&V post-processes
  81396. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  81397. var _this = this;
  81398. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  81399. var engine = scene.getEngine();
  81400. 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);
  81401. 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);
  81402. blurX.onActivateObservable.add(function () {
  81403. var dw = blurX.width / engine.getRenderWidth();
  81404. blurX.kernel = _this[blurWidthKey] * dw;
  81405. });
  81406. blurY.onActivateObservable.add(function () {
  81407. var dw = blurY.height / engine.getRenderHeight();
  81408. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  81409. });
  81410. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  81411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  81412. this.blurHPostProcesses.push(blurX);
  81413. this.blurVPostProcesses.push(blurY);
  81414. };
  81415. // Create texture adder post-process
  81416. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  81417. var _this = this;
  81418. 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);
  81419. this.textureAdderPostProcess.onApply = function (effect) {
  81420. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  81421. effect.setTexture("lensSampler", _this.lensTexture);
  81422. effect.setFloat("exposure", _this.exposure);
  81423. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  81424. };
  81425. // Add to pipeline
  81426. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  81427. };
  81428. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  81429. var _this = this;
  81430. var geometryRenderer = scene.enableGeometryBufferRenderer();
  81431. geometryRenderer.enablePosition = true;
  81432. var geometry = geometryRenderer.getGBuffer();
  81433. // Base post-process
  81434. 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));
  81435. var depthValues = BABYLON.Vector2.Zero();
  81436. this.volumetricLightPostProcess.onApply = function (effect) {
  81437. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  81438. var generator = _this.sourceLight.getShadowGenerator();
  81439. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  81440. effect.setTexture("positionSampler", geometry.textures[2]);
  81441. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  81442. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  81443. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  81444. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  81445. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  81446. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  81447. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  81448. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  81449. effect.setVector2("depthValues", depthValues);
  81450. }
  81451. };
  81452. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  81453. // Smooth
  81454. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  81455. // Merge
  81456. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  81457. this.volumetricLightMergePostProces.onApply = function (effect) {
  81458. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  81459. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  81460. };
  81461. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  81462. };
  81463. // Create luminance
  81464. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  81465. var _this = this;
  81466. // Create luminance
  81467. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  81468. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  81469. var offsets = [];
  81470. this.luminancePostProcess.onApply = function (effect) {
  81471. var sU = (1.0 / _this.luminancePostProcess.width);
  81472. var sV = (1.0 / _this.luminancePostProcess.height);
  81473. offsets[0] = -0.5 * sU;
  81474. offsets[1] = 0.5 * sV;
  81475. offsets[2] = 0.5 * sU;
  81476. offsets[3] = 0.5 * sV;
  81477. offsets[4] = -0.5 * sU;
  81478. offsets[5] = -0.5 * sV;
  81479. offsets[6] = 0.5 * sU;
  81480. offsets[7] = -0.5 * sV;
  81481. effect.setArray2("lumOffsets", offsets);
  81482. };
  81483. // Add to pipeline
  81484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  81485. // Create down sample luminance
  81486. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  81487. var size = Math.pow(3, i);
  81488. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  81489. if (i === 0) {
  81490. defines += "#define FINAL_DOWN_SAMPLER";
  81491. }
  81492. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  81493. this.luminanceDownSamplePostProcesses.push(postProcess);
  81494. }
  81495. // Create callbacks and add effects
  81496. var lastLuminance = this.luminancePostProcess;
  81497. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  81498. var downSampleOffsets = new Array(18);
  81499. pp.onApply = function (effect) {
  81500. if (!lastLuminance) {
  81501. return;
  81502. }
  81503. var id = 0;
  81504. for (var x = -1; x < 2; x++) {
  81505. for (var y = -1; y < 2; y++) {
  81506. downSampleOffsets[id] = x / lastLuminance.width;
  81507. downSampleOffsets[id + 1] = y / lastLuminance.height;
  81508. id += 2;
  81509. }
  81510. }
  81511. effect.setArray2("dsOffsets", downSampleOffsets);
  81512. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  81513. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81514. lastLuminance = _this.luminancePostProcess;
  81515. }
  81516. else {
  81517. lastLuminance = pp;
  81518. }
  81519. };
  81520. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  81521. pp.onAfterRender = function (effect) {
  81522. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  81523. 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);
  81524. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  81525. };
  81526. }
  81527. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  81528. });
  81529. };
  81530. // Create HDR post-process
  81531. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  81532. var _this = this;
  81533. 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);
  81534. var outputLiminance = 1;
  81535. var time = 0;
  81536. var lastTime = 0;
  81537. this.hdrPostProcess.onApply = function (effect) {
  81538. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  81539. time += scene.getEngine().getDeltaTime();
  81540. if (outputLiminance < 0) {
  81541. outputLiminance = _this._hdrCurrentLuminance;
  81542. }
  81543. else {
  81544. var dt = (lastTime - time) / 1000.0;
  81545. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  81546. outputLiminance += _this.hdrDecreaseRate * dt;
  81547. }
  81548. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  81549. outputLiminance -= _this.hdrIncreaseRate * dt;
  81550. }
  81551. else {
  81552. outputLiminance = _this._hdrCurrentLuminance;
  81553. }
  81554. }
  81555. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  81556. effect.setFloat("averageLuminance", outputLiminance);
  81557. lastTime = time;
  81558. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  81559. };
  81560. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  81561. };
  81562. // Create lens flare post-process
  81563. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  81564. var _this = this;
  81565. 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);
  81566. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  81567. this._createBlurPostProcesses(scene, ratio / 4, 2);
  81568. 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);
  81569. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  81570. var resolution = new BABYLON.Vector2(0, 0);
  81571. // Lens flare
  81572. this.lensFlarePostProcess.onApply = function (effect) {
  81573. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  81574. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  81575. effect.setFloat("strength", _this.lensFlareStrength);
  81576. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  81577. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  81578. // Shift
  81579. resolution.x = _this.lensFlarePostProcess.width;
  81580. resolution.y = _this.lensFlarePostProcess.height;
  81581. effect.setVector2("resolution", resolution);
  81582. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  81583. };
  81584. // Compose
  81585. 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);
  81586. 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);
  81587. this.lensFlareComposePostProcess.onApply = function (effect) {
  81588. if (!_this._scene.activeCamera) {
  81589. return;
  81590. }
  81591. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  81592. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  81593. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  81594. // Lens start rotation matrix
  81595. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  81596. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  81597. 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));
  81598. camRot *= 4.0;
  81599. 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);
  81600. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  81601. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  81602. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  81603. };
  81604. };
  81605. // Create depth-of-field post-process
  81606. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  81607. var _this = this;
  81608. 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);
  81609. this.depthOfFieldPostProcess.onApply = function (effect) {
  81610. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  81611. effect.setTexture("depthSampler", _this._getDepthTexture());
  81612. effect.setFloat("distance", _this.depthOfFieldDistance);
  81613. };
  81614. // Add to pipeline
  81615. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  81616. };
  81617. // Create motion blur post-process
  81618. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  81619. var _this = this;
  81620. 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);
  81621. var motionScale = 0;
  81622. var prevViewProjection = BABYLON.Matrix.Identity();
  81623. var invViewProjection = BABYLON.Matrix.Identity();
  81624. var viewProjection = BABYLON.Matrix.Identity();
  81625. var screenSize = BABYLON.Vector2.Zero();
  81626. this.motionBlurPostProcess.onApply = function (effect) {
  81627. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  81628. viewProjection.invertToRef(invViewProjection);
  81629. effect.setMatrix("inverseViewProjection", invViewProjection);
  81630. effect.setMatrix("prevViewProjection", prevViewProjection);
  81631. prevViewProjection = viewProjection;
  81632. screenSize.x = _this.motionBlurPostProcess.width;
  81633. screenSize.y = _this.motionBlurPostProcess.height;
  81634. effect.setVector2("screenSize", screenSize);
  81635. motionScale = scene.getEngine().getFps() / 60.0;
  81636. effect.setFloat("motionScale", motionScale);
  81637. effect.setFloat("motionStrength", _this.motionStrength);
  81638. effect.setTexture("depthSampler", _this._getDepthTexture());
  81639. };
  81640. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  81641. };
  81642. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  81643. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  81644. var renderer = this._scene.enableGeometryBufferRenderer();
  81645. return renderer.getGBuffer().textures[0];
  81646. }
  81647. return this._scene.enableDepthRenderer().getDepthMap();
  81648. };
  81649. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  81650. for (var i = 0; i < this._cameras.length; i++) {
  81651. var camera = this._cameras[i];
  81652. if (this.originalPostProcess) {
  81653. this.originalPostProcess.dispose(camera);
  81654. }
  81655. if (this.downSampleX4PostProcess) {
  81656. this.downSampleX4PostProcess.dispose(camera);
  81657. }
  81658. if (this.brightPassPostProcess) {
  81659. this.brightPassPostProcess.dispose(camera);
  81660. }
  81661. if (this.textureAdderPostProcess) {
  81662. this.textureAdderPostProcess.dispose(camera);
  81663. }
  81664. if (this.textureAdderFinalPostProcess) {
  81665. this.textureAdderFinalPostProcess.dispose(camera);
  81666. }
  81667. if (this.volumetricLightPostProcess) {
  81668. this.volumetricLightPostProcess.dispose(camera);
  81669. }
  81670. if (this.volumetricLightSmoothXPostProcess) {
  81671. this.volumetricLightSmoothXPostProcess.dispose(camera);
  81672. }
  81673. if (this.volumetricLightSmoothYPostProcess) {
  81674. this.volumetricLightSmoothYPostProcess.dispose(camera);
  81675. }
  81676. if (this.volumetricLightMergePostProces) {
  81677. this.volumetricLightMergePostProces.dispose(camera);
  81678. }
  81679. if (this.volumetricLightFinalPostProcess) {
  81680. this.volumetricLightFinalPostProcess.dispose(camera);
  81681. }
  81682. if (this.lensFlarePostProcess) {
  81683. this.lensFlarePostProcess.dispose(camera);
  81684. }
  81685. if (this.lensFlareComposePostProcess) {
  81686. this.lensFlareComposePostProcess.dispose(camera);
  81687. }
  81688. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  81689. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  81690. }
  81691. if (this.luminancePostProcess) {
  81692. this.luminancePostProcess.dispose(camera);
  81693. }
  81694. if (this.hdrPostProcess) {
  81695. this.hdrPostProcess.dispose(camera);
  81696. }
  81697. if (this.hdrFinalPostProcess) {
  81698. this.hdrFinalPostProcess.dispose(camera);
  81699. }
  81700. if (this.depthOfFieldPostProcess) {
  81701. this.depthOfFieldPostProcess.dispose(camera);
  81702. }
  81703. if (this.motionBlurPostProcess) {
  81704. this.motionBlurPostProcess.dispose(camera);
  81705. }
  81706. if (this.fxaaPostProcess) {
  81707. this.fxaaPostProcess.dispose(camera);
  81708. }
  81709. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  81710. this.blurHPostProcesses[j].dispose(camera);
  81711. }
  81712. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  81713. this.blurVPostProcesses[j].dispose(camera);
  81714. }
  81715. }
  81716. this.originalPostProcess = null;
  81717. this.downSampleX4PostProcess = null;
  81718. this.brightPassPostProcess = null;
  81719. this.textureAdderPostProcess = null;
  81720. this.textureAdderFinalPostProcess = null;
  81721. this.volumetricLightPostProcess = null;
  81722. this.volumetricLightSmoothXPostProcess = null;
  81723. this.volumetricLightSmoothYPostProcess = null;
  81724. this.volumetricLightMergePostProces = null;
  81725. this.volumetricLightFinalPostProcess = null;
  81726. this.lensFlarePostProcess = null;
  81727. this.lensFlareComposePostProcess = null;
  81728. this.luminancePostProcess = null;
  81729. this.hdrPostProcess = null;
  81730. this.hdrFinalPostProcess = null;
  81731. this.depthOfFieldPostProcess = null;
  81732. this.motionBlurPostProcess = null;
  81733. this.fxaaPostProcess = null;
  81734. this.luminanceDownSamplePostProcesses = [];
  81735. this.blurHPostProcesses = [];
  81736. this.blurVPostProcesses = [];
  81737. };
  81738. /**
  81739. * Dispose of the pipeline and stop all post processes
  81740. */
  81741. StandardRenderingPipeline.prototype.dispose = function () {
  81742. this._disposePostProcesses();
  81743. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  81744. _super.prototype.dispose.call(this);
  81745. };
  81746. /**
  81747. * Serialize the rendering pipeline (Used when exporting)
  81748. * @returns the serialized object
  81749. */
  81750. StandardRenderingPipeline.prototype.serialize = function () {
  81751. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81752. if (this.sourceLight) {
  81753. serializationObject.sourceLightId = this.sourceLight.id;
  81754. }
  81755. serializationObject.customType = "StandardRenderingPipeline";
  81756. return serializationObject;
  81757. };
  81758. /**
  81759. * Parse the serialized pipeline
  81760. * @param source Source pipeline.
  81761. * @param scene The scene to load the pipeline to.
  81762. * @param rootUrl The URL of the serialized pipeline.
  81763. * @returns An instantiated pipeline from the serialized object.
  81764. */
  81765. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  81766. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  81767. if (source.sourceLightId) {
  81768. p.sourceLight = scene.getLightByID(source.sourceLightId);
  81769. }
  81770. return p;
  81771. };
  81772. // Luminance steps
  81773. StandardRenderingPipeline.LuminanceSteps = 6;
  81774. __decorate([
  81775. BABYLON.serialize()
  81776. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  81777. __decorate([
  81778. BABYLON.serialize()
  81779. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  81780. __decorate([
  81781. BABYLON.serialize()
  81782. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  81783. __decorate([
  81784. BABYLON.serialize()
  81785. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  81786. __decorate([
  81787. BABYLON.serializeAsTexture("lensTexture")
  81788. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  81789. __decorate([
  81790. BABYLON.serialize()
  81791. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  81792. __decorate([
  81793. BABYLON.serialize()
  81794. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  81795. __decorate([
  81796. BABYLON.serialize()
  81797. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  81798. __decorate([
  81799. BABYLON.serialize()
  81800. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  81801. __decorate([
  81802. BABYLON.serialize()
  81803. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  81804. __decorate([
  81805. BABYLON.serialize()
  81806. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  81807. __decorate([
  81808. BABYLON.serializeAsTexture("lensColorTexture")
  81809. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  81810. __decorate([
  81811. BABYLON.serialize()
  81812. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  81813. __decorate([
  81814. BABYLON.serialize()
  81815. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  81816. __decorate([
  81817. BABYLON.serialize()
  81818. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  81819. __decorate([
  81820. BABYLON.serialize()
  81821. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  81822. __decorate([
  81823. BABYLON.serializeAsTexture("lensStarTexture")
  81824. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  81825. __decorate([
  81826. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  81827. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  81828. __decorate([
  81829. BABYLON.serialize()
  81830. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  81831. __decorate([
  81832. BABYLON.serialize()
  81833. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  81834. __decorate([
  81835. BABYLON.serialize()
  81836. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  81837. __decorate([
  81838. BABYLON.serialize()
  81839. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  81840. __decorate([
  81841. BABYLON.serialize()
  81842. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  81843. __decorate([
  81844. BABYLON.serialize()
  81845. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  81846. __decorate([
  81847. BABYLON.serialize()
  81848. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  81849. __decorate([
  81850. BABYLON.serialize()
  81851. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  81852. __decorate([
  81853. BABYLON.serialize()
  81854. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  81855. __decorate([
  81856. BABYLON.serialize()
  81857. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  81858. __decorate([
  81859. BABYLON.serialize()
  81860. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  81861. __decorate([
  81862. BABYLON.serialize()
  81863. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  81864. __decorate([
  81865. BABYLON.serialize()
  81866. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  81867. __decorate([
  81868. BABYLON.serialize()
  81869. ], StandardRenderingPipeline.prototype, "samples", null);
  81870. return StandardRenderingPipeline;
  81871. }(BABYLON.PostProcessRenderPipeline));
  81872. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  81873. })(BABYLON || (BABYLON = {}));
  81874. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  81875. var BABYLON;
  81876. (function (BABYLON) {
  81877. var FxaaPostProcess = /** @class */ (function (_super) {
  81878. __extends(FxaaPostProcess, _super);
  81879. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  81880. if (camera === void 0) { camera = null; }
  81881. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81882. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  81883. var defines = _this._getDefines();
  81884. _this.updateEffect(defines);
  81885. _this.onApplyObservable.add(function (effect) {
  81886. var texelSize = _this.texelSize;
  81887. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  81888. });
  81889. return _this;
  81890. }
  81891. FxaaPostProcess.prototype._getDefines = function () {
  81892. var engine = this.getEngine();
  81893. if (!engine) {
  81894. return null;
  81895. }
  81896. var glInfo = engine.getGlInfo();
  81897. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  81898. return "#define MALI 1\n";
  81899. }
  81900. return null;
  81901. };
  81902. return FxaaPostProcess;
  81903. }(BABYLON.PostProcess));
  81904. BABYLON.FxaaPostProcess = FxaaPostProcess;
  81905. })(BABYLON || (BABYLON = {}));
  81906. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  81907. var BABYLON;
  81908. (function (BABYLON) {
  81909. /**
  81910. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  81911. */
  81912. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  81913. __extends(ChromaticAberrationPostProcess, _super);
  81914. /**
  81915. * Creates a new instance ChromaticAberrationPostProcess
  81916. * @param name The name of the effect.
  81917. * @param screenWidth The width of the screen to apply the effect on.
  81918. * @param screenHeight The height of the screen to apply the effect on.
  81919. * @param options The required width/height ratio to downsize to before computing the render pass.
  81920. * @param camera The camera to apply the render pass to.
  81921. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81922. * @param engine The engine which the post process will be applied. (default: current engine)
  81923. * @param reusable If the post process can be reused on the same frame. (default: false)
  81924. * @param textureType Type of textures used when performing the post process. (default: 0)
  81925. * @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)
  81926. */
  81927. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81928. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81929. if (blockCompilation === void 0) { blockCompilation = false; }
  81930. 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;
  81931. /**
  81932. * The amount of seperation of rgb channels (default: 30)
  81933. */
  81934. _this.aberrationAmount = 30;
  81935. /**
  81936. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  81937. */
  81938. _this.radialIntensity = 0;
  81939. /**
  81940. * 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))
  81941. */
  81942. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  81943. /**
  81944. * 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))
  81945. */
  81946. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  81947. _this.onApplyObservable.add(function (effect) {
  81948. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  81949. effect.setFloat('screen_width', screenWidth);
  81950. effect.setFloat('screen_height', screenHeight);
  81951. effect.setFloat('radialIntensity', _this.radialIntensity);
  81952. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  81953. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  81954. });
  81955. return _this;
  81956. }
  81957. return ChromaticAberrationPostProcess;
  81958. }(BABYLON.PostProcess));
  81959. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  81960. })(BABYLON || (BABYLON = {}));
  81961. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  81962. var BABYLON;
  81963. (function (BABYLON) {
  81964. /**
  81965. * The GrainPostProcess adds noise to the image at mid luminance levels
  81966. */
  81967. var GrainPostProcess = /** @class */ (function (_super) {
  81968. __extends(GrainPostProcess, _super);
  81969. /**
  81970. * Creates a new instance of @see GrainPostProcess
  81971. * @param name The name of the effect.
  81972. * @param options The required width/height ratio to downsize to before computing the render pass.
  81973. * @param camera The camera to apply the render pass to.
  81974. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81975. * @param engine The engine which the post process will be applied. (default: current engine)
  81976. * @param reusable If the post process can be reused on the same frame. (default: false)
  81977. * @param textureType Type of textures used when performing the post process. (default: 0)
  81978. * @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)
  81979. */
  81980. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  81981. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81982. if (blockCompilation === void 0) { blockCompilation = false; }
  81983. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  81984. /**
  81985. * The intensity of the grain added (default: 30)
  81986. */
  81987. _this.intensity = 30;
  81988. /**
  81989. * If the grain should be randomized on every frame
  81990. */
  81991. _this.animated = false;
  81992. _this.onApplyObservable.add(function (effect) {
  81993. effect.setFloat('intensity', _this.intensity);
  81994. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  81995. });
  81996. return _this;
  81997. }
  81998. return GrainPostProcess;
  81999. }(BABYLON.PostProcess));
  82000. BABYLON.GrainPostProcess = GrainPostProcess;
  82001. })(BABYLON || (BABYLON = {}));
  82002. //# sourceMappingURL=babylon.grainPostProcess.js.map
  82003. var BABYLON;
  82004. (function (BABYLON) {
  82005. /**
  82006. * The SharpenPostProcess applies a sharpen kernel to every pixel
  82007. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  82008. */
  82009. var SharpenPostProcess = /** @class */ (function (_super) {
  82010. __extends(SharpenPostProcess, _super);
  82011. /**
  82012. * Creates a new instance ConvolutionPostProcess
  82013. * @param name The name of the effect.
  82014. * @param options The required width/height ratio to downsize to before computing the render pass.
  82015. * @param camera The camera to apply the render pass to.
  82016. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82017. * @param engine The engine which the post process will be applied. (default: current engine)
  82018. * @param reusable If the post process can be reused on the same frame. (default: false)
  82019. * @param textureType Type of textures used when performing the post process. (default: 0)
  82020. * @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)
  82021. */
  82022. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82023. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82024. if (blockCompilation === void 0) { blockCompilation = false; }
  82025. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82026. /**
  82027. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  82028. */
  82029. _this.colorAmount = 1.0;
  82030. /**
  82031. * How much sharpness should be applied (default: 0.3)
  82032. */
  82033. _this.edgeAmount = 0.3;
  82034. _this.onApply = function (effect) {
  82035. effect.setFloat2("screenSize", _this.width, _this.height);
  82036. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  82037. };
  82038. return _this;
  82039. }
  82040. return SharpenPostProcess;
  82041. }(BABYLON.PostProcess));
  82042. BABYLON.SharpenPostProcess = SharpenPostProcess;
  82043. })(BABYLON || (BABYLON = {}));
  82044. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  82045. var BABYLON;
  82046. (function (BABYLON) {
  82047. /**
  82048. * The Blur Post Process which blurs an image based on a kernel and direction.
  82049. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  82050. */
  82051. var BlurPostProcess = /** @class */ (function (_super) {
  82052. __extends(BlurPostProcess, _super);
  82053. /**
  82054. * Creates a new instance BlurPostProcess
  82055. * @param name The name of the effect.
  82056. * @param direction The direction in which to blur the image.
  82057. * @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.
  82058. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  82059. * @param camera The camera to apply the render pass to.
  82060. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82061. * @param engine The engine which the post process will be applied. (default: current engine)
  82062. * @param reusable If the post process can be reused on the same frame. (default: false)
  82063. * @param textureType Type of textures used when performing the post process. (default: 0)
  82064. * @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)
  82065. */
  82066. function BlurPostProcess(name,
  82067. /** The direction in which to blur the image. */
  82068. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  82069. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82070. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82071. if (defines === void 0) { defines = ""; }
  82072. if (blockCompilation === void 0) { blockCompilation = false; }
  82073. 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;
  82074. _this.direction = direction;
  82075. _this.blockCompilation = blockCompilation;
  82076. _this._packedFloat = false;
  82077. _this._staticDefines = "";
  82078. _this._staticDefines = defines;
  82079. _this.onApplyObservable.add(function (effect) {
  82080. if (_this._outputTexture) {
  82081. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  82082. }
  82083. else {
  82084. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  82085. }
  82086. });
  82087. _this.kernel = kernel;
  82088. return _this;
  82089. }
  82090. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  82091. /**
  82092. * Gets the length in pixels of the blur sample region
  82093. */
  82094. get: function () {
  82095. return this._idealKernel;
  82096. },
  82097. /**
  82098. * Sets the length in pixels of the blur sample region
  82099. */
  82100. set: function (v) {
  82101. if (this._idealKernel === v) {
  82102. return;
  82103. }
  82104. v = Math.max(v, 1);
  82105. this._idealKernel = v;
  82106. this._kernel = this._nearestBestKernel(v);
  82107. if (!this.blockCompilation) {
  82108. this._updateParameters();
  82109. }
  82110. },
  82111. enumerable: true,
  82112. configurable: true
  82113. });
  82114. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  82115. /**
  82116. * Gets wether or not the blur is unpacking/repacking floats
  82117. */
  82118. get: function () {
  82119. return this._packedFloat;
  82120. },
  82121. /**
  82122. * Sets wether or not the blur needs to unpack/repack floats
  82123. */
  82124. set: function (v) {
  82125. if (this._packedFloat === v) {
  82126. return;
  82127. }
  82128. this._packedFloat = v;
  82129. if (!this.blockCompilation) {
  82130. this._updateParameters();
  82131. }
  82132. },
  82133. enumerable: true,
  82134. configurable: true
  82135. });
  82136. /**
  82137. * Updates the effect with the current post process compile time values and recompiles the shader.
  82138. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82139. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82140. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82141. * @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
  82142. * @param onCompiled Called when the shader has been compiled.
  82143. * @param onError Called if there is an error when compiling a shader.
  82144. */
  82145. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82146. if (defines === void 0) { defines = null; }
  82147. if (uniforms === void 0) { uniforms = null; }
  82148. if (samplers === void 0) { samplers = null; }
  82149. this._updateParameters(onCompiled, onError);
  82150. };
  82151. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  82152. // Generate sampling offsets and weights
  82153. var N = this._kernel;
  82154. var centerIndex = (N - 1) / 2;
  82155. // Generate Gaussian sampling weights over kernel
  82156. var offsets = [];
  82157. var weights = [];
  82158. var totalWeight = 0;
  82159. for (var i = 0; i < N; i++) {
  82160. var u = i / (N - 1);
  82161. var w = this._gaussianWeight(u * 2.0 - 1);
  82162. offsets[i] = (i - centerIndex);
  82163. weights[i] = w;
  82164. totalWeight += w;
  82165. }
  82166. // Normalize weights
  82167. for (var i = 0; i < weights.length; i++) {
  82168. weights[i] /= totalWeight;
  82169. }
  82170. // Optimize: combine samples to take advantage of hardware linear sampling
  82171. // Walk from left to center, combining pairs (symmetrically)
  82172. var linearSamplingWeights = [];
  82173. var linearSamplingOffsets = [];
  82174. var linearSamplingMap = [];
  82175. for (var i = 0; i <= centerIndex; i += 2) {
  82176. var j = Math.min(i + 1, Math.floor(centerIndex));
  82177. var singleCenterSample = i === j;
  82178. if (singleCenterSample) {
  82179. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82180. }
  82181. else {
  82182. var sharedCell = j === centerIndex;
  82183. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  82184. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  82185. if (offsetLinear === 0) {
  82186. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  82187. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  82188. }
  82189. else {
  82190. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  82191. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  82192. }
  82193. }
  82194. }
  82195. for (var i = 0; i < linearSamplingMap.length; i++) {
  82196. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  82197. linearSamplingWeights[i] = linearSamplingMap[i].w;
  82198. }
  82199. // Replace with optimized
  82200. offsets = linearSamplingOffsets;
  82201. weights = linearSamplingWeights;
  82202. // Generate shaders
  82203. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  82204. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  82205. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  82206. var defines = "";
  82207. defines += this._staticDefines;
  82208. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  82209. if (this._staticDefines.indexOf("DOF") != -1) {
  82210. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  82211. varyingCount--;
  82212. }
  82213. for (var i = 0; i < varyingCount; i++) {
  82214. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  82215. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  82216. }
  82217. var depCount = 0;
  82218. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  82219. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  82220. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  82221. depCount++;
  82222. }
  82223. if (this.packedFloat) {
  82224. defines += "#define PACKEDFLOAT 1";
  82225. }
  82226. this.blockCompilation = false;
  82227. _super.prototype.updateEffect.call(this, defines, null, null, {
  82228. varyingCount: varyingCount,
  82229. depCount: depCount
  82230. }, onCompiled, onError);
  82231. };
  82232. /**
  82233. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  82234. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  82235. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  82236. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  82237. * The gaps between physical kernels are compensated for in the weighting of the samples
  82238. * @param idealKernel Ideal blur kernel.
  82239. * @return Nearest best kernel.
  82240. */
  82241. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  82242. var v = Math.round(idealKernel);
  82243. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  82244. var k = _a[_i];
  82245. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  82246. return Math.max(k, 3);
  82247. }
  82248. }
  82249. return Math.max(v, 3);
  82250. };
  82251. /**
  82252. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  82253. * @param x The point on the Gaussian distribution to sample.
  82254. * @return the value of the Gaussian function at x.
  82255. */
  82256. BlurPostProcess.prototype._gaussianWeight = function (x) {
  82257. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  82258. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  82259. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  82260. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  82261. // truncated at around 1.3% of peak strength.
  82262. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  82263. var sigma = (1 / 3);
  82264. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  82265. var exponent = -((x * x) / (2.0 * sigma * sigma));
  82266. var weight = (1.0 / denominator) * Math.exp(exponent);
  82267. return weight;
  82268. };
  82269. /**
  82270. * Generates a string that can be used as a floating point number in GLSL.
  82271. * @param x Value to print.
  82272. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  82273. * @return GLSL float string.
  82274. */
  82275. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  82276. if (decimalFigures === void 0) { decimalFigures = 8; }
  82277. return x.toFixed(decimalFigures).replace(/0+$/, '');
  82278. };
  82279. return BlurPostProcess;
  82280. }(BABYLON.PostProcess));
  82281. BABYLON.BlurPostProcess = BlurPostProcess;
  82282. })(BABYLON || (BABYLON = {}));
  82283. //# sourceMappingURL=babylon.blurPostProcess.js.map
  82284. var BABYLON;
  82285. (function (BABYLON) {
  82286. /**
  82287. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  82288. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  82289. * based on samples that have a large difference in distance than the center pixel.
  82290. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82291. */
  82292. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  82293. __extends(DepthOfFieldBlurPostProcess, _super);
  82294. /**
  82295. * Creates a new instance CircleOfConfusionPostProcess
  82296. * @param name The name of the effect.
  82297. * @param scene The scene the effect belongs to.
  82298. * @param direction The direction the blur should be applied.
  82299. * @param kernel The size of the kernel used to blur.
  82300. * @param options The required width/height ratio to downsize to before computing the render pass.
  82301. * @param camera The camera to apply the render pass to.
  82302. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  82303. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  82304. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82305. * @param engine The engine which the post process will be applied. (default: current engine)
  82306. * @param reusable If the post process can be reused on the same frame. (default: false)
  82307. * @param textureType Type of textures used when performing the post process. (default: 0)
  82308. * @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)
  82309. */
  82310. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  82311. if (imageToBlur === void 0) { imageToBlur = null; }
  82312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82313. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82314. if (blockCompilation === void 0) { blockCompilation = false; }
  82315. 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;
  82316. _this.direction = direction;
  82317. _this.onApplyObservable.add(function (effect) {
  82318. if (imageToBlur != null) {
  82319. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  82320. }
  82321. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82322. if (scene.activeCamera) {
  82323. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  82324. }
  82325. });
  82326. return _this;
  82327. }
  82328. return DepthOfFieldBlurPostProcess;
  82329. }(BABYLON.BlurPostProcess));
  82330. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  82331. })(BABYLON || (BABYLON = {}));
  82332. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  82333. var BABYLON;
  82334. (function (BABYLON) {
  82335. /**
  82336. * Options to be set when merging outputs from the default pipeline.
  82337. */
  82338. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  82339. function DepthOfFieldMergePostProcessOptions() {
  82340. }
  82341. return DepthOfFieldMergePostProcessOptions;
  82342. }());
  82343. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  82344. /**
  82345. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  82346. */
  82347. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  82348. __extends(DepthOfFieldMergePostProcess, _super);
  82349. /**
  82350. * Creates a new instance of DepthOfFieldMergePostProcess
  82351. * @param name The name of the effect.
  82352. * @param originalFromInput Post process which's input will be used for the merge.
  82353. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  82354. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  82355. * @param options The required width/height ratio to downsize to before computing the render pass.
  82356. * @param camera The camera to apply the render pass to.
  82357. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82358. * @param engine The engine which the post process will be applied. (default: current engine)
  82359. * @param reusable If the post process can be reused on the same frame. (default: false)
  82360. * @param textureType Type of textures used when performing the post process. (default: 0)
  82361. * @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)
  82362. */
  82363. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82364. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82365. if (blockCompilation === void 0) { blockCompilation = false; }
  82366. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  82367. _this.blurSteps = blurSteps;
  82368. _this.onApplyObservable.add(function (effect) {
  82369. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  82370. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  82371. blurSteps.forEach(function (step, index) {
  82372. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  82373. });
  82374. });
  82375. if (!blockCompilation) {
  82376. _this.updateEffect();
  82377. }
  82378. return _this;
  82379. }
  82380. /**
  82381. * Updates the effect with the current post process compile time values and recompiles the shader.
  82382. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  82383. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  82384. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  82385. * @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
  82386. * @param onCompiled Called when the shader has been compiled.
  82387. * @param onError Called if there is an error when compiling a shader.
  82388. */
  82389. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  82390. if (defines === void 0) { defines = null; }
  82391. if (uniforms === void 0) { uniforms = null; }
  82392. if (samplers === void 0) { samplers = null; }
  82393. if (!defines) {
  82394. defines = "";
  82395. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  82396. }
  82397. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  82398. };
  82399. return DepthOfFieldMergePostProcess;
  82400. }(BABYLON.PostProcess));
  82401. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  82402. })(BABYLON || (BABYLON = {}));
  82403. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  82404. var BABYLON;
  82405. (function (BABYLON) {
  82406. /**
  82407. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  82408. */
  82409. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  82410. __extends(CircleOfConfusionPostProcess, _super);
  82411. /**
  82412. * Creates a new instance CircleOfConfusionPostProcess
  82413. * @param name The name of the effect.
  82414. * @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.
  82415. * @param options The required width/height ratio to downsize to before computing the render pass.
  82416. * @param camera The camera to apply the render pass to.
  82417. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82418. * @param engine The engine which the post process will be applied. (default: current engine)
  82419. * @param reusable If the post process can be reused on the same frame. (default: false)
  82420. * @param textureType Type of textures used when performing the post process. (default: 0)
  82421. * @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)
  82422. */
  82423. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82424. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82425. if (blockCompilation === void 0) { blockCompilation = false; }
  82426. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82427. /**
  82428. * 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.
  82429. */
  82430. _this.lensSize = 50;
  82431. /**
  82432. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82433. */
  82434. _this.fStop = 1.4;
  82435. /**
  82436. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82437. */
  82438. _this.focusDistance = 2000;
  82439. /**
  82440. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  82441. */
  82442. _this.focalLength = 50;
  82443. _this._depthTexture = null;
  82444. _this._depthTexture = depthTexture;
  82445. _this.onApplyObservable.add(function (effect) {
  82446. if (!_this._depthTexture) {
  82447. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  82448. return;
  82449. }
  82450. effect.setTexture("depthSampler", _this._depthTexture);
  82451. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  82452. var aperture = _this.lensSize / _this.fStop;
  82453. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  82454. effect.setFloat('focusDistance', _this.focusDistance);
  82455. effect.setFloat('cocPrecalculation', cocPrecalculation);
  82456. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  82457. });
  82458. return _this;
  82459. }
  82460. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  82461. /**
  82462. * 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.
  82463. */
  82464. set: function (value) {
  82465. this._depthTexture = value;
  82466. },
  82467. enumerable: true,
  82468. configurable: true
  82469. });
  82470. return CircleOfConfusionPostProcess;
  82471. }(BABYLON.PostProcess));
  82472. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  82473. })(BABYLON || (BABYLON = {}));
  82474. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  82475. var BABYLON;
  82476. (function (BABYLON) {
  82477. /**
  82478. * Specifies the level of max blur that should be applied when using the depth of field effect
  82479. */
  82480. var DepthOfFieldEffectBlurLevel;
  82481. (function (DepthOfFieldEffectBlurLevel) {
  82482. /**
  82483. * Subtle blur
  82484. */
  82485. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  82486. /**
  82487. * Medium blur
  82488. */
  82489. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  82490. /**
  82491. * Large blur
  82492. */
  82493. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  82494. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  82495. ;
  82496. /**
  82497. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  82498. */
  82499. var DepthOfFieldEffect = /** @class */ (function (_super) {
  82500. __extends(DepthOfFieldEffect, _super);
  82501. /**
  82502. * Creates a new instance DepthOfFieldEffect
  82503. * @param scene The scene the effect belongs to.
  82504. * @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.
  82505. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  82506. * @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)
  82507. */
  82508. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  82509. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  82510. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  82511. if (blockCompilation === void 0) { blockCompilation = false; }
  82512. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  82513. return _this._effects;
  82514. }, true) || this;
  82515. /**
  82516. * @hidden Internal post processes in depth of field effect
  82517. */
  82518. _this._effects = [];
  82519. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  82520. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82521. // 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)
  82522. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  82523. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  82524. _this._depthOfFieldBlurY = [];
  82525. _this._depthOfFieldBlurX = [];
  82526. var blurCount = 1;
  82527. var kernelSize = 15;
  82528. switch (blurLevel) {
  82529. case DepthOfFieldEffectBlurLevel.High: {
  82530. blurCount = 3;
  82531. kernelSize = 51;
  82532. break;
  82533. }
  82534. case DepthOfFieldEffectBlurLevel.Medium: {
  82535. blurCount = 2;
  82536. kernelSize = 31;
  82537. break;
  82538. }
  82539. default: {
  82540. kernelSize = 15;
  82541. blurCount = 1;
  82542. break;
  82543. }
  82544. }
  82545. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  82546. var ratio = 1.0;
  82547. for (var i = 0; i < blurCount; i++) {
  82548. 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);
  82549. blurY.autoClear = false;
  82550. ratio = 0.75 / Math.pow(2, i);
  82551. 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);
  82552. blurX.autoClear = false;
  82553. _this._depthOfFieldBlurY.push(blurY);
  82554. _this._depthOfFieldBlurX.push(blurX);
  82555. }
  82556. // Set all post processes on the effect.
  82557. _this._effects = [_this._circleOfConfusion];
  82558. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  82559. _this._effects.push(_this._depthOfFieldBlurY[i]);
  82560. _this._effects.push(_this._depthOfFieldBlurX[i]);
  82561. }
  82562. // Merge blurred images with original image based on circleOfConfusion
  82563. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82564. _this._dofMerge.autoClear = false;
  82565. _this._effects.push(_this._dofMerge);
  82566. return _this;
  82567. }
  82568. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  82569. get: function () {
  82570. return this._circleOfConfusion.focalLength;
  82571. },
  82572. /**
  82573. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  82574. */
  82575. set: function (value) {
  82576. this._circleOfConfusion.focalLength = value;
  82577. },
  82578. enumerable: true,
  82579. configurable: true
  82580. });
  82581. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  82582. get: function () {
  82583. return this._circleOfConfusion.fStop;
  82584. },
  82585. /**
  82586. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  82587. */
  82588. set: function (value) {
  82589. this._circleOfConfusion.fStop = value;
  82590. },
  82591. enumerable: true,
  82592. configurable: true
  82593. });
  82594. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  82595. get: function () {
  82596. return this._circleOfConfusion.focusDistance;
  82597. },
  82598. /**
  82599. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  82600. */
  82601. set: function (value) {
  82602. this._circleOfConfusion.focusDistance = value;
  82603. },
  82604. enumerable: true,
  82605. configurable: true
  82606. });
  82607. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  82608. get: function () {
  82609. return this._circleOfConfusion.lensSize;
  82610. },
  82611. /**
  82612. * 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.
  82613. */
  82614. set: function (value) {
  82615. this._circleOfConfusion.lensSize = value;
  82616. },
  82617. enumerable: true,
  82618. configurable: true
  82619. });
  82620. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  82621. /**
  82622. * 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.
  82623. */
  82624. set: function (value) {
  82625. this._circleOfConfusion.depthTexture = value;
  82626. },
  82627. enumerable: true,
  82628. configurable: true
  82629. });
  82630. /**
  82631. * Disposes each of the internal effects for a given camera.
  82632. * @param camera The camera to dispose the effect on.
  82633. */
  82634. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  82635. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82636. this._effects[effectIndex].dispose(camera);
  82637. }
  82638. };
  82639. /**
  82640. * @hidden Internal
  82641. */
  82642. DepthOfFieldEffect.prototype._updateEffects = function () {
  82643. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82644. this._effects[effectIndex].updateEffect();
  82645. }
  82646. };
  82647. /**
  82648. * Internal
  82649. * @returns if all the contained post processes are ready.
  82650. * @hidden
  82651. */
  82652. DepthOfFieldEffect.prototype._isReady = function () {
  82653. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82654. if (!this._effects[effectIndex].isReady()) {
  82655. return false;
  82656. }
  82657. }
  82658. return true;
  82659. };
  82660. return DepthOfFieldEffect;
  82661. }(BABYLON.PostProcessRenderEffect));
  82662. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  82663. })(BABYLON || (BABYLON = {}));
  82664. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  82665. var BABYLON;
  82666. (function (BABYLON) {
  82667. /**
  82668. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  82669. */
  82670. var BloomMergePostProcess = /** @class */ (function (_super) {
  82671. __extends(BloomMergePostProcess, _super);
  82672. /**
  82673. * Creates a new instance of @see BloomMergePostProcess
  82674. * @param name The name of the effect.
  82675. * @param originalFromInput Post process which's input will be used for the merge.
  82676. * @param blurred Blurred highlights post process which's output will be used.
  82677. * @param weight Weight of the bloom to be added to the original input.
  82678. * @param options The required width/height ratio to downsize to before computing the render pass.
  82679. * @param camera The camera to apply the render pass to.
  82680. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  82681. * @param engine The engine which the post process will be applied. (default: current engine)
  82682. * @param reusable If the post process can be reused on the same frame. (default: false)
  82683. * @param textureType Type of textures used when performing the post process. (default: 0)
  82684. * @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)
  82685. */
  82686. function BloomMergePostProcess(name, originalFromInput, blurred,
  82687. /** Weight of the bloom to be added to the original input. */
  82688. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82689. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82690. if (blockCompilation === void 0) { blockCompilation = false; }
  82691. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  82692. _this.weight = weight;
  82693. _this.onApplyObservable.add(function (effect) {
  82694. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  82695. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  82696. effect.setFloat("bloomWeight", _this.weight);
  82697. });
  82698. if (!blockCompilation) {
  82699. _this.updateEffect();
  82700. }
  82701. return _this;
  82702. }
  82703. return BloomMergePostProcess;
  82704. }(BABYLON.PostProcess));
  82705. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  82706. })(BABYLON || (BABYLON = {}));
  82707. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  82708. var BABYLON;
  82709. (function (BABYLON) {
  82710. /**
  82711. * 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.
  82712. */
  82713. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  82714. __extends(ExtractHighlightsPostProcess, _super);
  82715. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  82716. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  82717. if (blockCompilation === void 0) { blockCompilation = false; }
  82718. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  82719. /**
  82720. * The luminance threshold, pixels below this value will be set to black.
  82721. */
  82722. _this.threshold = 0.9;
  82723. /** @hidden */
  82724. _this._exposure = 1;
  82725. /**
  82726. * Post process which has the input texture to be used when performing highlight extraction
  82727. * @hidden
  82728. */
  82729. _this._inputPostProcess = null;
  82730. _this.onApplyObservable.add(function (effect) {
  82731. if (_this._inputPostProcess) {
  82732. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  82733. }
  82734. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  82735. effect.setFloat('exposure', _this._exposure);
  82736. });
  82737. return _this;
  82738. }
  82739. return ExtractHighlightsPostProcess;
  82740. }(BABYLON.PostProcess));
  82741. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  82742. })(BABYLON || (BABYLON = {}));
  82743. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  82744. var BABYLON;
  82745. (function (BABYLON) {
  82746. /**
  82747. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  82748. */
  82749. var BloomEffect = /** @class */ (function (_super) {
  82750. __extends(BloomEffect, _super);
  82751. /**
  82752. * Creates a new instance of @see BloomEffect
  82753. * @param scene The scene the effect belongs to.
  82754. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  82755. * @param bloomKernel The size of the kernel to be used when applying the blur.
  82756. * @param bloomWeight The the strength of bloom.
  82757. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  82758. * @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)
  82759. */
  82760. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  82761. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  82762. if (blockCompilation === void 0) { blockCompilation = false; }
  82763. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  82764. return _this._effects;
  82765. }, true) || this;
  82766. _this.bloomScale = bloomScale;
  82767. /**
  82768. * @hidden Internal
  82769. */
  82770. _this._effects = [];
  82771. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82772. _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);
  82773. _this._blurX.alwaysForcePOT = true;
  82774. _this._blurX.autoClear = false;
  82775. _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);
  82776. _this._blurY.alwaysForcePOT = true;
  82777. _this._blurY.autoClear = false;
  82778. _this.kernel = bloomKernel;
  82779. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  82780. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  82781. _this._merge.autoClear = false;
  82782. _this._effects.push(_this._merge);
  82783. return _this;
  82784. }
  82785. Object.defineProperty(BloomEffect.prototype, "threshold", {
  82786. /**
  82787. * The luminance threshold to find bright areas of the image to bloom.
  82788. */
  82789. get: function () {
  82790. return this._downscale.threshold;
  82791. },
  82792. set: function (value) {
  82793. this._downscale.threshold = value;
  82794. },
  82795. enumerable: true,
  82796. configurable: true
  82797. });
  82798. Object.defineProperty(BloomEffect.prototype, "weight", {
  82799. /**
  82800. * The strength of the bloom.
  82801. */
  82802. get: function () {
  82803. return this._merge.weight;
  82804. },
  82805. set: function (value) {
  82806. this._merge.weight = value;
  82807. },
  82808. enumerable: true,
  82809. configurable: true
  82810. });
  82811. Object.defineProperty(BloomEffect.prototype, "kernel", {
  82812. /**
  82813. * Specifies the size of the bloom blur kernel, relative to the final output size
  82814. */
  82815. get: function () {
  82816. return this._blurX.kernel / this.bloomScale;
  82817. },
  82818. set: function (value) {
  82819. this._blurX.kernel = value * this.bloomScale;
  82820. this._blurY.kernel = value * this.bloomScale;
  82821. },
  82822. enumerable: true,
  82823. configurable: true
  82824. });
  82825. /**
  82826. * Disposes each of the internal effects for a given camera.
  82827. * @param camera The camera to dispose the effect on.
  82828. */
  82829. BloomEffect.prototype.disposeEffects = function (camera) {
  82830. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82831. this._effects[effectIndex].dispose(camera);
  82832. }
  82833. };
  82834. /**
  82835. * @hidden Internal
  82836. */
  82837. BloomEffect.prototype._updateEffects = function () {
  82838. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82839. this._effects[effectIndex].updateEffect();
  82840. }
  82841. };
  82842. /**
  82843. * Internal
  82844. * @returns if all the contained post processes are ready.
  82845. * @hidden
  82846. */
  82847. BloomEffect.prototype._isReady = function () {
  82848. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  82849. if (!this._effects[effectIndex].isReady()) {
  82850. return false;
  82851. }
  82852. }
  82853. return true;
  82854. };
  82855. return BloomEffect;
  82856. }(BABYLON.PostProcessRenderEffect));
  82857. BABYLON.BloomEffect = BloomEffect;
  82858. })(BABYLON || (BABYLON = {}));
  82859. //# sourceMappingURL=babylon.bloomEffect.js.map
  82860. var BABYLON;
  82861. (function (BABYLON) {
  82862. /**
  82863. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  82864. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  82865. */
  82866. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  82867. __extends(DefaultRenderingPipeline, _super);
  82868. /**
  82869. * @constructor
  82870. * @param {string} name - The rendering pipeline name (default: "")
  82871. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  82872. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  82873. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  82874. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  82875. */
  82876. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  82877. if (name === void 0) { name = ""; }
  82878. if (hdr === void 0) { hdr = true; }
  82879. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  82880. if (automaticBuild === void 0) { automaticBuild = true; }
  82881. var _this = _super.call(this, scene.getEngine(), name) || this;
  82882. _this._camerasToBeAttached = [];
  82883. /**
  82884. * ID of the sharpen post process,
  82885. */
  82886. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  82887. /**
  82888. * ID of the image processing post process;
  82889. */
  82890. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  82891. /**
  82892. * ID of the Fast Approximate Anti-Aliasing post process;
  82893. */
  82894. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  82895. /**
  82896. * ID of the chromatic aberration post process,
  82897. */
  82898. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  82899. /**
  82900. * ID of the grain post process
  82901. */
  82902. _this.GrainPostProcessId = "GrainPostProcessEffect";
  82903. /**
  82904. * Glow post process which adds a glow to emmisive areas of the image
  82905. */
  82906. _this._glowLayer = null;
  82907. /**
  82908. * Animations which can be used to tweak settings over a period of time
  82909. */
  82910. _this.animations = [];
  82911. _this._imageProcessingConfigurationObserver = null;
  82912. // Values
  82913. _this._sharpenEnabled = false;
  82914. _this._bloomEnabled = false;
  82915. _this._depthOfFieldEnabled = false;
  82916. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  82917. _this._fxaaEnabled = false;
  82918. _this._imageProcessingEnabled = true;
  82919. _this._bloomScale = 0.5;
  82920. _this._chromaticAberrationEnabled = false;
  82921. _this._grainEnabled = false;
  82922. _this._buildAllowed = true;
  82923. _this._resizeObserver = null;
  82924. _this._hardwareScaleLevel = 1.0;
  82925. _this._bloomKernel = 64;
  82926. /**
  82927. * Specifies the weight of the bloom in the final rendering
  82928. */
  82929. _this._bloomWeight = 0.15;
  82930. /**
  82931. * Specifies the luma threshold for the area that will be blurred by the bloom
  82932. */
  82933. _this._bloomThreshold = 0.9;
  82934. _this._samples = 1;
  82935. _this._hasCleared = false;
  82936. _this._prevPostProcess = null;
  82937. _this._prevPrevPostProcess = null;
  82938. _this._depthOfFieldSceneObserver = null;
  82939. _this._cameras = cameras || scene.cameras;
  82940. _this._cameras = _this._cameras.slice();
  82941. _this._camerasToBeAttached = _this._cameras.slice();
  82942. _this._buildAllowed = automaticBuild;
  82943. // Initialize
  82944. _this._scene = scene;
  82945. var caps = _this._scene.getEngine().getCaps();
  82946. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  82947. // Misc
  82948. if (_this._hdr) {
  82949. if (caps.textureHalfFloatRender) {
  82950. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82951. }
  82952. else if (caps.textureFloatRender) {
  82953. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82954. }
  82955. }
  82956. else {
  82957. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82958. }
  82959. // Attach
  82960. scene.postProcessRenderPipelineManager.addPipeline(_this);
  82961. var engine = _this._scene.getEngine();
  82962. // Create post processes before hand so they can be modified before enabled.
  82963. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  82964. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  82965. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  82966. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  82967. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  82968. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  82969. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  82970. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  82971. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  82972. _this._resizeObserver = engine.onResizeObservable.add(function () {
  82973. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  82974. _this.bloomKernel = _this.bloomKernel;
  82975. });
  82976. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  82977. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  82978. });
  82979. _this._buildPipeline();
  82980. return _this;
  82981. }
  82982. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  82983. get: function () {
  82984. return this._sharpenEnabled;
  82985. },
  82986. /**
  82987. * Enable or disable the sharpen process from the pipeline
  82988. */
  82989. set: function (enabled) {
  82990. if (this._sharpenEnabled === enabled) {
  82991. return;
  82992. }
  82993. this._sharpenEnabled = enabled;
  82994. this._buildPipeline();
  82995. },
  82996. enumerable: true,
  82997. configurable: true
  82998. });
  82999. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  83000. /**
  83001. * Specifies the size of the bloom blur kernel, relative to the final output size
  83002. */
  83003. get: function () {
  83004. return this._bloomKernel;
  83005. },
  83006. set: function (value) {
  83007. this._bloomKernel = value;
  83008. this.bloom.kernel = value / this._hardwareScaleLevel;
  83009. },
  83010. enumerable: true,
  83011. configurable: true
  83012. });
  83013. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  83014. get: function () {
  83015. return this._bloomWeight;
  83016. },
  83017. /**
  83018. * The strength of the bloom.
  83019. */
  83020. set: function (value) {
  83021. if (this._bloomWeight === value) {
  83022. return;
  83023. }
  83024. this.bloom.weight = value;
  83025. this._bloomWeight = value;
  83026. },
  83027. enumerable: true,
  83028. configurable: true
  83029. });
  83030. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  83031. get: function () {
  83032. return this._bloomThreshold;
  83033. },
  83034. /**
  83035. * The strength of the bloom.
  83036. */
  83037. set: function (value) {
  83038. if (this._bloomThreshold === value) {
  83039. return;
  83040. }
  83041. this.bloom.threshold = value;
  83042. this._bloomThreshold = value;
  83043. },
  83044. enumerable: true,
  83045. configurable: true
  83046. });
  83047. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  83048. get: function () {
  83049. return this._bloomScale;
  83050. },
  83051. /**
  83052. * The scale of the bloom, lower value will provide better performance.
  83053. */
  83054. set: function (value) {
  83055. if (this._bloomScale === value) {
  83056. return;
  83057. }
  83058. this._bloomScale = value;
  83059. // recreate bloom and dispose old as this setting is not dynamic
  83060. this._rebuildBloom();
  83061. this._buildPipeline();
  83062. },
  83063. enumerable: true,
  83064. configurable: true
  83065. });
  83066. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  83067. get: function () {
  83068. return this._bloomEnabled;
  83069. },
  83070. /**
  83071. * Enable or disable the bloom from the pipeline
  83072. */
  83073. set: function (enabled) {
  83074. if (this._bloomEnabled === enabled) {
  83075. return;
  83076. }
  83077. this._bloomEnabled = enabled;
  83078. this._buildPipeline();
  83079. },
  83080. enumerable: true,
  83081. configurable: true
  83082. });
  83083. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  83084. // recreate bloom and dispose old as this setting is not dynamic
  83085. var oldBloom = this.bloom;
  83086. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  83087. this.bloom.threshold = oldBloom.threshold;
  83088. for (var i = 0; i < this._cameras.length; i++) {
  83089. oldBloom.disposeEffects(this._cameras[i]);
  83090. }
  83091. };
  83092. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  83093. /**
  83094. * If the depth of field is enabled.
  83095. */
  83096. get: function () {
  83097. return this._depthOfFieldEnabled;
  83098. },
  83099. set: function (enabled) {
  83100. if (this._depthOfFieldEnabled === enabled) {
  83101. return;
  83102. }
  83103. this._depthOfFieldEnabled = enabled;
  83104. this._buildPipeline();
  83105. },
  83106. enumerable: true,
  83107. configurable: true
  83108. });
  83109. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  83110. /**
  83111. * Blur level of the depth of field effect. (Higher blur will effect performance)
  83112. */
  83113. get: function () {
  83114. return this._depthOfFieldBlurLevel;
  83115. },
  83116. set: function (value) {
  83117. if (this._depthOfFieldBlurLevel === value) {
  83118. return;
  83119. }
  83120. this._depthOfFieldBlurLevel = value;
  83121. // recreate dof and dispose old as this setting is not dynamic
  83122. var oldDof = this.depthOfField;
  83123. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  83124. this.depthOfField.focalLength = oldDof.focalLength;
  83125. this.depthOfField.focusDistance = oldDof.focusDistance;
  83126. this.depthOfField.fStop = oldDof.fStop;
  83127. this.depthOfField.lensSize = oldDof.lensSize;
  83128. for (var i = 0; i < this._cameras.length; i++) {
  83129. oldDof.disposeEffects(this._cameras[i]);
  83130. }
  83131. this._buildPipeline();
  83132. },
  83133. enumerable: true,
  83134. configurable: true
  83135. });
  83136. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  83137. get: function () {
  83138. return this._fxaaEnabled;
  83139. },
  83140. /**
  83141. * If the anti aliasing is enabled.
  83142. */
  83143. set: function (enabled) {
  83144. if (this._fxaaEnabled === enabled) {
  83145. return;
  83146. }
  83147. this._fxaaEnabled = enabled;
  83148. this._buildPipeline();
  83149. },
  83150. enumerable: true,
  83151. configurable: true
  83152. });
  83153. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  83154. get: function () {
  83155. return this._samples;
  83156. },
  83157. /**
  83158. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  83159. */
  83160. set: function (sampleCount) {
  83161. if (this._samples === sampleCount) {
  83162. return;
  83163. }
  83164. this._samples = sampleCount;
  83165. this._buildPipeline();
  83166. },
  83167. enumerable: true,
  83168. configurable: true
  83169. });
  83170. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  83171. get: function () {
  83172. return this._imageProcessingEnabled;
  83173. },
  83174. /**
  83175. * If image processing is enabled.
  83176. */
  83177. set: function (enabled) {
  83178. if (this._imageProcessingEnabled === enabled) {
  83179. return;
  83180. }
  83181. this._imageProcessingEnabled = enabled;
  83182. this._buildPipeline();
  83183. },
  83184. enumerable: true,
  83185. configurable: true
  83186. });
  83187. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  83188. get: function () {
  83189. return this._glowLayer == null;
  83190. },
  83191. /**
  83192. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  83193. */
  83194. set: function (enabled) {
  83195. if (enabled && !this._glowLayer) {
  83196. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  83197. }
  83198. else if (!enabled && this._glowLayer) {
  83199. this._glowLayer.dispose();
  83200. this._glowLayer = null;
  83201. }
  83202. },
  83203. enumerable: true,
  83204. configurable: true
  83205. });
  83206. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  83207. get: function () {
  83208. return this._chromaticAberrationEnabled;
  83209. },
  83210. /**
  83211. * Enable or disable the chromaticAberration process from the pipeline
  83212. */
  83213. set: function (enabled) {
  83214. if (this._chromaticAberrationEnabled === enabled) {
  83215. return;
  83216. }
  83217. this._chromaticAberrationEnabled = enabled;
  83218. this._buildPipeline();
  83219. },
  83220. enumerable: true,
  83221. configurable: true
  83222. });
  83223. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  83224. get: function () {
  83225. return this._grainEnabled;
  83226. },
  83227. /**
  83228. * Enable or disable the grain process from the pipeline
  83229. */
  83230. set: function (enabled) {
  83231. if (this._grainEnabled === enabled) {
  83232. return;
  83233. }
  83234. this._grainEnabled = enabled;
  83235. this._buildPipeline();
  83236. },
  83237. enumerable: true,
  83238. configurable: true
  83239. });
  83240. /**
  83241. * Force the compilation of the entire pipeline.
  83242. */
  83243. DefaultRenderingPipeline.prototype.prepare = function () {
  83244. var previousState = this._buildAllowed;
  83245. this._buildAllowed = true;
  83246. this._buildPipeline();
  83247. this._buildAllowed = previousState;
  83248. };
  83249. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  83250. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  83251. if (this._hasCleared) {
  83252. postProcess.autoClear = false;
  83253. }
  83254. else {
  83255. postProcess.autoClear = true;
  83256. this._scene.autoClear = false;
  83257. this._hasCleared = true;
  83258. }
  83259. if (!skipTextureSharing) {
  83260. if (this._prevPrevPostProcess) {
  83261. postProcess.shareOutputWith(this._prevPrevPostProcess);
  83262. }
  83263. else {
  83264. postProcess.useOwnOutput();
  83265. }
  83266. if (this._prevPostProcess) {
  83267. this._prevPrevPostProcess = this._prevPostProcess;
  83268. }
  83269. this._prevPostProcess = postProcess;
  83270. }
  83271. };
  83272. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  83273. var _this = this;
  83274. if (!this._buildAllowed) {
  83275. return;
  83276. }
  83277. this._scene.autoClear = true;
  83278. var engine = this._scene.getEngine();
  83279. this._disposePostProcesses();
  83280. if (this._cameras !== null) {
  83281. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83282. // get back cameras to be used to reattach pipeline
  83283. this._cameras = this._camerasToBeAttached.slice();
  83284. }
  83285. this._reset();
  83286. this._prevPostProcess = null;
  83287. this._prevPrevPostProcess = null;
  83288. this._hasCleared = false;
  83289. if (this.depthOfFieldEnabled) {
  83290. // Multi camera suport
  83291. if (this._cameras.length > 1) {
  83292. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  83293. var camera = _a[_i];
  83294. var depthRenderer = this._scene.enableDepthRenderer(camera);
  83295. depthRenderer.useOnlyInActiveCamera = true;
  83296. }
  83297. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  83298. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  83299. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  83300. }
  83301. });
  83302. }
  83303. else {
  83304. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83305. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  83306. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  83307. }
  83308. if (!this.depthOfField._isReady()) {
  83309. this.depthOfField._updateEffects();
  83310. }
  83311. this.addEffect(this.depthOfField);
  83312. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  83313. }
  83314. else {
  83315. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83316. }
  83317. if (this.bloomEnabled) {
  83318. if (!this.bloom._isReady()) {
  83319. this.bloom._updateEffects();
  83320. }
  83321. this.addEffect(this.bloom);
  83322. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  83323. }
  83324. if (this._imageProcessingEnabled) {
  83325. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83326. if (this._hdr) {
  83327. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  83328. this._setAutoClearAndTextureSharing(this.imageProcessing);
  83329. }
  83330. else {
  83331. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  83332. }
  83333. }
  83334. if (this.sharpenEnabled) {
  83335. if (!this.sharpen.isReady()) {
  83336. this.sharpen.updateEffect();
  83337. }
  83338. this.addEffect(this._sharpenEffect);
  83339. this._setAutoClearAndTextureSharing(this.sharpen);
  83340. }
  83341. if (this.grainEnabled) {
  83342. if (!this.grain.isReady()) {
  83343. this.grain.updateEffect();
  83344. }
  83345. this.addEffect(this._grainEffect);
  83346. this._setAutoClearAndTextureSharing(this.grain);
  83347. }
  83348. if (this.chromaticAberrationEnabled) {
  83349. if (!this.chromaticAberration.isReady()) {
  83350. this.chromaticAberration.updateEffect();
  83351. }
  83352. this.addEffect(this._chromaticAberrationEffect);
  83353. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  83354. }
  83355. if (this.fxaaEnabled) {
  83356. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  83357. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  83358. this._setAutoClearAndTextureSharing(this.fxaa, true);
  83359. }
  83360. if (this._cameras !== null) {
  83361. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  83362. }
  83363. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  83364. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  83365. }
  83366. };
  83367. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  83368. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  83369. for (var i = 0; i < this._cameras.length; i++) {
  83370. var camera = this._cameras[i];
  83371. if (this.imageProcessing) {
  83372. this.imageProcessing.dispose(camera);
  83373. }
  83374. if (this.fxaa) {
  83375. this.fxaa.dispose(camera);
  83376. }
  83377. // These are created in the constructor and should not be disposed on every pipeline change
  83378. if (disposeNonRecreated) {
  83379. if (this.sharpen) {
  83380. this.sharpen.dispose(camera);
  83381. }
  83382. if (this.depthOfField) {
  83383. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  83384. this.depthOfField.disposeEffects(camera);
  83385. }
  83386. if (this.bloom) {
  83387. this.bloom.disposeEffects(camera);
  83388. }
  83389. if (this.chromaticAberration) {
  83390. this.chromaticAberration.dispose(camera);
  83391. }
  83392. if (this.grain) {
  83393. this.grain.dispose(camera);
  83394. }
  83395. if (this._glowLayer) {
  83396. this._glowLayer.dispose();
  83397. }
  83398. }
  83399. }
  83400. this.imageProcessing = null;
  83401. this.fxaa = null;
  83402. if (disposeNonRecreated) {
  83403. this.sharpen = null;
  83404. this._sharpenEffect = null;
  83405. this.depthOfField = null;
  83406. this.bloom = null;
  83407. this.chromaticAberration = null;
  83408. this._chromaticAberrationEffect = null;
  83409. this.grain = null;
  83410. this._grainEffect = null;
  83411. this._glowLayer = null;
  83412. }
  83413. };
  83414. /**
  83415. * Adds a camera to the pipeline
  83416. * @param camera the camera to be added
  83417. */
  83418. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  83419. this._camerasToBeAttached.push(camera);
  83420. this._buildPipeline();
  83421. };
  83422. /**
  83423. * Removes a camera from the pipeline
  83424. * @param camera the camera to remove
  83425. */
  83426. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  83427. var index = this._camerasToBeAttached.indexOf(camera);
  83428. this._camerasToBeAttached.splice(index, 1);
  83429. this._buildPipeline();
  83430. };
  83431. /**
  83432. * Dispose of the pipeline and stop all post processes
  83433. */
  83434. DefaultRenderingPipeline.prototype.dispose = function () {
  83435. this._disposePostProcesses(true);
  83436. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  83437. this._scene.autoClear = true;
  83438. if (this._resizeObserver) {
  83439. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  83440. this._resizeObserver = null;
  83441. }
  83442. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  83443. _super.prototype.dispose.call(this);
  83444. };
  83445. /**
  83446. * Serialize the rendering pipeline (Used when exporting)
  83447. * @returns the serialized object
  83448. */
  83449. DefaultRenderingPipeline.prototype.serialize = function () {
  83450. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83451. serializationObject.customType = "DefaultRenderingPipeline";
  83452. return serializationObject;
  83453. };
  83454. /**
  83455. * Parse the serialized pipeline
  83456. * @param source Source pipeline.
  83457. * @param scene The scene to load the pipeline to.
  83458. * @param rootUrl The URL of the serialized pipeline.
  83459. * @returns An instantiated pipeline from the serialized object.
  83460. */
  83461. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  83462. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  83463. };
  83464. __decorate([
  83465. BABYLON.serialize()
  83466. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  83467. __decorate([
  83468. BABYLON.serialize()
  83469. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  83470. __decorate([
  83471. BABYLON.serialize()
  83472. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  83473. __decorate([
  83474. BABYLON.serialize()
  83475. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  83476. __decorate([
  83477. BABYLON.serialize()
  83478. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  83479. __decorate([
  83480. BABYLON.serialize()
  83481. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  83482. __decorate([
  83483. BABYLON.serialize()
  83484. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  83485. __decorate([
  83486. BABYLON.serialize()
  83487. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  83488. __decorate([
  83489. BABYLON.serialize()
  83490. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  83491. __decorate([
  83492. BABYLON.serialize()
  83493. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  83494. __decorate([
  83495. BABYLON.serialize()
  83496. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  83497. __decorate([
  83498. BABYLON.serialize()
  83499. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  83500. __decorate([
  83501. BABYLON.serialize()
  83502. ], DefaultRenderingPipeline.prototype, "samples", null);
  83503. __decorate([
  83504. BABYLON.serialize()
  83505. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  83506. __decorate([
  83507. BABYLON.serialize()
  83508. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  83509. __decorate([
  83510. BABYLON.serialize()
  83511. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  83512. __decorate([
  83513. BABYLON.serialize()
  83514. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  83515. return DefaultRenderingPipeline;
  83516. }(BABYLON.PostProcessRenderPipeline));
  83517. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  83518. })(BABYLON || (BABYLON = {}));
  83519. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  83520. var BABYLON;
  83521. (function (BABYLON) {
  83522. /**
  83523. * @hidden
  83524. */
  83525. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  83526. __extends(ImageProcessingConfigurationDefines, _super);
  83527. function ImageProcessingConfigurationDefines() {
  83528. var _this = _super.call(this) || this;
  83529. _this.IMAGEPROCESSING = false;
  83530. _this.VIGNETTE = false;
  83531. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83532. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83533. _this.TONEMAPPING = false;
  83534. _this.TONEMAPPING_ACES = false;
  83535. _this.CONTRAST = false;
  83536. _this.COLORCURVES = false;
  83537. _this.COLORGRADING = false;
  83538. _this.COLORGRADING3D = false;
  83539. _this.SAMPLER3DGREENDEPTH = false;
  83540. _this.SAMPLER3DBGRMAP = false;
  83541. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83542. _this.EXPOSURE = false;
  83543. _this.rebuild();
  83544. return _this;
  83545. }
  83546. return ImageProcessingConfigurationDefines;
  83547. }(BABYLON.MaterialDefines));
  83548. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  83549. /**
  83550. * This groups together the common properties used for image processing either in direct forward pass
  83551. * or through post processing effect depending on the use of the image processing pipeline in your scene
  83552. * or not.
  83553. */
  83554. var ImageProcessingConfiguration = /** @class */ (function () {
  83555. function ImageProcessingConfiguration() {
  83556. /**
  83557. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  83558. */
  83559. this.colorCurves = new BABYLON.ColorCurves();
  83560. this._colorCurvesEnabled = false;
  83561. this._colorGradingEnabled = false;
  83562. this._colorGradingWithGreenDepth = true;
  83563. this._colorGradingBGR = true;
  83564. /** @hidden */
  83565. this._exposure = 1.0;
  83566. this._toneMappingEnabled = false;
  83567. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  83568. this._contrast = 1.0;
  83569. /**
  83570. * Vignette stretch size.
  83571. */
  83572. this.vignetteStretch = 0;
  83573. /**
  83574. * Vignette centre X Offset.
  83575. */
  83576. this.vignetteCentreX = 0;
  83577. /**
  83578. * Vignette centre Y Offset.
  83579. */
  83580. this.vignetteCentreY = 0;
  83581. /**
  83582. * Vignette weight or intensity of the vignette effect.
  83583. */
  83584. this.vignetteWeight = 1.5;
  83585. /**
  83586. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  83587. * if vignetteEnabled is set to true.
  83588. */
  83589. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83590. /**
  83591. * Camera field of view used by the Vignette effect.
  83592. */
  83593. this.vignetteCameraFov = 0.5;
  83594. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  83595. this._vignetteEnabled = false;
  83596. this._applyByPostProcess = false;
  83597. this._isEnabled = true;
  83598. /**
  83599. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  83600. */
  83601. this.onUpdateParameters = new BABYLON.Observable();
  83602. }
  83603. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  83604. /**
  83605. * Gets wether the color curves effect is enabled.
  83606. */
  83607. get: function () {
  83608. return this._colorCurvesEnabled;
  83609. },
  83610. /**
  83611. * Sets wether the color curves effect is enabled.
  83612. */
  83613. set: function (value) {
  83614. if (this._colorCurvesEnabled === value) {
  83615. return;
  83616. }
  83617. this._colorCurvesEnabled = value;
  83618. this._updateParameters();
  83619. },
  83620. enumerable: true,
  83621. configurable: true
  83622. });
  83623. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  83624. /**
  83625. * Gets wether the color grading effect is enabled.
  83626. */
  83627. get: function () {
  83628. return this._colorGradingEnabled;
  83629. },
  83630. /**
  83631. * Sets wether the color grading effect is enabled.
  83632. */
  83633. set: function (value) {
  83634. if (this._colorGradingEnabled === value) {
  83635. return;
  83636. }
  83637. this._colorGradingEnabled = value;
  83638. this._updateParameters();
  83639. },
  83640. enumerable: true,
  83641. configurable: true
  83642. });
  83643. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  83644. /**
  83645. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  83646. */
  83647. get: function () {
  83648. return this._colorGradingWithGreenDepth;
  83649. },
  83650. /**
  83651. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  83652. */
  83653. set: function (value) {
  83654. if (this._colorGradingWithGreenDepth === value) {
  83655. return;
  83656. }
  83657. this._colorGradingWithGreenDepth = value;
  83658. this._updateParameters();
  83659. },
  83660. enumerable: true,
  83661. configurable: true
  83662. });
  83663. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  83664. /**
  83665. * Gets wether the color grading texture contains BGR values.
  83666. */
  83667. get: function () {
  83668. return this._colorGradingBGR;
  83669. },
  83670. /**
  83671. * Sets wether the color grading texture contains BGR values.
  83672. */
  83673. set: function (value) {
  83674. if (this._colorGradingBGR === value) {
  83675. return;
  83676. }
  83677. this._colorGradingBGR = value;
  83678. this._updateParameters();
  83679. },
  83680. enumerable: true,
  83681. configurable: true
  83682. });
  83683. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  83684. /**
  83685. * Gets the Exposure used in the effect.
  83686. */
  83687. get: function () {
  83688. return this._exposure;
  83689. },
  83690. /**
  83691. * Sets the Exposure used in the effect.
  83692. */
  83693. set: function (value) {
  83694. if (this._exposure === value) {
  83695. return;
  83696. }
  83697. this._exposure = value;
  83698. this._updateParameters();
  83699. },
  83700. enumerable: true,
  83701. configurable: true
  83702. });
  83703. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  83704. /**
  83705. * Gets wether the tone mapping effect is enabled.
  83706. */
  83707. get: function () {
  83708. return this._toneMappingEnabled;
  83709. },
  83710. /**
  83711. * Sets wether the tone mapping effect is enabled.
  83712. */
  83713. set: function (value) {
  83714. if (this._toneMappingEnabled === value) {
  83715. return;
  83716. }
  83717. this._toneMappingEnabled = value;
  83718. this._updateParameters();
  83719. },
  83720. enumerable: true,
  83721. configurable: true
  83722. });
  83723. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  83724. /**
  83725. * Gets the type of tone mapping effect.
  83726. */
  83727. get: function () {
  83728. return this._toneMappingType;
  83729. },
  83730. /**
  83731. * Sets the type of tone mapping effect used in BabylonJS.
  83732. */
  83733. set: function (value) {
  83734. if (this._toneMappingType === value) {
  83735. return;
  83736. }
  83737. this._toneMappingType = value;
  83738. this._updateParameters();
  83739. },
  83740. enumerable: true,
  83741. configurable: true
  83742. });
  83743. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  83744. /**
  83745. * Gets the contrast used in the effect.
  83746. */
  83747. get: function () {
  83748. return this._contrast;
  83749. },
  83750. /**
  83751. * Sets the contrast used in the effect.
  83752. */
  83753. set: function (value) {
  83754. if (this._contrast === value) {
  83755. return;
  83756. }
  83757. this._contrast = value;
  83758. this._updateParameters();
  83759. },
  83760. enumerable: true,
  83761. configurable: true
  83762. });
  83763. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  83764. /**
  83765. * Gets the vignette blend mode allowing different kind of effect.
  83766. */
  83767. get: function () {
  83768. return this._vignetteBlendMode;
  83769. },
  83770. /**
  83771. * Sets the vignette blend mode allowing different kind of effect.
  83772. */
  83773. set: function (value) {
  83774. if (this._vignetteBlendMode === value) {
  83775. return;
  83776. }
  83777. this._vignetteBlendMode = value;
  83778. this._updateParameters();
  83779. },
  83780. enumerable: true,
  83781. configurable: true
  83782. });
  83783. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  83784. /**
  83785. * Gets wether the vignette effect is enabled.
  83786. */
  83787. get: function () {
  83788. return this._vignetteEnabled;
  83789. },
  83790. /**
  83791. * Sets wether the vignette effect is enabled.
  83792. */
  83793. set: function (value) {
  83794. if (this._vignetteEnabled === value) {
  83795. return;
  83796. }
  83797. this._vignetteEnabled = value;
  83798. this._updateParameters();
  83799. },
  83800. enumerable: true,
  83801. configurable: true
  83802. });
  83803. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  83804. /**
  83805. * Gets wether the image processing is applied through a post process or not.
  83806. */
  83807. get: function () {
  83808. return this._applyByPostProcess;
  83809. },
  83810. /**
  83811. * Sets wether the image processing is applied through a post process or not.
  83812. */
  83813. set: function (value) {
  83814. if (this._applyByPostProcess === value) {
  83815. return;
  83816. }
  83817. this._applyByPostProcess = value;
  83818. this._updateParameters();
  83819. },
  83820. enumerable: true,
  83821. configurable: true
  83822. });
  83823. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  83824. /**
  83825. * Gets wether the image processing is enabled or not.
  83826. */
  83827. get: function () {
  83828. return this._isEnabled;
  83829. },
  83830. /**
  83831. * Sets wether the image processing is enabled or not.
  83832. */
  83833. set: function (value) {
  83834. if (this._isEnabled === value) {
  83835. return;
  83836. }
  83837. this._isEnabled = value;
  83838. this._updateParameters();
  83839. },
  83840. enumerable: true,
  83841. configurable: true
  83842. });
  83843. /**
  83844. * Method called each time the image processing information changes requires to recompile the effect.
  83845. */
  83846. ImageProcessingConfiguration.prototype._updateParameters = function () {
  83847. this.onUpdateParameters.notifyObservers(this);
  83848. };
  83849. ImageProcessingConfiguration.prototype.getClassName = function () {
  83850. return "ImageProcessingConfiguration";
  83851. };
  83852. /**
  83853. * Prepare the list of uniforms associated with the Image Processing effects.
  83854. * @param uniformsList The list of uniforms used in the effect
  83855. * @param defines the list of defines currently in use
  83856. */
  83857. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  83858. if (defines.EXPOSURE) {
  83859. uniforms.push("exposureLinear");
  83860. }
  83861. if (defines.CONTRAST) {
  83862. uniforms.push("contrast");
  83863. }
  83864. if (defines.COLORGRADING) {
  83865. uniforms.push("colorTransformSettings");
  83866. }
  83867. if (defines.VIGNETTE) {
  83868. uniforms.push("vInverseScreenSize");
  83869. uniforms.push("vignetteSettings1");
  83870. uniforms.push("vignetteSettings2");
  83871. }
  83872. if (defines.COLORCURVES) {
  83873. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  83874. }
  83875. };
  83876. /**
  83877. * Prepare the list of samplers associated with the Image Processing effects.
  83878. * @param uniformsList The list of uniforms used in the effect
  83879. * @param defines the list of defines currently in use
  83880. */
  83881. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  83882. if (defines.COLORGRADING) {
  83883. samplersList.push("txColorTransform");
  83884. }
  83885. };
  83886. /**
  83887. * Prepare the list of defines associated to the shader.
  83888. * @param defines the list of defines to complete
  83889. */
  83890. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  83891. if (forPostProcess === void 0) { forPostProcess = false; }
  83892. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  83893. defines.VIGNETTE = false;
  83894. defines.TONEMAPPING = false;
  83895. defines.TONEMAPPING_ACES = false;
  83896. defines.CONTRAST = false;
  83897. defines.EXPOSURE = false;
  83898. defines.COLORCURVES = false;
  83899. defines.COLORGRADING = false;
  83900. defines.COLORGRADING3D = false;
  83901. defines.IMAGEPROCESSING = false;
  83902. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  83903. return;
  83904. }
  83905. defines.VIGNETTE = this.vignetteEnabled;
  83906. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  83907. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  83908. defines.TONEMAPPING = this.toneMappingEnabled;
  83909. switch (this._toneMappingType) {
  83910. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  83911. defines.TONEMAPPING_ACES = true;
  83912. break;
  83913. }
  83914. defines.CONTRAST = (this.contrast !== 1.0);
  83915. defines.EXPOSURE = (this.exposure !== 1.0);
  83916. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  83917. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  83918. if (defines.COLORGRADING) {
  83919. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  83920. }
  83921. else {
  83922. defines.COLORGRADING3D = false;
  83923. }
  83924. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  83925. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  83926. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  83927. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  83928. };
  83929. /**
  83930. * Returns true if all the image processing information are ready.
  83931. */
  83932. ImageProcessingConfiguration.prototype.isReady = function () {
  83933. // Color Grading texure can not be none blocking.
  83934. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  83935. };
  83936. /**
  83937. * Binds the image processing to the shader.
  83938. * @param effect The effect to bind to
  83939. */
  83940. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  83941. if (aspectRatio === void 0) { aspectRatio = 1; }
  83942. // Color Curves
  83943. if (this._colorCurvesEnabled && this.colorCurves) {
  83944. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  83945. }
  83946. // Vignette
  83947. if (this._vignetteEnabled) {
  83948. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  83949. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  83950. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  83951. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  83952. var vignetteScaleX = vignetteScaleY * aspectRatio;
  83953. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  83954. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  83955. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  83956. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  83957. var vignettePower = -2.0 * this.vignetteWeight;
  83958. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  83959. }
  83960. // Exposure
  83961. effect.setFloat("exposureLinear", this.exposure);
  83962. // Contrast
  83963. effect.setFloat("contrast", this.contrast);
  83964. // Color transform settings
  83965. if (this.colorGradingTexture) {
  83966. effect.setTexture("txColorTransform", this.colorGradingTexture);
  83967. var textureSize = this.colorGradingTexture.getSize().height;
  83968. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  83969. 0.5 / textureSize, // textureOffset
  83970. textureSize, // textureSize
  83971. this.colorGradingTexture.level // weight
  83972. );
  83973. }
  83974. };
  83975. /**
  83976. * Clones the current image processing instance.
  83977. * @return The cloned image processing
  83978. */
  83979. ImageProcessingConfiguration.prototype.clone = function () {
  83980. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  83981. };
  83982. /**
  83983. * Serializes the current image processing instance to a json representation.
  83984. * @return a JSON representation
  83985. */
  83986. ImageProcessingConfiguration.prototype.serialize = function () {
  83987. return BABYLON.SerializationHelper.Serialize(this);
  83988. };
  83989. /**
  83990. * Parses the image processing from a json representation.
  83991. * @param source the JSON source to parse
  83992. * @return The parsed image processing
  83993. */
  83994. ImageProcessingConfiguration.Parse = function (source) {
  83995. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  83996. };
  83997. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  83998. /**
  83999. * Used to apply the vignette as a mix with the pixel color.
  84000. */
  84001. get: function () {
  84002. return this._VIGNETTEMODE_MULTIPLY;
  84003. },
  84004. enumerable: true,
  84005. configurable: true
  84006. });
  84007. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  84008. /**
  84009. * Used to apply the vignette as a replacement of the pixel color.
  84010. */
  84011. get: function () {
  84012. return this._VIGNETTEMODE_OPAQUE;
  84013. },
  84014. enumerable: true,
  84015. configurable: true
  84016. });
  84017. /**
  84018. * Default tone mapping applied in BabylonJS.
  84019. */
  84020. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  84021. /**
  84022. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  84023. * to other engines rendering to increase portability.
  84024. */
  84025. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  84026. // Static constants associated to the image processing.
  84027. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  84028. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  84029. __decorate([
  84030. BABYLON.serializeAsColorCurves()
  84031. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  84032. __decorate([
  84033. BABYLON.serialize()
  84034. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  84035. __decorate([
  84036. BABYLON.serializeAsTexture()
  84037. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  84038. __decorate([
  84039. BABYLON.serialize()
  84040. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  84041. __decorate([
  84042. BABYLON.serialize()
  84043. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  84044. __decorate([
  84045. BABYLON.serialize()
  84046. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  84047. __decorate([
  84048. BABYLON.serialize()
  84049. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  84050. __decorate([
  84051. BABYLON.serialize()
  84052. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  84053. __decorate([
  84054. BABYLON.serialize()
  84055. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  84056. __decorate([
  84057. BABYLON.serialize()
  84058. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  84059. __decorate([
  84060. BABYLON.serialize()
  84061. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  84062. __decorate([
  84063. BABYLON.serialize()
  84064. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  84065. __decorate([
  84066. BABYLON.serialize()
  84067. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  84068. __decorate([
  84069. BABYLON.serialize()
  84070. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  84071. __decorate([
  84072. BABYLON.serializeAsColor4()
  84073. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  84074. __decorate([
  84075. BABYLON.serialize()
  84076. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  84077. __decorate([
  84078. BABYLON.serialize()
  84079. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  84080. __decorate([
  84081. BABYLON.serialize()
  84082. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  84083. __decorate([
  84084. BABYLON.serialize()
  84085. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  84086. __decorate([
  84087. BABYLON.serialize()
  84088. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  84089. return ImageProcessingConfiguration;
  84090. }());
  84091. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  84092. })(BABYLON || (BABYLON = {}));
  84093. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  84094. var BABYLON;
  84095. (function (BABYLON) {
  84096. /**
  84097. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  84098. * It can help converting any input color in a desired output one. This can then be used to create effects
  84099. * from sepia, black and white to sixties or futuristic rendering...
  84100. *
  84101. * The only supported format is currently 3dl.
  84102. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  84103. */
  84104. var ColorGradingTexture = /** @class */ (function (_super) {
  84105. __extends(ColorGradingTexture, _super);
  84106. /**
  84107. * Instantiates a ColorGradingTexture from the following parameters.
  84108. *
  84109. * @param url The location of the color gradind data (currently only supporting 3dl)
  84110. * @param scene The scene the texture will be used in
  84111. */
  84112. function ColorGradingTexture(url, scene) {
  84113. var _this = _super.call(this, scene) || this;
  84114. if (!url) {
  84115. return _this;
  84116. }
  84117. _this._engine = scene.getEngine();
  84118. _this._textureMatrix = BABYLON.Matrix.Identity();
  84119. _this.name = url;
  84120. _this.url = url;
  84121. _this.hasAlpha = false;
  84122. _this.isCube = false;
  84123. _this.is3D = _this._engine.webGLVersion > 1;
  84124. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84125. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84126. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84127. _this.anisotropicFilteringLevel = 1;
  84128. _this._texture = _this._getFromCache(url, true);
  84129. if (!_this._texture) {
  84130. if (!scene.useDelayedTextureLoading) {
  84131. _this.loadTexture();
  84132. }
  84133. else {
  84134. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84135. }
  84136. }
  84137. return _this;
  84138. }
  84139. /**
  84140. * Returns the texture matrix used in most of the material.
  84141. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  84142. */
  84143. ColorGradingTexture.prototype.getTextureMatrix = function () {
  84144. return this._textureMatrix;
  84145. };
  84146. /**
  84147. * Occurs when the file being loaded is a .3dl LUT file.
  84148. */
  84149. ColorGradingTexture.prototype.load3dlTexture = function () {
  84150. var engine = this._engine;
  84151. var texture;
  84152. if (engine.webGLVersion === 1) {
  84153. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84154. }
  84155. else {
  84156. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84157. }
  84158. this._texture = texture;
  84159. var callback = function (text) {
  84160. if (typeof text !== "string") {
  84161. return;
  84162. }
  84163. var data = null;
  84164. var tempData = null;
  84165. var line;
  84166. var lines = text.split('\n');
  84167. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  84168. var maxColor = 0;
  84169. for (var i = 0; i < lines.length; i++) {
  84170. line = lines[i];
  84171. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  84172. continue;
  84173. if (line.indexOf('#') === 0)
  84174. continue;
  84175. var words = line.split(" ");
  84176. if (size === 0) {
  84177. // Number of space + one
  84178. size = words.length;
  84179. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  84180. tempData = new Float32Array(size * size * size * 4);
  84181. continue;
  84182. }
  84183. if (size != 0) {
  84184. var r = Math.max(parseInt(words[0]), 0);
  84185. var g = Math.max(parseInt(words[1]), 0);
  84186. var b = Math.max(parseInt(words[2]), 0);
  84187. maxColor = Math.max(r, maxColor);
  84188. maxColor = Math.max(g, maxColor);
  84189. maxColor = Math.max(b, maxColor);
  84190. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  84191. if (tempData) {
  84192. tempData[pixelStorageIndex + 0] = r;
  84193. tempData[pixelStorageIndex + 1] = g;
  84194. tempData[pixelStorageIndex + 2] = b;
  84195. }
  84196. pixelIndexSlice++;
  84197. if (pixelIndexSlice % size == 0) {
  84198. pixelIndexH++;
  84199. pixelIndexSlice = 0;
  84200. if (pixelIndexH % size == 0) {
  84201. pixelIndexW++;
  84202. pixelIndexH = 0;
  84203. }
  84204. }
  84205. }
  84206. }
  84207. if (tempData && data) {
  84208. for (var i = 0; i < tempData.length; i++) {
  84209. if (i > 0 && (i + 1) % 4 === 0) {
  84210. data[i] = 255;
  84211. }
  84212. else {
  84213. var value = tempData[i];
  84214. data[i] = (value / maxColor * 255);
  84215. }
  84216. }
  84217. }
  84218. if (texture.is3D) {
  84219. texture.updateSize(size, size, size);
  84220. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84221. }
  84222. else {
  84223. texture.updateSize(size * size, size);
  84224. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  84225. }
  84226. };
  84227. var scene = this.getScene();
  84228. if (scene) {
  84229. scene._loadFile(this.url, callback);
  84230. }
  84231. else {
  84232. this._engine._loadFile(this.url, callback);
  84233. }
  84234. return this._texture;
  84235. };
  84236. /**
  84237. * Starts the loading process of the texture.
  84238. */
  84239. ColorGradingTexture.prototype.loadTexture = function () {
  84240. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  84241. this.load3dlTexture();
  84242. }
  84243. };
  84244. /**
  84245. * Clones the color gradind texture.
  84246. */
  84247. ColorGradingTexture.prototype.clone = function () {
  84248. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  84249. // Base texture
  84250. newTexture.level = this.level;
  84251. return newTexture;
  84252. };
  84253. /**
  84254. * Called during delayed load for textures.
  84255. */
  84256. ColorGradingTexture.prototype.delayLoad = function () {
  84257. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84258. return;
  84259. }
  84260. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84261. this._texture = this._getFromCache(this.url, true);
  84262. if (!this._texture) {
  84263. this.loadTexture();
  84264. }
  84265. };
  84266. /**
  84267. * Parses a color grading texture serialized by Babylon.
  84268. * @param parsedTexture The texture information being parsedTexture
  84269. * @param scene The scene to load the texture in
  84270. * @param rootUrl The root url of the data assets to load
  84271. * @return A color gradind texture
  84272. */
  84273. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84274. var texture = null;
  84275. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84276. texture = new ColorGradingTexture(parsedTexture.name, scene);
  84277. texture.name = parsedTexture.name;
  84278. texture.level = parsedTexture.level;
  84279. }
  84280. return texture;
  84281. };
  84282. /**
  84283. * Serializes the LUT texture to json format.
  84284. */
  84285. ColorGradingTexture.prototype.serialize = function () {
  84286. if (!this.name) {
  84287. return null;
  84288. }
  84289. var serializationObject = {};
  84290. serializationObject.name = this.name;
  84291. serializationObject.level = this.level;
  84292. serializationObject.customType = "BABYLON.ColorGradingTexture";
  84293. return serializationObject;
  84294. };
  84295. /**
  84296. * Empty line regex stored for GC.
  84297. */
  84298. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  84299. return ColorGradingTexture;
  84300. }(BABYLON.BaseTexture));
  84301. BABYLON.ColorGradingTexture = ColorGradingTexture;
  84302. })(BABYLON || (BABYLON = {}));
  84303. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  84304. var BABYLON;
  84305. (function (BABYLON) {
  84306. /**
  84307. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  84308. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  84309. * 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;
  84310. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  84311. */
  84312. var ColorCurves = /** @class */ (function () {
  84313. function ColorCurves() {
  84314. this._dirty = true;
  84315. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  84316. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  84317. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84318. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  84319. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  84320. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  84321. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  84322. this._globalHue = 30;
  84323. this._globalDensity = 0;
  84324. this._globalSaturation = 0;
  84325. this._globalExposure = 0;
  84326. this._highlightsHue = 30;
  84327. this._highlightsDensity = 0;
  84328. this._highlightsSaturation = 0;
  84329. this._highlightsExposure = 0;
  84330. this._midtonesHue = 30;
  84331. this._midtonesDensity = 0;
  84332. this._midtonesSaturation = 0;
  84333. this._midtonesExposure = 0;
  84334. this._shadowsHue = 30;
  84335. this._shadowsDensity = 0;
  84336. this._shadowsSaturation = 0;
  84337. this._shadowsExposure = 0;
  84338. }
  84339. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  84340. /**
  84341. * Gets the global Hue value.
  84342. * 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).
  84343. */
  84344. get: function () {
  84345. return this._globalHue;
  84346. },
  84347. /**
  84348. * Sets the global Hue value.
  84349. * 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).
  84350. */
  84351. set: function (value) {
  84352. this._globalHue = value;
  84353. this._dirty = true;
  84354. },
  84355. enumerable: true,
  84356. configurable: true
  84357. });
  84358. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  84359. /**
  84360. * Gets the global Density value.
  84361. * 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.
  84362. * Values less than zero provide a filter of opposite hue.
  84363. */
  84364. get: function () {
  84365. return this._globalDensity;
  84366. },
  84367. /**
  84368. * Sets the global Density value.
  84369. * 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.
  84370. * Values less than zero provide a filter of opposite hue.
  84371. */
  84372. set: function (value) {
  84373. this._globalDensity = value;
  84374. this._dirty = true;
  84375. },
  84376. enumerable: true,
  84377. configurable: true
  84378. });
  84379. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  84380. /**
  84381. * Gets the global Saturation value.
  84382. * 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.
  84383. */
  84384. get: function () {
  84385. return this._globalSaturation;
  84386. },
  84387. /**
  84388. * Sets the global Saturation value.
  84389. * 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.
  84390. */
  84391. set: function (value) {
  84392. this._globalSaturation = value;
  84393. this._dirty = true;
  84394. },
  84395. enumerable: true,
  84396. configurable: true
  84397. });
  84398. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  84399. /**
  84400. * Gets the global Exposure value.
  84401. * 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.
  84402. */
  84403. get: function () {
  84404. return this._globalExposure;
  84405. },
  84406. /**
  84407. * Sets the global Exposure value.
  84408. * 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.
  84409. */
  84410. set: function (value) {
  84411. this._globalExposure = value;
  84412. this._dirty = true;
  84413. },
  84414. enumerable: true,
  84415. configurable: true
  84416. });
  84417. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  84418. /**
  84419. * Gets the highlights Hue value.
  84420. * 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).
  84421. */
  84422. get: function () {
  84423. return this._highlightsHue;
  84424. },
  84425. /**
  84426. * Sets the highlights Hue value.
  84427. * 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).
  84428. */
  84429. set: function (value) {
  84430. this._highlightsHue = value;
  84431. this._dirty = true;
  84432. },
  84433. enumerable: true,
  84434. configurable: true
  84435. });
  84436. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  84437. /**
  84438. * Gets the highlights Density value.
  84439. * 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.
  84440. * Values less than zero provide a filter of opposite hue.
  84441. */
  84442. get: function () {
  84443. return this._highlightsDensity;
  84444. },
  84445. /**
  84446. * Sets the highlights Density value.
  84447. * 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.
  84448. * Values less than zero provide a filter of opposite hue.
  84449. */
  84450. set: function (value) {
  84451. this._highlightsDensity = value;
  84452. this._dirty = true;
  84453. },
  84454. enumerable: true,
  84455. configurable: true
  84456. });
  84457. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  84458. /**
  84459. * Gets the highlights Saturation value.
  84460. * 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.
  84461. */
  84462. get: function () {
  84463. return this._highlightsSaturation;
  84464. },
  84465. /**
  84466. * Sets the highlights Saturation value.
  84467. * 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.
  84468. */
  84469. set: function (value) {
  84470. this._highlightsSaturation = value;
  84471. this._dirty = true;
  84472. },
  84473. enumerable: true,
  84474. configurable: true
  84475. });
  84476. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  84477. /**
  84478. * Gets the highlights Exposure value.
  84479. * 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.
  84480. */
  84481. get: function () {
  84482. return this._highlightsExposure;
  84483. },
  84484. /**
  84485. * Sets the highlights Exposure value.
  84486. * 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.
  84487. */
  84488. set: function (value) {
  84489. this._highlightsExposure = value;
  84490. this._dirty = true;
  84491. },
  84492. enumerable: true,
  84493. configurable: true
  84494. });
  84495. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  84496. /**
  84497. * Gets the midtones Hue value.
  84498. * 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).
  84499. */
  84500. get: function () {
  84501. return this._midtonesHue;
  84502. },
  84503. /**
  84504. * Sets the midtones Hue value.
  84505. * 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).
  84506. */
  84507. set: function (value) {
  84508. this._midtonesHue = value;
  84509. this._dirty = true;
  84510. },
  84511. enumerable: true,
  84512. configurable: true
  84513. });
  84514. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  84515. /**
  84516. * Gets the midtones Density value.
  84517. * 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.
  84518. * Values less than zero provide a filter of opposite hue.
  84519. */
  84520. get: function () {
  84521. return this._midtonesDensity;
  84522. },
  84523. /**
  84524. * Sets the midtones Density value.
  84525. * 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.
  84526. * Values less than zero provide a filter of opposite hue.
  84527. */
  84528. set: function (value) {
  84529. this._midtonesDensity = value;
  84530. this._dirty = true;
  84531. },
  84532. enumerable: true,
  84533. configurable: true
  84534. });
  84535. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  84536. /**
  84537. * Gets the midtones Saturation value.
  84538. * 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.
  84539. */
  84540. get: function () {
  84541. return this._midtonesSaturation;
  84542. },
  84543. /**
  84544. * Sets the midtones Saturation value.
  84545. * 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.
  84546. */
  84547. set: function (value) {
  84548. this._midtonesSaturation = value;
  84549. this._dirty = true;
  84550. },
  84551. enumerable: true,
  84552. configurable: true
  84553. });
  84554. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  84555. /**
  84556. * Gets the midtones Exposure value.
  84557. * 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.
  84558. */
  84559. get: function () {
  84560. return this._midtonesExposure;
  84561. },
  84562. /**
  84563. * Sets the midtones Exposure value.
  84564. * 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.
  84565. */
  84566. set: function (value) {
  84567. this._midtonesExposure = value;
  84568. this._dirty = true;
  84569. },
  84570. enumerable: true,
  84571. configurable: true
  84572. });
  84573. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  84574. /**
  84575. * Gets the shadows Hue value.
  84576. * 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).
  84577. */
  84578. get: function () {
  84579. return this._shadowsHue;
  84580. },
  84581. /**
  84582. * Sets the shadows Hue value.
  84583. * 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).
  84584. */
  84585. set: function (value) {
  84586. this._shadowsHue = value;
  84587. this._dirty = true;
  84588. },
  84589. enumerable: true,
  84590. configurable: true
  84591. });
  84592. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  84593. /**
  84594. * Gets the shadows Density value.
  84595. * 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.
  84596. * Values less than zero provide a filter of opposite hue.
  84597. */
  84598. get: function () {
  84599. return this._shadowsDensity;
  84600. },
  84601. /**
  84602. * Sets the shadows Density value.
  84603. * 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.
  84604. * Values less than zero provide a filter of opposite hue.
  84605. */
  84606. set: function (value) {
  84607. this._shadowsDensity = value;
  84608. this._dirty = true;
  84609. },
  84610. enumerable: true,
  84611. configurable: true
  84612. });
  84613. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  84614. /**
  84615. * Gets the shadows Saturation value.
  84616. * 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.
  84617. */
  84618. get: function () {
  84619. return this._shadowsSaturation;
  84620. },
  84621. /**
  84622. * Sets the shadows Saturation value.
  84623. * 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.
  84624. */
  84625. set: function (value) {
  84626. this._shadowsSaturation = value;
  84627. this._dirty = true;
  84628. },
  84629. enumerable: true,
  84630. configurable: true
  84631. });
  84632. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  84633. /**
  84634. * Gets the shadows Exposure value.
  84635. * 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.
  84636. */
  84637. get: function () {
  84638. return this._shadowsExposure;
  84639. },
  84640. /**
  84641. * Sets the shadows Exposure value.
  84642. * 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.
  84643. */
  84644. set: function (value) {
  84645. this._shadowsExposure = value;
  84646. this._dirty = true;
  84647. },
  84648. enumerable: true,
  84649. configurable: true
  84650. });
  84651. ColorCurves.prototype.getClassName = function () {
  84652. return "ColorCurves";
  84653. };
  84654. /**
  84655. * Binds the color curves to the shader.
  84656. * @param colorCurves The color curve to bind
  84657. * @param effect The effect to bind to
  84658. */
  84659. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  84660. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  84661. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  84662. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  84663. if (colorCurves._dirty) {
  84664. colorCurves._dirty = false;
  84665. // Fill in global info.
  84666. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  84667. // Compute highlights info.
  84668. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  84669. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  84670. // Compute midtones info.
  84671. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  84672. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  84673. // Compute shadows info.
  84674. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  84675. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  84676. // Compute deltas (neutral is midtones).
  84677. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  84678. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  84679. }
  84680. if (effect) {
  84681. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  84682. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  84683. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  84684. }
  84685. };
  84686. /**
  84687. * Prepare the list of uniforms associated with the ColorCurves effects.
  84688. * @param uniformsList The list of uniforms used in the effect
  84689. */
  84690. ColorCurves.PrepareUniforms = function (uniformsList) {
  84691. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  84692. };
  84693. /**
  84694. * Returns color grading data based on a hue, density, saturation and exposure value.
  84695. * @param filterHue The hue of the color filter.
  84696. * @param filterDensity The density of the color filter.
  84697. * @param saturation The saturation.
  84698. * @param exposure The exposure.
  84699. * @param result The result data container.
  84700. */
  84701. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  84702. if (hue == null) {
  84703. return;
  84704. }
  84705. hue = ColorCurves.clamp(hue, 0, 360);
  84706. density = ColorCurves.clamp(density, -100, 100);
  84707. saturation = ColorCurves.clamp(saturation, -100, 100);
  84708. exposure = ColorCurves.clamp(exposure, -100, 100);
  84709. // Remap the slider/config filter density with non-linear mapping and also scale by half
  84710. // so that the maximum filter density is only 50% control. This provides fine control
  84711. // for small values and reasonable range.
  84712. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  84713. density *= 0.5;
  84714. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  84715. if (density < 0) {
  84716. density *= -1;
  84717. hue = (hue + 180) % 360;
  84718. }
  84719. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  84720. result.scaleToRef(2, result);
  84721. result.a = 1 + 0.01 * saturation;
  84722. };
  84723. /**
  84724. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  84725. * @param value The input slider value in range [-100,100].
  84726. * @returns Adjusted value.
  84727. */
  84728. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  84729. value /= 100;
  84730. var x = Math.abs(value);
  84731. x = Math.pow(x, 2);
  84732. if (value < 0) {
  84733. x *= -1;
  84734. }
  84735. x *= 100;
  84736. return x;
  84737. };
  84738. /**
  84739. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  84740. * @param hue The hue (H) input.
  84741. * @param saturation The saturation (S) input.
  84742. * @param brightness The brightness (B) input.
  84743. * @result An RGBA color represented as Vector4.
  84744. */
  84745. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  84746. var h = ColorCurves.clamp(hue, 0, 360);
  84747. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  84748. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  84749. if (s === 0) {
  84750. result.r = v;
  84751. result.g = v;
  84752. result.b = v;
  84753. }
  84754. else {
  84755. // sector 0 to 5
  84756. h /= 60;
  84757. var i = Math.floor(h);
  84758. // fractional part of h
  84759. var f = h - i;
  84760. var p = v * (1 - s);
  84761. var q = v * (1 - s * f);
  84762. var t = v * (1 - s * (1 - f));
  84763. switch (i) {
  84764. case 0:
  84765. result.r = v;
  84766. result.g = t;
  84767. result.b = p;
  84768. break;
  84769. case 1:
  84770. result.r = q;
  84771. result.g = v;
  84772. result.b = p;
  84773. break;
  84774. case 2:
  84775. result.r = p;
  84776. result.g = v;
  84777. result.b = t;
  84778. break;
  84779. case 3:
  84780. result.r = p;
  84781. result.g = q;
  84782. result.b = v;
  84783. break;
  84784. case 4:
  84785. result.r = t;
  84786. result.g = p;
  84787. result.b = v;
  84788. break;
  84789. default: // case 5:
  84790. result.r = v;
  84791. result.g = p;
  84792. result.b = q;
  84793. break;
  84794. }
  84795. }
  84796. result.a = 1;
  84797. };
  84798. /**
  84799. * Returns a value clamped between min and max
  84800. * @param value The value to clamp
  84801. * @param min The minimum of value
  84802. * @param max The maximum of value
  84803. * @returns The clamped value.
  84804. */
  84805. ColorCurves.clamp = function (value, min, max) {
  84806. return Math.min(Math.max(value, min), max);
  84807. };
  84808. /**
  84809. * Clones the current color curve instance.
  84810. * @return The cloned curves
  84811. */
  84812. ColorCurves.prototype.clone = function () {
  84813. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  84814. };
  84815. /**
  84816. * Serializes the current color curve instance to a json representation.
  84817. * @return a JSON representation
  84818. */
  84819. ColorCurves.prototype.serialize = function () {
  84820. return BABYLON.SerializationHelper.Serialize(this);
  84821. };
  84822. /**
  84823. * Parses the color curve from a json representation.
  84824. * @param source the JSON source to parse
  84825. * @return The parsed curves
  84826. */
  84827. ColorCurves.Parse = function (source) {
  84828. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  84829. };
  84830. __decorate([
  84831. BABYLON.serialize()
  84832. ], ColorCurves.prototype, "_globalHue", void 0);
  84833. __decorate([
  84834. BABYLON.serialize()
  84835. ], ColorCurves.prototype, "_globalDensity", void 0);
  84836. __decorate([
  84837. BABYLON.serialize()
  84838. ], ColorCurves.prototype, "_globalSaturation", void 0);
  84839. __decorate([
  84840. BABYLON.serialize()
  84841. ], ColorCurves.prototype, "_globalExposure", void 0);
  84842. __decorate([
  84843. BABYLON.serialize()
  84844. ], ColorCurves.prototype, "_highlightsHue", void 0);
  84845. __decorate([
  84846. BABYLON.serialize()
  84847. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  84848. __decorate([
  84849. BABYLON.serialize()
  84850. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  84851. __decorate([
  84852. BABYLON.serialize()
  84853. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  84854. __decorate([
  84855. BABYLON.serialize()
  84856. ], ColorCurves.prototype, "_midtonesHue", void 0);
  84857. __decorate([
  84858. BABYLON.serialize()
  84859. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  84860. __decorate([
  84861. BABYLON.serialize()
  84862. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  84863. __decorate([
  84864. BABYLON.serialize()
  84865. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  84866. return ColorCurves;
  84867. }());
  84868. BABYLON.ColorCurves = ColorCurves;
  84869. })(BABYLON || (BABYLON = {}));
  84870. //# sourceMappingURL=babylon.colorCurves.js.map
  84871. var BABYLON;
  84872. (function (BABYLON) {
  84873. var RefractionPostProcess = /** @class */ (function (_super) {
  84874. __extends(RefractionPostProcess, _super);
  84875. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  84876. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  84877. _this.color = color;
  84878. _this.depth = depth;
  84879. _this.colorLevel = colorLevel;
  84880. _this._ownRefractionTexture = true;
  84881. _this.onActivateObservable.add(function (cam) {
  84882. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  84883. });
  84884. _this.onApplyObservable.add(function (effect) {
  84885. effect.setColor3("baseColor", _this.color);
  84886. effect.setFloat("depth", _this.depth);
  84887. effect.setFloat("colorLevel", _this.colorLevel);
  84888. effect.setTexture("refractionSampler", _this._refTexture);
  84889. });
  84890. return _this;
  84891. }
  84892. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  84893. /**
  84894. * Gets or sets the refraction texture
  84895. * Please note that you are responsible for disposing the texture if you set it manually
  84896. */
  84897. get: function () {
  84898. return this._refTexture;
  84899. },
  84900. set: function (value) {
  84901. if (this._refTexture && this._ownRefractionTexture) {
  84902. this._refTexture.dispose();
  84903. }
  84904. this._refTexture = value;
  84905. this._ownRefractionTexture = false;
  84906. },
  84907. enumerable: true,
  84908. configurable: true
  84909. });
  84910. // Methods
  84911. RefractionPostProcess.prototype.dispose = function (camera) {
  84912. if (this._refTexture && this._ownRefractionTexture) {
  84913. this._refTexture.dispose();
  84914. this._refTexture = null;
  84915. }
  84916. _super.prototype.dispose.call(this, camera);
  84917. };
  84918. return RefractionPostProcess;
  84919. }(BABYLON.PostProcess));
  84920. BABYLON.RefractionPostProcess = RefractionPostProcess;
  84921. })(BABYLON || (BABYLON = {}));
  84922. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  84923. var BABYLON;
  84924. (function (BABYLON) {
  84925. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  84926. __extends(BlackAndWhitePostProcess, _super);
  84927. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  84928. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  84929. _this.degree = 1;
  84930. _this.onApplyObservable.add(function (effect) {
  84931. effect.setFloat("degree", _this.degree);
  84932. });
  84933. return _this;
  84934. }
  84935. return BlackAndWhitePostProcess;
  84936. }(BABYLON.PostProcess));
  84937. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  84938. })(BABYLON || (BABYLON = {}));
  84939. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  84940. var BABYLON;
  84941. (function (BABYLON) {
  84942. /**
  84943. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  84944. * input texture to perform effects such as edge detection or sharpening
  84945. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  84946. */
  84947. var ConvolutionPostProcess = /** @class */ (function (_super) {
  84948. __extends(ConvolutionPostProcess, _super);
  84949. /**
  84950. * Creates a new instance ConvolutionPostProcess
  84951. * @param name The name of the effect.
  84952. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  84953. * @param options The required width/height ratio to downsize to before computing the render pass.
  84954. * @param camera The camera to apply the render pass to.
  84955. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  84956. * @param engine The engine which the post process will be applied. (default: current engine)
  84957. * @param reusable If the post process can be reused on the same frame. (default: false)
  84958. * @param textureType Type of textures used when performing the post process. (default: 0)
  84959. */
  84960. function ConvolutionPostProcess(name,
  84961. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  84962. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  84963. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  84964. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  84965. _this.kernel = kernel;
  84966. _this.onApply = function (effect) {
  84967. effect.setFloat2("screenSize", _this.width, _this.height);
  84968. effect.setArray("kernel", _this.kernel);
  84969. };
  84970. return _this;
  84971. }
  84972. // Statics
  84973. /**
  84974. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  84975. */
  84976. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  84977. /**
  84978. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  84979. */
  84980. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  84981. /**
  84982. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  84983. */
  84984. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  84985. /**
  84986. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  84987. */
  84988. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  84989. /**
  84990. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  84991. */
  84992. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  84993. /**
  84994. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  84995. */
  84996. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  84997. return ConvolutionPostProcess;
  84998. }(BABYLON.PostProcess));
  84999. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  85000. })(BABYLON || (BABYLON = {}));
  85001. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  85002. var BABYLON;
  85003. (function (BABYLON) {
  85004. var FilterPostProcess = /** @class */ (function (_super) {
  85005. __extends(FilterPostProcess, _super);
  85006. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  85007. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  85008. _this.kernelMatrix = kernelMatrix;
  85009. _this.onApply = function (effect) {
  85010. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  85011. };
  85012. return _this;
  85013. }
  85014. return FilterPostProcess;
  85015. }(BABYLON.PostProcess));
  85016. BABYLON.FilterPostProcess = FilterPostProcess;
  85017. })(BABYLON || (BABYLON = {}));
  85018. //# sourceMappingURL=babylon.filterPostProcess.js.map
  85019. var BABYLON;
  85020. (function (BABYLON) {
  85021. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  85022. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  85023. __extends(VolumetricLightScatteringPostProcess, _super);
  85024. /**
  85025. * @constructor
  85026. * @param {string} name - The post-process name
  85027. * @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)
  85028. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  85029. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  85030. * @param {number} samples - The post-process quality, default 100
  85031. * @param {number} samplingMode - The post-process filtering mode
  85032. * @param {BABYLON.Engine} engine - The babylon engine
  85033. * @param {boolean} reusable - If the post-process is reusable
  85034. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  85035. */
  85036. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  85037. if (samples === void 0) { samples = 100; }
  85038. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85039. 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;
  85040. _this._screenCoordinates = BABYLON.Vector2.Zero();
  85041. /**
  85042. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  85043. */
  85044. _this.customMeshPosition = BABYLON.Vector3.Zero();
  85045. /**
  85046. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  85047. */
  85048. _this.useCustomMeshPosition = false;
  85049. /**
  85050. * If the post-process should inverse the light scattering direction
  85051. */
  85052. _this.invert = true;
  85053. /**
  85054. * Array containing the excluded meshes not rendered in the internal pass
  85055. */
  85056. _this.excludedMeshes = new Array();
  85057. /**
  85058. * Controls the overall intensity of the post-process
  85059. */
  85060. _this.exposure = 0.3;
  85061. /**
  85062. * Dissipates each sample's contribution in range [0, 1]
  85063. */
  85064. _this.decay = 0.96815;
  85065. /**
  85066. * Controls the overall intensity of each sample
  85067. */
  85068. _this.weight = 0.58767;
  85069. /**
  85070. * Controls the density of each sample
  85071. */
  85072. _this.density = 0.926;
  85073. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  85074. engine = scene.getEngine();
  85075. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  85076. // Configure mesh
  85077. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  85078. // Configure
  85079. _this._createPass(scene, ratio.passRatio || ratio);
  85080. _this.onActivate = function (camera) {
  85081. if (!_this.isSupported) {
  85082. _this.dispose(camera);
  85083. }
  85084. _this.onActivate = null;
  85085. };
  85086. _this.onApplyObservable.add(function (effect) {
  85087. _this._updateMeshScreenCoordinates(scene);
  85088. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  85089. effect.setFloat("exposure", _this.exposure);
  85090. effect.setFloat("decay", _this.decay);
  85091. effect.setFloat("weight", _this.weight);
  85092. effect.setFloat("density", _this.density);
  85093. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  85094. });
  85095. return _this;
  85096. }
  85097. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  85098. get: function () {
  85099. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85100. return false;
  85101. },
  85102. set: function (useDiffuseColor) {
  85103. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  85104. },
  85105. enumerable: true,
  85106. configurable: true
  85107. });
  85108. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  85109. return "VolumetricLightScatteringPostProcess";
  85110. };
  85111. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  85112. var mesh = subMesh.getMesh();
  85113. // Render this.mesh as default
  85114. if (mesh === this.mesh && mesh.material) {
  85115. return mesh.material.isReady(mesh);
  85116. }
  85117. var defines = [];
  85118. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85119. var material = subMesh.getMaterial();
  85120. // Alpha test
  85121. if (material) {
  85122. if (material.needAlphaTesting()) {
  85123. defines.push("#define ALPHATEST");
  85124. }
  85125. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85126. attribs.push(BABYLON.VertexBuffer.UVKind);
  85127. defines.push("#define UV1");
  85128. }
  85129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85130. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85131. defines.push("#define UV2");
  85132. }
  85133. }
  85134. // Bones
  85135. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85136. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85137. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85138. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85139. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85140. }
  85141. else {
  85142. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85143. }
  85144. // Instances
  85145. if (useInstances) {
  85146. defines.push("#define INSTANCES");
  85147. attribs.push("world0");
  85148. attribs.push("world1");
  85149. attribs.push("world2");
  85150. attribs.push("world3");
  85151. }
  85152. // Get correct effect
  85153. var join = defines.join("\n");
  85154. if (this._cachedDefines !== join) {
  85155. this._cachedDefines = join;
  85156. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  85157. }
  85158. return this._volumetricLightScatteringPass.isReady();
  85159. };
  85160. /**
  85161. * Sets the new light position for light scattering effect
  85162. * @param {BABYLON.Vector3} The new custom light position
  85163. */
  85164. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  85165. this.customMeshPosition = position;
  85166. };
  85167. /**
  85168. * Returns the light position for light scattering effect
  85169. * @return {BABYLON.Vector3} The custom light position
  85170. */
  85171. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  85172. return this.customMeshPosition;
  85173. };
  85174. /**
  85175. * Disposes the internal assets and detaches the post-process from the camera
  85176. */
  85177. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  85178. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  85179. if (rttIndex !== -1) {
  85180. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  85181. }
  85182. this._volumetricLightScatteringRTT.dispose();
  85183. _super.prototype.dispose.call(this, camera);
  85184. };
  85185. /**
  85186. * Returns the render target texture used by the post-process
  85187. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  85188. */
  85189. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  85190. return this._volumetricLightScatteringRTT;
  85191. };
  85192. // Private methods
  85193. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  85194. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  85195. return true;
  85196. }
  85197. return false;
  85198. };
  85199. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  85200. var _this = this;
  85201. var engine = scene.getEngine();
  85202. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85203. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85204. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85205. this._volumetricLightScatteringRTT.renderList = null;
  85206. this._volumetricLightScatteringRTT.renderParticles = false;
  85207. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  85208. var camera = this.getCamera();
  85209. if (camera) {
  85210. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85211. }
  85212. else {
  85213. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  85214. }
  85215. // Custom render function for submeshes
  85216. var renderSubMesh = function (subMesh) {
  85217. var mesh = subMesh.getRenderingMesh();
  85218. if (_this._meshExcluded(mesh)) {
  85219. return;
  85220. }
  85221. var material = subMesh.getMaterial();
  85222. if (!material) {
  85223. return;
  85224. }
  85225. var scene = mesh.getScene();
  85226. var engine = scene.getEngine();
  85227. // Culling
  85228. engine.setState(material.backFaceCulling);
  85229. // Managing instances
  85230. var batch = mesh._getInstancesRenderList(subMesh._id);
  85231. if (batch.mustReturn) {
  85232. return;
  85233. }
  85234. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  85235. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  85236. var effect = _this._volumetricLightScatteringPass;
  85237. if (mesh === _this.mesh) {
  85238. if (subMesh.effect) {
  85239. effect = subMesh.effect;
  85240. }
  85241. else {
  85242. effect = material.getEffect();
  85243. }
  85244. }
  85245. engine.enableEffect(effect);
  85246. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  85247. if (mesh === _this.mesh) {
  85248. material.bind(mesh.getWorldMatrix(), mesh);
  85249. }
  85250. else {
  85251. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  85252. // Alpha test
  85253. if (material && material.needAlphaTesting()) {
  85254. var alphaTexture = material.getAlphaTestTexture();
  85255. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  85256. if (alphaTexture) {
  85257. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85258. }
  85259. }
  85260. // Bones
  85261. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85262. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85263. }
  85264. }
  85265. // Draw
  85266. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  85267. }
  85268. };
  85269. // Render target texture callbacks
  85270. var savedSceneClearColor;
  85271. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  85272. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  85273. savedSceneClearColor = scene.clearColor;
  85274. scene.clearColor = sceneClearColor;
  85275. });
  85276. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  85277. scene.clearColor = savedSceneClearColor;
  85278. });
  85279. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85280. var engine = scene.getEngine();
  85281. var index;
  85282. if (depthOnlySubMeshes.length) {
  85283. engine.setColorWrite(false);
  85284. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85285. renderSubMesh(depthOnlySubMeshes.data[index]);
  85286. }
  85287. engine.setColorWrite(true);
  85288. }
  85289. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85290. renderSubMesh(opaqueSubMeshes.data[index]);
  85291. }
  85292. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85293. renderSubMesh(alphaTestSubMeshes.data[index]);
  85294. }
  85295. if (transparentSubMeshes.length) {
  85296. // Sort sub meshes
  85297. for (index = 0; index < transparentSubMeshes.length; index++) {
  85298. var submesh = transparentSubMeshes.data[index];
  85299. var boundingInfo = submesh.getBoundingInfo();
  85300. if (boundingInfo && scene.activeCamera) {
  85301. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  85302. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  85303. }
  85304. }
  85305. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  85306. sortedArray.sort(function (a, b) {
  85307. // Alpha index first
  85308. if (a._alphaIndex > b._alphaIndex) {
  85309. return 1;
  85310. }
  85311. if (a._alphaIndex < b._alphaIndex) {
  85312. return -1;
  85313. }
  85314. // Then distance to camera
  85315. if (a._distanceToCamera < b._distanceToCamera) {
  85316. return 1;
  85317. }
  85318. if (a._distanceToCamera > b._distanceToCamera) {
  85319. return -1;
  85320. }
  85321. return 0;
  85322. });
  85323. // Render sub meshes
  85324. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  85325. for (index = 0; index < sortedArray.length; index++) {
  85326. renderSubMesh(sortedArray[index]);
  85327. }
  85328. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85329. }
  85330. };
  85331. };
  85332. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  85333. var transform = scene.getTransformMatrix();
  85334. var meshPosition;
  85335. if (this.useCustomMeshPosition) {
  85336. meshPosition = this.customMeshPosition;
  85337. }
  85338. else if (this.attachedNode) {
  85339. meshPosition = this.attachedNode.position;
  85340. }
  85341. else {
  85342. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  85343. }
  85344. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  85345. this._screenCoordinates.x = pos.x / this._viewPort.width;
  85346. this._screenCoordinates.y = pos.y / this._viewPort.height;
  85347. if (this.invert)
  85348. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  85349. };
  85350. // Static methods
  85351. /**
  85352. * Creates a default mesh for the Volumeric Light Scattering post-process
  85353. * @param {string} The mesh name
  85354. * @param {BABYLON.Scene} The scene where to create the mesh
  85355. * @return {BABYLON.Mesh} the default mesh
  85356. */
  85357. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  85358. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  85359. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  85360. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  85361. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  85362. mesh.material = material;
  85363. return mesh;
  85364. };
  85365. __decorate([
  85366. BABYLON.serializeAsVector3()
  85367. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  85368. __decorate([
  85369. BABYLON.serialize()
  85370. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  85371. __decorate([
  85372. BABYLON.serialize()
  85373. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  85374. __decorate([
  85375. BABYLON.serializeAsMeshReference()
  85376. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  85377. __decorate([
  85378. BABYLON.serialize()
  85379. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  85380. __decorate([
  85381. BABYLON.serialize()
  85382. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  85383. __decorate([
  85384. BABYLON.serialize()
  85385. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  85386. __decorate([
  85387. BABYLON.serialize()
  85388. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  85389. __decorate([
  85390. BABYLON.serialize()
  85391. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  85392. return VolumetricLightScatteringPostProcess;
  85393. }(BABYLON.PostProcess));
  85394. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  85395. })(BABYLON || (BABYLON = {}));
  85396. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  85397. //
  85398. // This post-process allows the modification of rendered colors by using
  85399. // a 'look-up table' (LUT). This effect is also called Color Grading.
  85400. //
  85401. // The object needs to be provided an url to a texture containing the color
  85402. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  85403. // Use an image editing software to tweak the LUT to match your needs.
  85404. //
  85405. // For an example of a color LUT, see here:
  85406. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  85407. // For explanations on color grading, see here:
  85408. // http://udn.epicgames.com/Three/ColorGrading.html
  85409. //
  85410. var BABYLON;
  85411. (function (BABYLON) {
  85412. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  85413. __extends(ColorCorrectionPostProcess, _super);
  85414. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  85415. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  85416. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  85417. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  85418. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85419. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85420. _this.onApply = function (effect) {
  85421. effect.setTexture("colorTable", _this._colorTableTexture);
  85422. };
  85423. return _this;
  85424. }
  85425. return ColorCorrectionPostProcess;
  85426. }(BABYLON.PostProcess));
  85427. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  85428. })(BABYLON || (BABYLON = {}));
  85429. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  85430. var BABYLON;
  85431. (function (BABYLON) {
  85432. /** Defines operator used for tonemapping */
  85433. var TonemappingOperator;
  85434. (function (TonemappingOperator) {
  85435. /** Hable */
  85436. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  85437. /** Reinhard */
  85438. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  85439. /** HejiDawson */
  85440. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  85441. /** Photographic */
  85442. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  85443. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  85444. ;
  85445. /**
  85446. * Defines a post process to apply tone mapping
  85447. */
  85448. var TonemapPostProcess = /** @class */ (function (_super) {
  85449. __extends(TonemapPostProcess, _super);
  85450. /**
  85451. * Creates a new TonemapPostProcess
  85452. * @param name defines the name of the postprocess
  85453. * @param _operator defines the operator to use
  85454. * @param exposureAdjustment defines the required exposure adjustement
  85455. * @param camera defines the camera to use (can be null)
  85456. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  85457. * @param engine defines the hosting engine (can be ignore if camera is set)
  85458. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  85459. */
  85460. function TonemapPostProcess(name, _operator,
  85461. /** Defines the required exposure adjustement */
  85462. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  85463. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85464. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85465. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  85466. _this._operator = _operator;
  85467. _this.exposureAdjustment = exposureAdjustment;
  85468. var defines = "#define ";
  85469. if (_this._operator === TonemappingOperator.Hable)
  85470. defines += "HABLE_TONEMAPPING";
  85471. else if (_this._operator === TonemappingOperator.Reinhard)
  85472. defines += "REINHARD_TONEMAPPING";
  85473. else if (_this._operator === TonemappingOperator.HejiDawson)
  85474. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  85475. else if (_this._operator === TonemappingOperator.Photographic)
  85476. defines += "PHOTOGRAPHIC_TONEMAPPING";
  85477. //sadly a second call to create the effect.
  85478. _this.updateEffect(defines);
  85479. _this.onApply = function (effect) {
  85480. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  85481. };
  85482. return _this;
  85483. }
  85484. return TonemapPostProcess;
  85485. }(BABYLON.PostProcess));
  85486. BABYLON.TonemapPostProcess = TonemapPostProcess;
  85487. })(BABYLON || (BABYLON = {}));
  85488. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  85489. var BABYLON;
  85490. (function (BABYLON) {
  85491. var DisplayPassPostProcess = /** @class */ (function (_super) {
  85492. __extends(DisplayPassPostProcess, _super);
  85493. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  85494. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  85495. }
  85496. return DisplayPassPostProcess;
  85497. }(BABYLON.PostProcess));
  85498. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  85499. })(BABYLON || (BABYLON = {}));
  85500. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  85501. var BABYLON;
  85502. (function (BABYLON) {
  85503. var HighlightsPostProcess = /** @class */ (function (_super) {
  85504. __extends(HighlightsPostProcess, _super);
  85505. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85506. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85507. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  85508. }
  85509. return HighlightsPostProcess;
  85510. }(BABYLON.PostProcess));
  85511. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  85512. })(BABYLON || (BABYLON = {}));
  85513. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  85514. var BABYLON;
  85515. (function (BABYLON) {
  85516. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  85517. __extends(ImageProcessingPostProcess, _super);
  85518. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  85519. if (camera === void 0) { camera = null; }
  85520. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85521. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  85522. _this._fromLinearSpace = true;
  85523. /**
  85524. * Defines cache preventing GC.
  85525. */
  85526. _this._defines = {
  85527. IMAGEPROCESSING: false,
  85528. VIGNETTE: false,
  85529. VIGNETTEBLENDMODEMULTIPLY: false,
  85530. VIGNETTEBLENDMODEOPAQUE: false,
  85531. TONEMAPPING: false,
  85532. TONEMAPPING_ACES: false,
  85533. CONTRAST: false,
  85534. COLORCURVES: false,
  85535. COLORGRADING: false,
  85536. COLORGRADING3D: false,
  85537. FROMLINEARSPACE: false,
  85538. SAMPLER3DGREENDEPTH: false,
  85539. SAMPLER3DBGRMAP: false,
  85540. IMAGEPROCESSINGPOSTPROCESS: false,
  85541. EXPOSURE: false,
  85542. };
  85543. // Setup the configuration as forced by the constructor. This would then not force the
  85544. // scene materials output in linear space and let untouched the default forward pass.
  85545. if (imageProcessingConfiguration) {
  85546. imageProcessingConfiguration.applyByPostProcess = true;
  85547. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  85548. // This will cause the shader to be compiled
  85549. _this.fromLinearSpace = false;
  85550. }
  85551. // Setup the default processing configuration to the scene.
  85552. else {
  85553. _this._attachImageProcessingConfiguration(null, true);
  85554. _this.imageProcessingConfiguration.applyByPostProcess = true;
  85555. }
  85556. _this.onApply = function (effect) {
  85557. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  85558. };
  85559. return _this;
  85560. }
  85561. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  85562. /**
  85563. * Gets the image processing configuration used either in this material.
  85564. */
  85565. get: function () {
  85566. return this._imageProcessingConfiguration;
  85567. },
  85568. /**
  85569. * Sets the Default image processing configuration used either in the this material.
  85570. *
  85571. * If sets to null, the scene one is in use.
  85572. */
  85573. set: function (value) {
  85574. this._attachImageProcessingConfiguration(value);
  85575. },
  85576. enumerable: true,
  85577. configurable: true
  85578. });
  85579. /**
  85580. * Attaches a new image processing configuration to the PBR Material.
  85581. * @param configuration
  85582. */
  85583. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  85584. var _this = this;
  85585. if (doNotBuild === void 0) { doNotBuild = false; }
  85586. if (configuration === this._imageProcessingConfiguration) {
  85587. return;
  85588. }
  85589. // Detaches observer.
  85590. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85591. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85592. }
  85593. // Pick the scene configuration if needed.
  85594. if (!configuration) {
  85595. var scene = null;
  85596. var engine = this.getEngine();
  85597. var camera = this.getCamera();
  85598. if (camera) {
  85599. scene = camera.getScene();
  85600. }
  85601. else if (engine && engine.scenes) {
  85602. var scenes = engine.scenes;
  85603. scene = scenes[scenes.length - 1];
  85604. }
  85605. else {
  85606. scene = BABYLON.Engine.LastCreatedScene;
  85607. }
  85608. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  85609. }
  85610. else {
  85611. this._imageProcessingConfiguration = configuration;
  85612. }
  85613. // Attaches observer.
  85614. if (this._imageProcessingConfiguration) {
  85615. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  85616. _this._updateParameters();
  85617. });
  85618. }
  85619. // Ensure the effect will be rebuilt.
  85620. if (!doNotBuild) {
  85621. this._updateParameters();
  85622. }
  85623. };
  85624. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  85625. /**
  85626. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  85627. */
  85628. get: function () {
  85629. return this.imageProcessingConfiguration.colorCurves;
  85630. },
  85631. /**
  85632. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  85633. */
  85634. set: function (value) {
  85635. this.imageProcessingConfiguration.colorCurves = value;
  85636. },
  85637. enumerable: true,
  85638. configurable: true
  85639. });
  85640. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  85641. /**
  85642. * Gets wether the color curves effect is enabled.
  85643. */
  85644. get: function () {
  85645. return this.imageProcessingConfiguration.colorCurvesEnabled;
  85646. },
  85647. /**
  85648. * Sets wether the color curves effect is enabled.
  85649. */
  85650. set: function (value) {
  85651. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  85652. },
  85653. enumerable: true,
  85654. configurable: true
  85655. });
  85656. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  85657. /**
  85658. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  85659. */
  85660. get: function () {
  85661. return this.imageProcessingConfiguration.colorGradingTexture;
  85662. },
  85663. /**
  85664. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  85665. */
  85666. set: function (value) {
  85667. this.imageProcessingConfiguration.colorGradingTexture = value;
  85668. },
  85669. enumerable: true,
  85670. configurable: true
  85671. });
  85672. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  85673. /**
  85674. * Gets wether the color grading effect is enabled.
  85675. */
  85676. get: function () {
  85677. return this.imageProcessingConfiguration.colorGradingEnabled;
  85678. },
  85679. /**
  85680. * Gets wether the color grading effect is enabled.
  85681. */
  85682. set: function (value) {
  85683. this.imageProcessingConfiguration.colorGradingEnabled = value;
  85684. },
  85685. enumerable: true,
  85686. configurable: true
  85687. });
  85688. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  85689. /**
  85690. * Gets exposure used in the effect.
  85691. */
  85692. get: function () {
  85693. return this.imageProcessingConfiguration.exposure;
  85694. },
  85695. /**
  85696. * Sets exposure used in the effect.
  85697. */
  85698. set: function (value) {
  85699. this.imageProcessingConfiguration.exposure = value;
  85700. },
  85701. enumerable: true,
  85702. configurable: true
  85703. });
  85704. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  85705. /**
  85706. * Gets wether tonemapping is enabled or not.
  85707. */
  85708. get: function () {
  85709. return this._imageProcessingConfiguration.toneMappingEnabled;
  85710. },
  85711. /**
  85712. * Sets wether tonemapping is enabled or not
  85713. */
  85714. set: function (value) {
  85715. this._imageProcessingConfiguration.toneMappingEnabled = value;
  85716. },
  85717. enumerable: true,
  85718. configurable: true
  85719. });
  85720. ;
  85721. ;
  85722. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  85723. /**
  85724. * Gets contrast used in the effect.
  85725. */
  85726. get: function () {
  85727. return this.imageProcessingConfiguration.contrast;
  85728. },
  85729. /**
  85730. * Sets contrast used in the effect.
  85731. */
  85732. set: function (value) {
  85733. this.imageProcessingConfiguration.contrast = value;
  85734. },
  85735. enumerable: true,
  85736. configurable: true
  85737. });
  85738. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  85739. /**
  85740. * Gets Vignette stretch size.
  85741. */
  85742. get: function () {
  85743. return this.imageProcessingConfiguration.vignetteStretch;
  85744. },
  85745. /**
  85746. * Sets Vignette stretch size.
  85747. */
  85748. set: function (value) {
  85749. this.imageProcessingConfiguration.vignetteStretch = value;
  85750. },
  85751. enumerable: true,
  85752. configurable: true
  85753. });
  85754. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  85755. /**
  85756. * Gets Vignette centre X Offset.
  85757. */
  85758. get: function () {
  85759. return this.imageProcessingConfiguration.vignetteCentreX;
  85760. },
  85761. /**
  85762. * Sets Vignette centre X Offset.
  85763. */
  85764. set: function (value) {
  85765. this.imageProcessingConfiguration.vignetteCentreX = value;
  85766. },
  85767. enumerable: true,
  85768. configurable: true
  85769. });
  85770. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  85771. /**
  85772. * Gets Vignette centre Y Offset.
  85773. */
  85774. get: function () {
  85775. return this.imageProcessingConfiguration.vignetteCentreY;
  85776. },
  85777. /**
  85778. * Sets Vignette centre Y Offset.
  85779. */
  85780. set: function (value) {
  85781. this.imageProcessingConfiguration.vignetteCentreY = value;
  85782. },
  85783. enumerable: true,
  85784. configurable: true
  85785. });
  85786. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  85787. /**
  85788. * Gets Vignette weight or intensity of the vignette effect.
  85789. */
  85790. get: function () {
  85791. return this.imageProcessingConfiguration.vignetteWeight;
  85792. },
  85793. /**
  85794. * Sets Vignette weight or intensity of the vignette effect.
  85795. */
  85796. set: function (value) {
  85797. this.imageProcessingConfiguration.vignetteWeight = value;
  85798. },
  85799. enumerable: true,
  85800. configurable: true
  85801. });
  85802. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  85803. /**
  85804. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  85805. * if vignetteEnabled is set to true.
  85806. */
  85807. get: function () {
  85808. return this.imageProcessingConfiguration.vignetteColor;
  85809. },
  85810. /**
  85811. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  85812. * if vignetteEnabled is set to true.
  85813. */
  85814. set: function (value) {
  85815. this.imageProcessingConfiguration.vignetteColor = value;
  85816. },
  85817. enumerable: true,
  85818. configurable: true
  85819. });
  85820. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  85821. /**
  85822. * Gets Camera field of view used by the Vignette effect.
  85823. */
  85824. get: function () {
  85825. return this.imageProcessingConfiguration.vignetteCameraFov;
  85826. },
  85827. /**
  85828. * Sets Camera field of view used by the Vignette effect.
  85829. */
  85830. set: function (value) {
  85831. this.imageProcessingConfiguration.vignetteCameraFov = value;
  85832. },
  85833. enumerable: true,
  85834. configurable: true
  85835. });
  85836. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  85837. /**
  85838. * Gets the vignette blend mode allowing different kind of effect.
  85839. */
  85840. get: function () {
  85841. return this.imageProcessingConfiguration.vignetteBlendMode;
  85842. },
  85843. /**
  85844. * Sets the vignette blend mode allowing different kind of effect.
  85845. */
  85846. set: function (value) {
  85847. this.imageProcessingConfiguration.vignetteBlendMode = value;
  85848. },
  85849. enumerable: true,
  85850. configurable: true
  85851. });
  85852. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  85853. /**
  85854. * Gets wether the vignette effect is enabled.
  85855. */
  85856. get: function () {
  85857. return this.imageProcessingConfiguration.vignetteEnabled;
  85858. },
  85859. /**
  85860. * Sets wether the vignette effect is enabled.
  85861. */
  85862. set: function (value) {
  85863. this.imageProcessingConfiguration.vignetteEnabled = value;
  85864. },
  85865. enumerable: true,
  85866. configurable: true
  85867. });
  85868. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  85869. /**
  85870. * Gets wether the input of the processing is in Gamma or Linear Space.
  85871. */
  85872. get: function () {
  85873. return this._fromLinearSpace;
  85874. },
  85875. /**
  85876. * Sets wether the input of the processing is in Gamma or Linear Space.
  85877. */
  85878. set: function (value) {
  85879. if (this._fromLinearSpace === value) {
  85880. return;
  85881. }
  85882. this._fromLinearSpace = value;
  85883. this._updateParameters();
  85884. },
  85885. enumerable: true,
  85886. configurable: true
  85887. });
  85888. ImageProcessingPostProcess.prototype.getClassName = function () {
  85889. return "ImageProcessingPostProcess";
  85890. };
  85891. ImageProcessingPostProcess.prototype._updateParameters = function () {
  85892. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  85893. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  85894. var defines = "";
  85895. for (var define in this._defines) {
  85896. if (this._defines[define]) {
  85897. defines += "#define " + define + ";\r\n";
  85898. }
  85899. }
  85900. var samplers = ["textureSampler"];
  85901. var uniforms = ["scale"];
  85902. if (BABYLON.ImageProcessingConfiguration) {
  85903. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  85904. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  85905. }
  85906. this.updateEffect(defines, uniforms, samplers);
  85907. };
  85908. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  85909. _super.prototype.dispose.call(this, camera);
  85910. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  85911. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  85912. }
  85913. if (this._imageProcessingConfiguration) {
  85914. this.imageProcessingConfiguration.applyByPostProcess = false;
  85915. }
  85916. };
  85917. __decorate([
  85918. BABYLON.serialize()
  85919. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  85920. return ImageProcessingPostProcess;
  85921. }(BABYLON.PostProcess));
  85922. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  85923. })(BABYLON || (BABYLON = {}));
  85924. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  85925. var BABYLON;
  85926. (function (BABYLON) {
  85927. /**
  85928. * Class used to store bone information
  85929. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  85930. */
  85931. var Bone = /** @class */ (function (_super) {
  85932. __extends(Bone, _super);
  85933. /**
  85934. * Create a new bone
  85935. * @param name defines the bone name
  85936. * @param skeleton defines the parent skeleton
  85937. * @param parentBone defines the parent (can be null if the bone is the root)
  85938. * @param localMatrix defines the local matrix
  85939. * @param restPose defines the rest pose matrix
  85940. * @param baseMatrix defines the base matrix
  85941. * @param index defines index of the bone in the hiearchy
  85942. */
  85943. function Bone(
  85944. /**
  85945. * defines the bone name
  85946. */
  85947. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  85948. if (parentBone === void 0) { parentBone = null; }
  85949. if (localMatrix === void 0) { localMatrix = null; }
  85950. if (restPose === void 0) { restPose = null; }
  85951. if (baseMatrix === void 0) { baseMatrix = null; }
  85952. if (index === void 0) { index = null; }
  85953. var _this = _super.call(this, name, skeleton.getScene()) || this;
  85954. _this.name = name;
  85955. /**
  85956. * Gets the list of child bones
  85957. */
  85958. _this.children = new Array();
  85959. /** Gets the animations associated with this bone */
  85960. _this.animations = new Array();
  85961. /**
  85962. * @hidden Internal only
  85963. * Set this value to map this bone to a different index in the transform matrices
  85964. * Set this value to -1 to exclude the bone from the transform matrices
  85965. */
  85966. _this._index = null;
  85967. _this._absoluteTransform = new BABYLON.Matrix();
  85968. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  85969. _this._scalingDeterminant = 1;
  85970. _this._worldTransform = new BABYLON.Matrix();
  85971. _this._needToDecompose = true;
  85972. _this._needToCompose = false;
  85973. _this._skeleton = skeleton;
  85974. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  85975. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  85976. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  85977. _this._index = index;
  85978. skeleton.bones.push(_this);
  85979. _this.setParent(parentBone, false);
  85980. if (baseMatrix || localMatrix) {
  85981. _this._updateDifferenceMatrix();
  85982. }
  85983. return _this;
  85984. }
  85985. Object.defineProperty(Bone.prototype, "_matrix", {
  85986. /** @hidden */
  85987. get: function () {
  85988. this._compose();
  85989. return this._localMatrix;
  85990. },
  85991. /** @hidden */
  85992. set: function (value) {
  85993. this._localMatrix.copyFrom(value);
  85994. this._needToDecompose = true;
  85995. },
  85996. enumerable: true,
  85997. configurable: true
  85998. });
  85999. // Members
  86000. /**
  86001. * Gets the parent skeleton
  86002. * @returns a skeleton
  86003. */
  86004. Bone.prototype.getSkeleton = function () {
  86005. return this._skeleton;
  86006. };
  86007. /**
  86008. * Gets parent bone
  86009. * @returns a bone or null if the bone is the root of the bone hierarchy
  86010. */
  86011. Bone.prototype.getParent = function () {
  86012. return this._parent;
  86013. };
  86014. /**
  86015. * Sets the parent bone
  86016. * @param parent defines the parent (can be null if the bone is the root)
  86017. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86018. */
  86019. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  86020. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86021. if (this._parent === parent) {
  86022. return;
  86023. }
  86024. if (this._parent) {
  86025. var index = this._parent.children.indexOf(this);
  86026. if (index !== -1) {
  86027. this._parent.children.splice(index, 1);
  86028. }
  86029. }
  86030. this._parent = parent;
  86031. if (this._parent) {
  86032. this._parent.children.push(this);
  86033. }
  86034. if (updateDifferenceMatrix) {
  86035. this._updateDifferenceMatrix();
  86036. }
  86037. this.markAsDirty();
  86038. };
  86039. /**
  86040. * Gets the local matrix
  86041. * @returns a matrix
  86042. */
  86043. Bone.prototype.getLocalMatrix = function () {
  86044. this._compose();
  86045. return this._localMatrix;
  86046. };
  86047. /**
  86048. * Gets the base matrix (initial matrix which remains unchanged)
  86049. * @returns a matrix
  86050. */
  86051. Bone.prototype.getBaseMatrix = function () {
  86052. return this._baseMatrix;
  86053. };
  86054. /**
  86055. * Gets the rest pose matrix
  86056. * @returns a matrix
  86057. */
  86058. Bone.prototype.getRestPose = function () {
  86059. return this._restPose;
  86060. };
  86061. /**
  86062. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  86063. */
  86064. Bone.prototype.getWorldMatrix = function () {
  86065. return this._worldTransform;
  86066. };
  86067. /**
  86068. * Sets the local matrix to rest pose matrix
  86069. */
  86070. Bone.prototype.returnToRest = function () {
  86071. this.updateMatrix(this._restPose.clone());
  86072. };
  86073. /**
  86074. * Gets the inverse of the absolute transform matrix.
  86075. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  86076. * @returns a matrix
  86077. */
  86078. Bone.prototype.getInvertedAbsoluteTransform = function () {
  86079. return this._invertedAbsoluteTransform;
  86080. };
  86081. /**
  86082. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  86083. * @returns a matrix
  86084. */
  86085. Bone.prototype.getAbsoluteTransform = function () {
  86086. return this._absoluteTransform;
  86087. };
  86088. Object.defineProperty(Bone.prototype, "position", {
  86089. // Properties (matches AbstractMesh properties)
  86090. /** Gets or sets current position (in local space) */
  86091. get: function () {
  86092. this._decompose();
  86093. return this._localPosition;
  86094. },
  86095. set: function (newPosition) {
  86096. this._decompose();
  86097. this._localPosition.copyFrom(newPosition);
  86098. this._markAsDirtyAndCompose();
  86099. },
  86100. enumerable: true,
  86101. configurable: true
  86102. });
  86103. Object.defineProperty(Bone.prototype, "rotation", {
  86104. /** Gets or sets current rotation (in local space) */
  86105. get: function () {
  86106. return this.getRotation();
  86107. },
  86108. set: function (newRotation) {
  86109. this.setRotation(newRotation);
  86110. },
  86111. enumerable: true,
  86112. configurable: true
  86113. });
  86114. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  86115. /** Gets or sets current rotation quaternion (in local space) */
  86116. get: function () {
  86117. this._decompose();
  86118. return this._localRotation;
  86119. },
  86120. set: function (newRotation) {
  86121. this.setRotationQuaternion(newRotation);
  86122. },
  86123. enumerable: true,
  86124. configurable: true
  86125. });
  86126. Object.defineProperty(Bone.prototype, "scaling", {
  86127. /** Gets or sets current scaling (in local space) */
  86128. get: function () {
  86129. return this.getScale();
  86130. },
  86131. set: function (newScaling) {
  86132. this.setScale(newScaling);
  86133. },
  86134. enumerable: true,
  86135. configurable: true
  86136. });
  86137. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  86138. /**
  86139. * Gets the animation properties override
  86140. */
  86141. get: function () {
  86142. return this._skeleton.animationPropertiesOverride;
  86143. },
  86144. enumerable: true,
  86145. configurable: true
  86146. });
  86147. // Methods
  86148. Bone.prototype._decompose = function () {
  86149. if (!this._needToDecompose) {
  86150. return;
  86151. }
  86152. this._needToDecompose = false;
  86153. if (!this._localScaling) {
  86154. this._localScaling = BABYLON.Vector3.Zero();
  86155. this._localRotation = BABYLON.Quaternion.Zero();
  86156. this._localPosition = BABYLON.Vector3.Zero();
  86157. }
  86158. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  86159. };
  86160. Bone.prototype._compose = function () {
  86161. if (!this._needToCompose) {
  86162. return;
  86163. }
  86164. this._needToCompose = false;
  86165. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  86166. };
  86167. /**
  86168. * Update the base and local matrices
  86169. * @param matrix defines the new base or local matrix
  86170. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  86171. * @param updateLocalMatrix defines if the local matrix should be updated
  86172. */
  86173. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  86174. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  86175. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  86176. this._baseMatrix.copyFrom(matrix);
  86177. if (updateDifferenceMatrix) {
  86178. this._updateDifferenceMatrix();
  86179. }
  86180. if (updateLocalMatrix) {
  86181. this._localMatrix.copyFrom(matrix);
  86182. this._markAsDirtyAndDecompose();
  86183. }
  86184. else {
  86185. this.markAsDirty();
  86186. }
  86187. };
  86188. /** @hidden */
  86189. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  86190. if (updateChildren === void 0) { updateChildren = true; }
  86191. if (!rootMatrix) {
  86192. rootMatrix = this._baseMatrix;
  86193. }
  86194. if (this._parent) {
  86195. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  86196. }
  86197. else {
  86198. this._absoluteTransform.copyFrom(rootMatrix);
  86199. }
  86200. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  86201. if (updateChildren) {
  86202. for (var index = 0; index < this.children.length; index++) {
  86203. this.children[index]._updateDifferenceMatrix();
  86204. }
  86205. }
  86206. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  86207. };
  86208. /**
  86209. * Flag the bone as dirty (Forcing it to update everything)
  86210. */
  86211. Bone.prototype.markAsDirty = function () {
  86212. this._currentRenderId++;
  86213. this._childRenderId++;
  86214. this._skeleton._markAsDirty();
  86215. };
  86216. Bone.prototype._markAsDirtyAndCompose = function () {
  86217. this.markAsDirty();
  86218. this._needToCompose = true;
  86219. };
  86220. Bone.prototype._markAsDirtyAndDecompose = function () {
  86221. this.markAsDirty();
  86222. this._needToDecompose = true;
  86223. };
  86224. /**
  86225. * Copy an animation range from another bone
  86226. * @param source defines the source bone
  86227. * @param rangeName defines the range name to copy
  86228. * @param frameOffset defines the frame offset
  86229. * @param rescaleAsRequired defines if rescaling must be applied if required
  86230. * @param skelDimensionsRatio defines the scaling ratio
  86231. * @returns true if operation was successful
  86232. */
  86233. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  86234. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  86235. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  86236. // all animation may be coming from a library skeleton, so may need to create animation
  86237. if (this.animations.length === 0) {
  86238. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  86239. this.animations[0].setKeys([]);
  86240. }
  86241. // get animation info / verify there is such a range from the source bone
  86242. var sourceRange = source.animations[0].getRange(rangeName);
  86243. if (!sourceRange) {
  86244. return false;
  86245. }
  86246. var from = sourceRange.from;
  86247. var to = sourceRange.to;
  86248. var sourceKeys = source.animations[0].getKeys();
  86249. // rescaling prep
  86250. var sourceBoneLength = source.length;
  86251. var sourceParent = source.getParent();
  86252. var parent = this.getParent();
  86253. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  86254. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  86255. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  86256. var destKeys = this.animations[0].getKeys();
  86257. // loop vars declaration
  86258. var orig;
  86259. var origTranslation;
  86260. var mat;
  86261. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  86262. orig = sourceKeys[key];
  86263. if (orig.frame >= from && orig.frame <= to) {
  86264. if (rescaleAsRequired) {
  86265. mat = orig.value.clone();
  86266. // scale based on parent ratio, when bone has parent
  86267. if (parentScalingReqd) {
  86268. origTranslation = mat.getTranslation();
  86269. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  86270. // scale based on skeleton dimension ratio when root bone, and value is passed
  86271. }
  86272. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  86273. origTranslation = mat.getTranslation();
  86274. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  86275. // use original when root bone, and no data for skelDimensionsRatio
  86276. }
  86277. else {
  86278. mat = orig.value;
  86279. }
  86280. }
  86281. else {
  86282. mat = orig.value;
  86283. }
  86284. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  86285. }
  86286. }
  86287. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  86288. return true;
  86289. };
  86290. /**
  86291. * Translate the bone in local or world space
  86292. * @param vec The amount to translate the bone
  86293. * @param space The space that the translation is in
  86294. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86295. */
  86296. Bone.prototype.translate = function (vec, space, mesh) {
  86297. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86298. var lm = this.getLocalMatrix();
  86299. if (space == BABYLON.Space.LOCAL) {
  86300. lm.m[12] += vec.x;
  86301. lm.m[13] += vec.y;
  86302. lm.m[14] += vec.z;
  86303. }
  86304. else {
  86305. var wm = null;
  86306. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86307. if (mesh) {
  86308. wm = mesh.getWorldMatrix();
  86309. }
  86310. this._skeleton.computeAbsoluteTransforms();
  86311. var tmat = Bone._tmpMats[0];
  86312. var tvec = Bone._tmpVecs[0];
  86313. if (this._parent) {
  86314. if (mesh && wm) {
  86315. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86316. tmat.multiplyToRef(wm, tmat);
  86317. }
  86318. else {
  86319. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86320. }
  86321. }
  86322. tmat.m[12] = 0;
  86323. tmat.m[13] = 0;
  86324. tmat.m[14] = 0;
  86325. tmat.invert();
  86326. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  86327. lm.m[12] += tvec.x;
  86328. lm.m[13] += tvec.y;
  86329. lm.m[14] += tvec.z;
  86330. }
  86331. this._markAsDirtyAndDecompose();
  86332. };
  86333. /**
  86334. * Set the postion of the bone in local or world space
  86335. * @param position The position to set the bone
  86336. * @param space The space that the position is in
  86337. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86338. */
  86339. Bone.prototype.setPosition = function (position, space, mesh) {
  86340. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86341. var lm = this.getLocalMatrix();
  86342. if (space == BABYLON.Space.LOCAL) {
  86343. lm.m[12] = position.x;
  86344. lm.m[13] = position.y;
  86345. lm.m[14] = position.z;
  86346. }
  86347. else {
  86348. var wm = null;
  86349. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86350. if (mesh) {
  86351. wm = mesh.getWorldMatrix();
  86352. }
  86353. this._skeleton.computeAbsoluteTransforms();
  86354. var tmat = Bone._tmpMats[0];
  86355. var vec = Bone._tmpVecs[0];
  86356. if (this._parent) {
  86357. if (mesh && wm) {
  86358. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86359. tmat.multiplyToRef(wm, tmat);
  86360. }
  86361. else {
  86362. tmat.copyFrom(this._parent.getAbsoluteTransform());
  86363. }
  86364. }
  86365. tmat.invert();
  86366. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  86367. lm.m[12] = vec.x;
  86368. lm.m[13] = vec.y;
  86369. lm.m[14] = vec.z;
  86370. }
  86371. this._markAsDirtyAndDecompose();
  86372. };
  86373. /**
  86374. * Set the absolute position of the bone (world space)
  86375. * @param position The position to set the bone
  86376. * @param mesh The mesh that this bone is attached to
  86377. */
  86378. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  86379. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  86380. };
  86381. /**
  86382. * Scale the bone on the x, y and z axes (in local space)
  86383. * @param x The amount to scale the bone on the x axis
  86384. * @param y The amount to scale the bone on the y axis
  86385. * @param z The amount to scale the bone on the z axis
  86386. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  86387. */
  86388. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  86389. if (scaleChildren === void 0) { scaleChildren = false; }
  86390. var locMat = this.getLocalMatrix();
  86391. // Apply new scaling on top of current local matrix
  86392. var scaleMat = Bone._tmpMats[0];
  86393. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  86394. scaleMat.multiplyToRef(locMat, locMat);
  86395. // Invert scaling matrix and apply the inverse to all children
  86396. scaleMat.invert();
  86397. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  86398. var child = _a[_i];
  86399. var cm = child.getLocalMatrix();
  86400. cm.multiplyToRef(scaleMat, cm);
  86401. cm.m[12] *= x;
  86402. cm.m[13] *= y;
  86403. cm.m[14] *= z;
  86404. child._markAsDirtyAndDecompose();
  86405. }
  86406. this._markAsDirtyAndDecompose();
  86407. if (scaleChildren) {
  86408. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  86409. var child = _c[_b];
  86410. child.scale(x, y, z, scaleChildren);
  86411. }
  86412. }
  86413. };
  86414. /**
  86415. * Set the bone scaling in local space
  86416. * @param scale defines the scaling vector
  86417. */
  86418. Bone.prototype.setScale = function (scale) {
  86419. this._decompose();
  86420. this._localScaling.copyFrom(scale);
  86421. this._markAsDirtyAndCompose();
  86422. };
  86423. /**
  86424. * Gets the current scaling in local space
  86425. * @returns the current scaling vector
  86426. */
  86427. Bone.prototype.getScale = function () {
  86428. this._decompose();
  86429. return this._localScaling;
  86430. };
  86431. /**
  86432. * Gets the current scaling in local space and stores it in a target vector
  86433. * @param result defines the target vector
  86434. */
  86435. Bone.prototype.getScaleToRef = function (result) {
  86436. this._decompose();
  86437. result.copyFrom(this._localScaling);
  86438. };
  86439. /**
  86440. * Set the yaw, pitch, and roll of the bone in local or world space
  86441. * @param yaw The rotation of the bone on the y axis
  86442. * @param pitch The rotation of the bone on the x axis
  86443. * @param roll The rotation of the bone on the z axis
  86444. * @param space The space that the axes of rotation are in
  86445. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86446. */
  86447. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  86448. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86449. if (space === BABYLON.Space.LOCAL) {
  86450. var quat = Bone._tmpQuat;
  86451. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  86452. this.setRotationQuaternion(quat, space, mesh);
  86453. return;
  86454. }
  86455. var rotMatInv = Bone._tmpMats[0];
  86456. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86457. return;
  86458. }
  86459. var rotMat = Bone._tmpMats[1];
  86460. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  86461. rotMatInv.multiplyToRef(rotMat, rotMat);
  86462. this._rotateWithMatrix(rotMat, space, mesh);
  86463. };
  86464. /**
  86465. * Add a rotation to the bone on an axis in local or world space
  86466. * @param axis The axis to rotate the bone on
  86467. * @param amount The amount to rotate the bone
  86468. * @param space The space that the axis is in
  86469. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86470. */
  86471. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  86472. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86473. var rmat = Bone._tmpMats[0];
  86474. rmat.m[12] = 0;
  86475. rmat.m[13] = 0;
  86476. rmat.m[14] = 0;
  86477. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  86478. this._rotateWithMatrix(rmat, space, mesh);
  86479. };
  86480. /**
  86481. * Set the rotation of the bone to a particular axis angle in local or world space
  86482. * @param axis The axis to rotate the bone on
  86483. * @param angle The angle that the bone should be rotated to
  86484. * @param space The space that the axis is in
  86485. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86486. */
  86487. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  86488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86489. if (space === BABYLON.Space.LOCAL) {
  86490. var quat = Bone._tmpQuat;
  86491. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  86492. this.setRotationQuaternion(quat, space, mesh);
  86493. return;
  86494. }
  86495. var rotMatInv = Bone._tmpMats[0];
  86496. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86497. return;
  86498. }
  86499. var rotMat = Bone._tmpMats[1];
  86500. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  86501. rotMatInv.multiplyToRef(rotMat, rotMat);
  86502. this._rotateWithMatrix(rotMat, space, mesh);
  86503. };
  86504. /**
  86505. * Set the euler rotation of the bone in local of world space
  86506. * @param rotation The euler rotation that the bone should be set to
  86507. * @param space The space that the rotation is in
  86508. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86509. */
  86510. Bone.prototype.setRotation = function (rotation, space, mesh) {
  86511. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86512. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  86513. };
  86514. /**
  86515. * Set the quaternion rotation of the bone in local of world space
  86516. * @param quat The quaternion rotation that the bone should be set to
  86517. * @param space The space that the rotation is in
  86518. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86519. */
  86520. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  86521. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86522. if (space === BABYLON.Space.LOCAL) {
  86523. this._decompose();
  86524. this._localRotation.copyFrom(quat);
  86525. this._markAsDirtyAndCompose();
  86526. return;
  86527. }
  86528. var rotMatInv = Bone._tmpMats[0];
  86529. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86530. return;
  86531. }
  86532. var rotMat = Bone._tmpMats[1];
  86533. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  86534. rotMatInv.multiplyToRef(rotMat, rotMat);
  86535. this._rotateWithMatrix(rotMat, space, mesh);
  86536. };
  86537. /**
  86538. * Set the rotation matrix of the bone in local of world space
  86539. * @param rotMat The rotation matrix that the bone should be set to
  86540. * @param space The space that the rotation is in
  86541. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86542. */
  86543. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  86544. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86545. if (space === BABYLON.Space.LOCAL) {
  86546. var quat = Bone._tmpQuat;
  86547. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  86548. this.setRotationQuaternion(quat, space, mesh);
  86549. return;
  86550. }
  86551. var rotMatInv = Bone._tmpMats[0];
  86552. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  86553. return;
  86554. }
  86555. var rotMat2 = Bone._tmpMats[1];
  86556. rotMat2.copyFrom(rotMat);
  86557. rotMatInv.multiplyToRef(rotMat, rotMat2);
  86558. this._rotateWithMatrix(rotMat2, space, mesh);
  86559. };
  86560. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  86561. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86562. var lmat = this.getLocalMatrix();
  86563. var lx = lmat.m[12];
  86564. var ly = lmat.m[13];
  86565. var lz = lmat.m[14];
  86566. var parent = this.getParent();
  86567. var parentScale = Bone._tmpMats[3];
  86568. var parentScaleInv = Bone._tmpMats[4];
  86569. if (parent && space == BABYLON.Space.WORLD) {
  86570. if (mesh) {
  86571. parentScale.copyFrom(mesh.getWorldMatrix());
  86572. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  86573. }
  86574. else {
  86575. parentScale.copyFrom(parent.getAbsoluteTransform());
  86576. }
  86577. parentScaleInv.copyFrom(parentScale);
  86578. parentScaleInv.invert();
  86579. lmat.multiplyToRef(parentScale, lmat);
  86580. lmat.multiplyToRef(rmat, lmat);
  86581. lmat.multiplyToRef(parentScaleInv, lmat);
  86582. }
  86583. else {
  86584. if (space == BABYLON.Space.WORLD && mesh) {
  86585. parentScale.copyFrom(mesh.getWorldMatrix());
  86586. parentScaleInv.copyFrom(parentScale);
  86587. parentScaleInv.invert();
  86588. lmat.multiplyToRef(parentScale, lmat);
  86589. lmat.multiplyToRef(rmat, lmat);
  86590. lmat.multiplyToRef(parentScaleInv, lmat);
  86591. }
  86592. else {
  86593. lmat.multiplyToRef(rmat, lmat);
  86594. }
  86595. }
  86596. lmat.m[12] = lx;
  86597. lmat.m[13] = ly;
  86598. lmat.m[14] = lz;
  86599. this.computeAbsoluteTransforms();
  86600. this._markAsDirtyAndDecompose();
  86601. };
  86602. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  86603. var scaleMatrix = Bone._tmpMats[2];
  86604. rotMatInv.copyFrom(this.getAbsoluteTransform());
  86605. if (mesh) {
  86606. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  86607. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  86608. }
  86609. rotMatInv.invert();
  86610. if (isNaN(rotMatInv.m[0])) {
  86611. // Matrix failed to invert.
  86612. // This can happen if scale is zero for example.
  86613. return false;
  86614. }
  86615. scaleMatrix.m[0] *= this._scalingDeterminant;
  86616. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  86617. return true;
  86618. };
  86619. /**
  86620. * Get the position of the bone in local or world space
  86621. * @param space The space that the returned position is in
  86622. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86623. * @returns The position of the bone
  86624. */
  86625. Bone.prototype.getPosition = function (space, mesh) {
  86626. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86627. if (mesh === void 0) { mesh = null; }
  86628. var pos = BABYLON.Vector3.Zero();
  86629. this.getPositionToRef(space, mesh, pos);
  86630. return pos;
  86631. };
  86632. /**
  86633. * Copy the position of the bone to a vector3 in local or world space
  86634. * @param space The space that the returned position is in
  86635. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86636. * @param result The vector3 to copy the position to
  86637. */
  86638. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  86639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86640. if (space == BABYLON.Space.LOCAL) {
  86641. var lm = this.getLocalMatrix();
  86642. result.x = lm.m[12];
  86643. result.y = lm.m[13];
  86644. result.z = lm.m[14];
  86645. }
  86646. else {
  86647. var wm = null;
  86648. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86649. if (mesh) {
  86650. wm = mesh.getWorldMatrix();
  86651. }
  86652. this._skeleton.computeAbsoluteTransforms();
  86653. var tmat = Bone._tmpMats[0];
  86654. if (mesh && wm) {
  86655. tmat.copyFrom(this.getAbsoluteTransform());
  86656. tmat.multiplyToRef(wm, tmat);
  86657. }
  86658. else {
  86659. tmat = this.getAbsoluteTransform();
  86660. }
  86661. result.x = tmat.m[12];
  86662. result.y = tmat.m[13];
  86663. result.z = tmat.m[14];
  86664. }
  86665. };
  86666. /**
  86667. * Get the absolute position of the bone (world space)
  86668. * @param mesh The mesh that this bone is attached to
  86669. * @returns The absolute position of the bone
  86670. */
  86671. Bone.prototype.getAbsolutePosition = function (mesh) {
  86672. if (mesh === void 0) { mesh = null; }
  86673. var pos = BABYLON.Vector3.Zero();
  86674. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  86675. return pos;
  86676. };
  86677. /**
  86678. * Copy the absolute position of the bone (world space) to the result param
  86679. * @param mesh The mesh that this bone is attached to
  86680. * @param result The vector3 to copy the absolute position to
  86681. */
  86682. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  86683. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  86684. };
  86685. /**
  86686. * Compute the absolute transforms of this bone and its children
  86687. */
  86688. Bone.prototype.computeAbsoluteTransforms = function () {
  86689. this._compose();
  86690. if (this._parent) {
  86691. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  86692. }
  86693. else {
  86694. this._absoluteTransform.copyFrom(this._localMatrix);
  86695. var poseMatrix = this._skeleton.getPoseMatrix();
  86696. if (poseMatrix) {
  86697. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  86698. }
  86699. }
  86700. var children = this.children;
  86701. var len = children.length;
  86702. for (var i = 0; i < len; i++) {
  86703. children[i].computeAbsoluteTransforms();
  86704. }
  86705. };
  86706. /**
  86707. * Get the world direction from an axis that is in the local space of the bone
  86708. * @param localAxis The local direction that is used to compute the world direction
  86709. * @param mesh The mesh that this bone is attached to
  86710. * @returns The world direction
  86711. */
  86712. Bone.prototype.getDirection = function (localAxis, mesh) {
  86713. if (mesh === void 0) { mesh = null; }
  86714. var result = BABYLON.Vector3.Zero();
  86715. this.getDirectionToRef(localAxis, mesh, result);
  86716. return result;
  86717. };
  86718. /**
  86719. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  86720. * @param localAxis The local direction that is used to compute the world direction
  86721. * @param mesh The mesh that this bone is attached to
  86722. * @param result The vector3 that the world direction will be copied to
  86723. */
  86724. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  86725. if (mesh === void 0) { mesh = null; }
  86726. var wm = null;
  86727. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86728. if (mesh) {
  86729. wm = mesh.getWorldMatrix();
  86730. }
  86731. this._skeleton.computeAbsoluteTransforms();
  86732. var mat = Bone._tmpMats[0];
  86733. mat.copyFrom(this.getAbsoluteTransform());
  86734. if (mesh && wm) {
  86735. mat.multiplyToRef(wm, mat);
  86736. }
  86737. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  86738. result.normalize();
  86739. };
  86740. /**
  86741. * Get the euler rotation of the bone in local or world space
  86742. * @param space The space that the rotation should be in
  86743. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86744. * @returns The euler rotation
  86745. */
  86746. Bone.prototype.getRotation = function (space, mesh) {
  86747. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86748. if (mesh === void 0) { mesh = null; }
  86749. var result = BABYLON.Vector3.Zero();
  86750. this.getRotationToRef(space, mesh, result);
  86751. return result;
  86752. };
  86753. /**
  86754. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  86755. * @param space The space that the rotation should be in
  86756. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86757. * @param result The vector3 that the rotation should be copied to
  86758. */
  86759. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  86760. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86761. if (mesh === void 0) { mesh = null; }
  86762. var quat = Bone._tmpQuat;
  86763. this.getRotationQuaternionToRef(space, mesh, quat);
  86764. quat.toEulerAnglesToRef(result);
  86765. };
  86766. /**
  86767. * Get the quaternion rotation of the bone in either local or world space
  86768. * @param space The space that the rotation should be in
  86769. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86770. * @returns The quaternion rotation
  86771. */
  86772. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  86773. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86774. if (mesh === void 0) { mesh = null; }
  86775. var result = BABYLON.Quaternion.Identity();
  86776. this.getRotationQuaternionToRef(space, mesh, result);
  86777. return result;
  86778. };
  86779. /**
  86780. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  86781. * @param space The space that the rotation should be in
  86782. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86783. * @param result The quaternion that the rotation should be copied to
  86784. */
  86785. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  86786. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86787. if (mesh === void 0) { mesh = null; }
  86788. if (space == BABYLON.Space.LOCAL) {
  86789. this._decompose();
  86790. result.copyFrom(this._localRotation);
  86791. }
  86792. else {
  86793. var mat = Bone._tmpMats[0];
  86794. var amat = this.getAbsoluteTransform();
  86795. if (mesh) {
  86796. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  86797. }
  86798. else {
  86799. mat.copyFrom(amat);
  86800. }
  86801. mat.m[0] *= this._scalingDeterminant;
  86802. mat.m[1] *= this._scalingDeterminant;
  86803. mat.m[2] *= this._scalingDeterminant;
  86804. mat.decompose(undefined, result, undefined);
  86805. }
  86806. };
  86807. /**
  86808. * Get the rotation matrix of the bone in local or world space
  86809. * @param space The space that the rotation should be in
  86810. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86811. * @returns The rotation matrix
  86812. */
  86813. Bone.prototype.getRotationMatrix = function (space, mesh) {
  86814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86815. var result = BABYLON.Matrix.Identity();
  86816. this.getRotationMatrixToRef(space, mesh, result);
  86817. return result;
  86818. };
  86819. /**
  86820. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  86821. * @param space The space that the rotation should be in
  86822. * @param mesh The mesh that this bone is attached to. This is only used in world space
  86823. * @param result The quaternion that the rotation should be copied to
  86824. */
  86825. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  86826. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  86827. if (space == BABYLON.Space.LOCAL) {
  86828. this.getLocalMatrix().getRotationMatrixToRef(result);
  86829. }
  86830. else {
  86831. var mat = Bone._tmpMats[0];
  86832. var amat = this.getAbsoluteTransform();
  86833. if (mesh) {
  86834. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  86835. }
  86836. else {
  86837. mat.copyFrom(amat);
  86838. }
  86839. mat.m[0] *= this._scalingDeterminant;
  86840. mat.m[1] *= this._scalingDeterminant;
  86841. mat.m[2] *= this._scalingDeterminant;
  86842. mat.getRotationMatrixToRef(result);
  86843. }
  86844. };
  86845. /**
  86846. * Get the world position of a point that is in the local space of the bone
  86847. * @param position The local position
  86848. * @param mesh The mesh that this bone is attached to
  86849. * @returns The world position
  86850. */
  86851. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  86852. if (mesh === void 0) { mesh = null; }
  86853. var result = BABYLON.Vector3.Zero();
  86854. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  86855. return result;
  86856. };
  86857. /**
  86858. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  86859. * @param position The local position
  86860. * @param mesh The mesh that this bone is attached to
  86861. * @param result The vector3 that the world position should be copied to
  86862. */
  86863. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  86864. if (mesh === void 0) { mesh = null; }
  86865. var wm = null;
  86866. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86867. if (mesh) {
  86868. wm = mesh.getWorldMatrix();
  86869. }
  86870. this._skeleton.computeAbsoluteTransforms();
  86871. var tmat = Bone._tmpMats[0];
  86872. if (mesh && wm) {
  86873. tmat.copyFrom(this.getAbsoluteTransform());
  86874. tmat.multiplyToRef(wm, tmat);
  86875. }
  86876. else {
  86877. tmat = this.getAbsoluteTransform();
  86878. }
  86879. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  86880. };
  86881. /**
  86882. * Get the local position of a point that is in world space
  86883. * @param position The world position
  86884. * @param mesh The mesh that this bone is attached to
  86885. * @returns The local position
  86886. */
  86887. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  86888. if (mesh === void 0) { mesh = null; }
  86889. var result = BABYLON.Vector3.Zero();
  86890. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  86891. return result;
  86892. };
  86893. /**
  86894. * Get the local position of a point that is in world space and copy it to the result param
  86895. * @param position The world position
  86896. * @param mesh The mesh that this bone is attached to
  86897. * @param result The vector3 that the local position should be copied to
  86898. */
  86899. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  86900. if (mesh === void 0) { mesh = null; }
  86901. var wm = null;
  86902. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  86903. if (mesh) {
  86904. wm = mesh.getWorldMatrix();
  86905. }
  86906. this._skeleton.computeAbsoluteTransforms();
  86907. var tmat = Bone._tmpMats[0];
  86908. tmat.copyFrom(this.getAbsoluteTransform());
  86909. if (mesh && wm) {
  86910. tmat.multiplyToRef(wm, tmat);
  86911. }
  86912. tmat.invert();
  86913. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  86914. };
  86915. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86916. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  86917. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  86918. return Bone;
  86919. }(BABYLON.Node));
  86920. BABYLON.Bone = Bone;
  86921. })(BABYLON || (BABYLON = {}));
  86922. //# sourceMappingURL=babylon.bone.js.map
  86923. var BABYLON;
  86924. (function (BABYLON) {
  86925. /**
  86926. * Class used to apply inverse kinematics to bones
  86927. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  86928. */
  86929. var BoneIKController = /** @class */ (function () {
  86930. /**
  86931. * Creates a new BoneIKController
  86932. * @param mesh defines the mesh to control
  86933. * @param bone defines the bone to control
  86934. * @param options defines options to set up the controller
  86935. */
  86936. function BoneIKController(mesh, bone, options) {
  86937. /**
  86938. * Gets or sets the target position
  86939. */
  86940. this.targetPosition = BABYLON.Vector3.Zero();
  86941. /**
  86942. * Gets or sets the pole target position
  86943. */
  86944. this.poleTargetPosition = BABYLON.Vector3.Zero();
  86945. /**
  86946. * Gets or sets the pole target local offset
  86947. */
  86948. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  86949. /**
  86950. * Gets or sets the pole angle
  86951. */
  86952. this.poleAngle = 0;
  86953. /**
  86954. * 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)
  86955. */
  86956. this.slerpAmount = 1;
  86957. this._bone1Quat = BABYLON.Quaternion.Identity();
  86958. this._bone1Mat = BABYLON.Matrix.Identity();
  86959. this._bone2Ang = Math.PI;
  86960. this._maxAngle = Math.PI;
  86961. this._rightHandedSystem = false;
  86962. this._bendAxis = BABYLON.Vector3.Right();
  86963. this._slerping = false;
  86964. this._adjustRoll = 0;
  86965. this._bone2 = bone;
  86966. this._bone1 = bone.getParent();
  86967. if (!this._bone1) {
  86968. return;
  86969. }
  86970. this.mesh = mesh;
  86971. var bonePos = bone.getPosition();
  86972. if (bone.getAbsoluteTransform().determinant() > 0) {
  86973. this._rightHandedSystem = true;
  86974. this._bendAxis.x = 0;
  86975. this._bendAxis.y = 0;
  86976. this._bendAxis.z = -1;
  86977. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  86978. this._adjustRoll = Math.PI * .5;
  86979. this._bendAxis.z = 1;
  86980. }
  86981. }
  86982. if (this._bone1.length) {
  86983. var boneScale1 = this._bone1.getScale();
  86984. var boneScale2 = this._bone2.getScale();
  86985. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  86986. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  86987. }
  86988. else if (this._bone1.children[0]) {
  86989. mesh.computeWorldMatrix(true);
  86990. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  86991. var pos2 = this._bone2.getAbsolutePosition(mesh);
  86992. var pos3 = this._bone1.getAbsolutePosition(mesh);
  86993. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  86994. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  86995. }
  86996. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  86997. this.maxAngle = Math.PI;
  86998. if (options) {
  86999. if (options.targetMesh) {
  87000. this.targetMesh = options.targetMesh;
  87001. this.targetMesh.computeWorldMatrix(true);
  87002. }
  87003. if (options.poleTargetMesh) {
  87004. this.poleTargetMesh = options.poleTargetMesh;
  87005. this.poleTargetMesh.computeWorldMatrix(true);
  87006. }
  87007. else if (options.poleTargetBone) {
  87008. this.poleTargetBone = options.poleTargetBone;
  87009. }
  87010. else if (this._bone1.getParent()) {
  87011. this.poleTargetBone = this._bone1.getParent();
  87012. }
  87013. if (options.poleTargetLocalOffset) {
  87014. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  87015. }
  87016. if (options.poleAngle) {
  87017. this.poleAngle = options.poleAngle;
  87018. }
  87019. if (options.bendAxis) {
  87020. this._bendAxis.copyFrom(options.bendAxis);
  87021. }
  87022. if (options.maxAngle) {
  87023. this.maxAngle = options.maxAngle;
  87024. }
  87025. if (options.slerpAmount) {
  87026. this.slerpAmount = options.slerpAmount;
  87027. }
  87028. }
  87029. }
  87030. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  87031. /**
  87032. * Gets or sets maximum allowed angle
  87033. */
  87034. get: function () {
  87035. return this._maxAngle;
  87036. },
  87037. set: function (value) {
  87038. this._setMaxAngle(value);
  87039. },
  87040. enumerable: true,
  87041. configurable: true
  87042. });
  87043. BoneIKController.prototype._setMaxAngle = function (ang) {
  87044. if (ang < 0) {
  87045. ang = 0;
  87046. }
  87047. if (ang > Math.PI || ang == undefined) {
  87048. ang = Math.PI;
  87049. }
  87050. this._maxAngle = ang;
  87051. var a = this._bone1Length;
  87052. var b = this._bone2Length;
  87053. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  87054. };
  87055. /**
  87056. * Force the controller to update the bones
  87057. */
  87058. BoneIKController.prototype.update = function () {
  87059. var bone1 = this._bone1;
  87060. if (!bone1) {
  87061. return;
  87062. }
  87063. var target = this.targetPosition;
  87064. var poleTarget = this.poleTargetPosition;
  87065. var mat1 = BoneIKController._tmpMats[0];
  87066. var mat2 = BoneIKController._tmpMats[1];
  87067. if (this.targetMesh) {
  87068. target.copyFrom(this.targetMesh.getAbsolutePosition());
  87069. }
  87070. if (this.poleTargetBone) {
  87071. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  87072. }
  87073. else if (this.poleTargetMesh) {
  87074. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  87075. }
  87076. var bonePos = BoneIKController._tmpVecs[0];
  87077. var zaxis = BoneIKController._tmpVecs[1];
  87078. var xaxis = BoneIKController._tmpVecs[2];
  87079. var yaxis = BoneIKController._tmpVecs[3];
  87080. var upAxis = BoneIKController._tmpVecs[4];
  87081. var _tmpQuat = BoneIKController._tmpQuat;
  87082. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  87083. poleTarget.subtractToRef(bonePos, upAxis);
  87084. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  87085. upAxis.y = 1;
  87086. }
  87087. else {
  87088. upAxis.normalize();
  87089. }
  87090. target.subtractToRef(bonePos, yaxis);
  87091. yaxis.normalize();
  87092. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  87093. zaxis.normalize();
  87094. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  87095. xaxis.normalize();
  87096. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  87097. var a = this._bone1Length;
  87098. var b = this._bone2Length;
  87099. var c = BABYLON.Vector3.Distance(bonePos, target);
  87100. if (this._maxReach > 0) {
  87101. c = Math.min(this._maxReach, c);
  87102. }
  87103. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  87104. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  87105. if (acosa > 1) {
  87106. acosa = 1;
  87107. }
  87108. if (acosb > 1) {
  87109. acosb = 1;
  87110. }
  87111. if (acosa < -1) {
  87112. acosa = -1;
  87113. }
  87114. if (acosb < -1) {
  87115. acosb = -1;
  87116. }
  87117. var angA = Math.acos(acosa);
  87118. var angB = Math.acos(acosb);
  87119. var angC = -angA - angB;
  87120. if (this._rightHandedSystem) {
  87121. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  87122. mat2.multiplyToRef(mat1, mat1);
  87123. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  87124. mat2.multiplyToRef(mat1, mat1);
  87125. }
  87126. else {
  87127. var _tmpVec = BoneIKController._tmpVecs[5];
  87128. _tmpVec.copyFrom(this._bendAxis);
  87129. _tmpVec.x *= -1;
  87130. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  87131. mat2.multiplyToRef(mat1, mat1);
  87132. }
  87133. if (this.poleAngle) {
  87134. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  87135. mat1.multiplyToRef(mat2, mat1);
  87136. }
  87137. if (this._bone1) {
  87138. if (this.slerpAmount < 1) {
  87139. if (!this._slerping) {
  87140. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  87141. }
  87142. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  87143. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  87144. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  87145. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  87146. this._slerping = true;
  87147. }
  87148. else {
  87149. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  87150. this._bone1Mat.copyFrom(mat1);
  87151. this._slerping = false;
  87152. }
  87153. }
  87154. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  87155. this._bone2Ang = angC;
  87156. };
  87157. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87158. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  87159. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87160. return BoneIKController;
  87161. }());
  87162. BABYLON.BoneIKController = BoneIKController;
  87163. })(BABYLON || (BABYLON = {}));
  87164. //# sourceMappingURL=babylon.boneIKController.js.map
  87165. var BABYLON;
  87166. (function (BABYLON) {
  87167. /**
  87168. * Class used to make a bone look toward a point in space
  87169. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  87170. */
  87171. var BoneLookController = /** @class */ (function () {
  87172. /**
  87173. * Create a BoneLookController
  87174. * @param mesh the mesh that the bone belongs to
  87175. * @param bone the bone that will be looking to the target
  87176. * @param target the target Vector3 to look at
  87177. * @param settings optional settings:
  87178. * * maxYaw: the maximum angle the bone will yaw to
  87179. * * minYaw: the minimum angle the bone will yaw to
  87180. * * maxPitch: the maximum angle the bone will pitch to
  87181. * * minPitch: the minimum angle the bone will yaw to
  87182. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  87183. * * upAxis: the up axis of the coordinate system
  87184. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  87185. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  87186. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  87187. * * adjustYaw: used to make an adjustment to the yaw of the bone
  87188. * * adjustPitch: used to make an adjustment to the pitch of the bone
  87189. * * adjustRoll: used to make an adjustment to the roll of the bone
  87190. **/
  87191. function BoneLookController(mesh, bone, target, options) {
  87192. /**
  87193. * The up axis of the coordinate system that is used when the bone is rotated
  87194. */
  87195. this.upAxis = BABYLON.Vector3.Up();
  87196. /**
  87197. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  87198. */
  87199. this.upAxisSpace = BABYLON.Space.LOCAL;
  87200. /**
  87201. * Used to make an adjustment to the yaw of the bone
  87202. */
  87203. this.adjustYaw = 0;
  87204. /**
  87205. * Used to make an adjustment to the pitch of the bone
  87206. */
  87207. this.adjustPitch = 0;
  87208. /**
  87209. * Used to make an adjustment to the roll of the bone
  87210. */
  87211. this.adjustRoll = 0;
  87212. /**
  87213. * 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)
  87214. */
  87215. this.slerpAmount = 1;
  87216. this._boneQuat = BABYLON.Quaternion.Identity();
  87217. this._slerping = false;
  87218. this._firstFrameSkipped = false;
  87219. this._fowardAxis = BABYLON.Vector3.Forward();
  87220. this.mesh = mesh;
  87221. this.bone = bone;
  87222. this.target = target;
  87223. if (options) {
  87224. if (options.adjustYaw) {
  87225. this.adjustYaw = options.adjustYaw;
  87226. }
  87227. if (options.adjustPitch) {
  87228. this.adjustPitch = options.adjustPitch;
  87229. }
  87230. if (options.adjustRoll) {
  87231. this.adjustRoll = options.adjustRoll;
  87232. }
  87233. if (options.maxYaw != null) {
  87234. this.maxYaw = options.maxYaw;
  87235. }
  87236. else {
  87237. this.maxYaw = Math.PI;
  87238. }
  87239. if (options.minYaw != null) {
  87240. this.minYaw = options.minYaw;
  87241. }
  87242. else {
  87243. this.minYaw = -Math.PI;
  87244. }
  87245. if (options.maxPitch != null) {
  87246. this.maxPitch = options.maxPitch;
  87247. }
  87248. else {
  87249. this.maxPitch = Math.PI;
  87250. }
  87251. if (options.minPitch != null) {
  87252. this.minPitch = options.minPitch;
  87253. }
  87254. else {
  87255. this.minPitch = -Math.PI;
  87256. }
  87257. if (options.slerpAmount != null) {
  87258. this.slerpAmount = options.slerpAmount;
  87259. }
  87260. if (options.upAxis != null) {
  87261. this.upAxis = options.upAxis;
  87262. }
  87263. if (options.upAxisSpace != null) {
  87264. this.upAxisSpace = options.upAxisSpace;
  87265. }
  87266. if (options.yawAxis != null || options.pitchAxis != null) {
  87267. var newYawAxis = BABYLON.Axis.Y;
  87268. var newPitchAxis = BABYLON.Axis.X;
  87269. if (options.yawAxis != null) {
  87270. newYawAxis = options.yawAxis.clone();
  87271. newYawAxis.normalize();
  87272. }
  87273. if (options.pitchAxis != null) {
  87274. newPitchAxis = options.pitchAxis.clone();
  87275. newPitchAxis.normalize();
  87276. }
  87277. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  87278. this._transformYawPitch = BABYLON.Matrix.Identity();
  87279. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  87280. this._transformYawPitchInv = this._transformYawPitch.clone();
  87281. this._transformYawPitch.invert();
  87282. }
  87283. }
  87284. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  87285. this.upAxisSpace = BABYLON.Space.LOCAL;
  87286. }
  87287. }
  87288. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  87289. /**
  87290. * Gets or sets the minimum yaw angle that the bone can look to
  87291. */
  87292. get: function () {
  87293. return this._minYaw;
  87294. },
  87295. set: function (value) {
  87296. this._minYaw = value;
  87297. this._minYawSin = Math.sin(value);
  87298. this._minYawCos = Math.cos(value);
  87299. if (this._maxYaw != null) {
  87300. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87301. this._yawRange = this._maxYaw - this._minYaw;
  87302. }
  87303. },
  87304. enumerable: true,
  87305. configurable: true
  87306. });
  87307. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  87308. /**
  87309. * Gets or sets the maximum yaw angle that the bone can look to
  87310. */
  87311. get: function () {
  87312. return this._maxYaw;
  87313. },
  87314. set: function (value) {
  87315. this._maxYaw = value;
  87316. this._maxYawSin = Math.sin(value);
  87317. this._maxYawCos = Math.cos(value);
  87318. if (this._minYaw != null) {
  87319. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  87320. this._yawRange = this._maxYaw - this._minYaw;
  87321. }
  87322. },
  87323. enumerable: true,
  87324. configurable: true
  87325. });
  87326. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  87327. /**
  87328. * Gets or sets the minimum pitch angle that the bone can look to
  87329. */
  87330. get: function () {
  87331. return this._minPitch;
  87332. },
  87333. set: function (value) {
  87334. this._minPitch = value;
  87335. this._minPitchTan = Math.tan(value);
  87336. },
  87337. enumerable: true,
  87338. configurable: true
  87339. });
  87340. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  87341. /**
  87342. * Gets or sets the maximum pitch angle that the bone can look to
  87343. */
  87344. get: function () {
  87345. return this._maxPitch;
  87346. },
  87347. set: function (value) {
  87348. this._maxPitch = value;
  87349. this._maxPitchTan = Math.tan(value);
  87350. },
  87351. enumerable: true,
  87352. configurable: true
  87353. });
  87354. /**
  87355. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  87356. */
  87357. BoneLookController.prototype.update = function () {
  87358. //skip the first frame when slerping so that the mesh rotation is correct
  87359. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  87360. this._firstFrameSkipped = true;
  87361. return;
  87362. }
  87363. var bone = this.bone;
  87364. var bonePos = BoneLookController._tmpVecs[0];
  87365. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  87366. var target = this.target;
  87367. var _tmpMat1 = BoneLookController._tmpMats[0];
  87368. var _tmpMat2 = BoneLookController._tmpMats[1];
  87369. var mesh = this.mesh;
  87370. var parentBone = bone.getParent();
  87371. var upAxis = BoneLookController._tmpVecs[1];
  87372. upAxis.copyFrom(this.upAxis);
  87373. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  87374. if (this._transformYawPitch) {
  87375. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  87376. }
  87377. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  87378. }
  87379. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  87380. mesh.getDirectionToRef(upAxis, upAxis);
  87381. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  87382. upAxis.normalize();
  87383. }
  87384. }
  87385. var checkYaw = false;
  87386. var checkPitch = false;
  87387. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  87388. checkYaw = true;
  87389. }
  87390. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  87391. checkPitch = true;
  87392. }
  87393. if (checkYaw || checkPitch) {
  87394. var spaceMat = BoneLookController._tmpMats[2];
  87395. var spaceMatInv = BoneLookController._tmpMats[3];
  87396. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  87397. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  87398. }
  87399. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  87400. spaceMat.copyFrom(mesh.getWorldMatrix());
  87401. }
  87402. else {
  87403. var forwardAxis = BoneLookController._tmpVecs[2];
  87404. forwardAxis.copyFrom(this._fowardAxis);
  87405. if (this._transformYawPitch) {
  87406. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  87407. }
  87408. if (parentBone) {
  87409. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  87410. }
  87411. else {
  87412. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  87413. }
  87414. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  87415. rightAxis.normalize();
  87416. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  87417. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  87418. }
  87419. spaceMat.invertToRef(spaceMatInv);
  87420. var xzlen = null;
  87421. if (checkPitch) {
  87422. var localTarget = BoneLookController._tmpVecs[3];
  87423. target.subtractToRef(bonePos, localTarget);
  87424. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87425. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87426. var pitch = Math.atan2(localTarget.y, xzlen);
  87427. var newPitch = pitch;
  87428. if (pitch > this._maxPitch) {
  87429. localTarget.y = this._maxPitchTan * xzlen;
  87430. newPitch = this._maxPitch;
  87431. }
  87432. else if (pitch < this._minPitch) {
  87433. localTarget.y = this._minPitchTan * xzlen;
  87434. newPitch = this._minPitch;
  87435. }
  87436. if (pitch != newPitch) {
  87437. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87438. localTarget.addInPlace(bonePos);
  87439. target = localTarget;
  87440. }
  87441. }
  87442. if (checkYaw) {
  87443. var localTarget = BoneLookController._tmpVecs[4];
  87444. target.subtractToRef(bonePos, localTarget);
  87445. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  87446. var yaw = Math.atan2(localTarget.x, localTarget.z);
  87447. var newYaw = yaw;
  87448. if (yaw > this._maxYaw || yaw < this._minYaw) {
  87449. if (xzlen == null) {
  87450. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87451. }
  87452. if (this._yawRange > Math.PI) {
  87453. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  87454. localTarget.z = this._maxYawCos * xzlen;
  87455. localTarget.x = this._maxYawSin * xzlen;
  87456. newYaw = this._maxYaw;
  87457. }
  87458. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  87459. localTarget.z = this._minYawCos * xzlen;
  87460. localTarget.x = this._minYawSin * xzlen;
  87461. newYaw = this._minYaw;
  87462. }
  87463. }
  87464. else {
  87465. if (yaw > this._maxYaw) {
  87466. localTarget.z = this._maxYawCos * xzlen;
  87467. localTarget.x = this._maxYawSin * xzlen;
  87468. newYaw = this._maxYaw;
  87469. }
  87470. else if (yaw < this._minYaw) {
  87471. localTarget.z = this._minYawCos * xzlen;
  87472. localTarget.x = this._minYawSin * xzlen;
  87473. newYaw = this._minYaw;
  87474. }
  87475. }
  87476. }
  87477. if (this._slerping && this._yawRange > Math.PI) {
  87478. //are we going to be crossing into the min/max region?
  87479. var boneFwd = BoneLookController._tmpVecs[8];
  87480. boneFwd.copyFrom(BABYLON.Axis.Z);
  87481. if (this._transformYawPitch) {
  87482. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  87483. }
  87484. var boneRotMat = BoneLookController._tmpMats[4];
  87485. this._boneQuat.toRotationMatrix(boneRotMat);
  87486. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  87487. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  87488. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  87489. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  87490. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  87491. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  87492. if (angBtwTar > angBtwMidYaw) {
  87493. if (xzlen == null) {
  87494. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  87495. }
  87496. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  87497. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  87498. if (angBtwMin < angBtwMax) {
  87499. newYaw = boneYaw + Math.PI * .75;
  87500. localTarget.z = Math.cos(newYaw) * xzlen;
  87501. localTarget.x = Math.sin(newYaw) * xzlen;
  87502. }
  87503. else {
  87504. newYaw = boneYaw - Math.PI * .75;
  87505. localTarget.z = Math.cos(newYaw) * xzlen;
  87506. localTarget.x = Math.sin(newYaw) * xzlen;
  87507. }
  87508. }
  87509. }
  87510. if (yaw != newYaw) {
  87511. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  87512. localTarget.addInPlace(bonePos);
  87513. target = localTarget;
  87514. }
  87515. }
  87516. }
  87517. var zaxis = BoneLookController._tmpVecs[5];
  87518. var xaxis = BoneLookController._tmpVecs[6];
  87519. var yaxis = BoneLookController._tmpVecs[7];
  87520. var _tmpQuat = BoneLookController._tmpQuat;
  87521. target.subtractToRef(bonePos, zaxis);
  87522. zaxis.normalize();
  87523. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  87524. xaxis.normalize();
  87525. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  87526. yaxis.normalize();
  87527. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  87528. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  87529. return;
  87530. }
  87531. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  87532. return;
  87533. }
  87534. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  87535. return;
  87536. }
  87537. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  87538. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  87539. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  87540. }
  87541. if (this.slerpAmount < 1) {
  87542. if (!this._slerping) {
  87543. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  87544. }
  87545. if (this._transformYawPitch) {
  87546. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87547. }
  87548. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  87549. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  87550. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  87551. this._slerping = true;
  87552. }
  87553. else {
  87554. if (this._transformYawPitch) {
  87555. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  87556. }
  87557. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  87558. this._slerping = false;
  87559. }
  87560. };
  87561. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  87562. var angDiff = ang2 - ang1;
  87563. angDiff %= Math.PI * 2;
  87564. if (angDiff > Math.PI) {
  87565. angDiff -= Math.PI * 2;
  87566. }
  87567. else if (angDiff < -Math.PI) {
  87568. angDiff += Math.PI * 2;
  87569. }
  87570. return angDiff;
  87571. };
  87572. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  87573. ang1 %= (2 * Math.PI);
  87574. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87575. ang2 %= (2 * Math.PI);
  87576. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87577. var ab = 0;
  87578. if (ang1 < ang2) {
  87579. ab = ang2 - ang1;
  87580. }
  87581. else {
  87582. ab = ang1 - ang2;
  87583. }
  87584. if (ab > Math.PI) {
  87585. ab = Math.PI * 2 - ab;
  87586. }
  87587. return ab;
  87588. };
  87589. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  87590. ang %= (2 * Math.PI);
  87591. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  87592. ang1 %= (2 * Math.PI);
  87593. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  87594. ang2 %= (2 * Math.PI);
  87595. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  87596. if (ang1 < ang2) {
  87597. if (ang > ang1 && ang < ang2) {
  87598. return true;
  87599. }
  87600. }
  87601. else {
  87602. if (ang > ang2 && ang < ang1) {
  87603. return true;
  87604. }
  87605. }
  87606. return false;
  87607. };
  87608. 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()];
  87609. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  87610. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  87611. return BoneLookController;
  87612. }());
  87613. BABYLON.BoneLookController = BoneLookController;
  87614. })(BABYLON || (BABYLON = {}));
  87615. //# sourceMappingURL=babylon.boneLookController.js.map
  87616. var BABYLON;
  87617. (function (BABYLON) {
  87618. /**
  87619. * Class used to handle skinning animations
  87620. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  87621. */
  87622. var Skeleton = /** @class */ (function () {
  87623. /**
  87624. * Creates a new skeleton
  87625. * @param name defines the skeleton name
  87626. * @param id defines the skeleton Id
  87627. * @param scene defines the hosting scene
  87628. */
  87629. function Skeleton(
  87630. /** defines the skeleton name */
  87631. name,
  87632. /** defines the skeleton Id */
  87633. id, scene) {
  87634. this.name = name;
  87635. this.id = id;
  87636. /**
  87637. * Gets the list of child bones
  87638. */
  87639. this.bones = new Array();
  87640. /**
  87641. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  87642. */
  87643. this.needInitialSkinMatrix = false;
  87644. this._isDirty = true;
  87645. this._meshesWithPoseMatrix = new Array();
  87646. this._identity = BABYLON.Matrix.Identity();
  87647. this._ranges = {};
  87648. this._lastAbsoluteTransformsUpdateId = -1;
  87649. /**
  87650. * Specifies if the skeleton should be serialized
  87651. */
  87652. this.doNotSerialize = false;
  87653. this._animationPropertiesOverride = null;
  87654. // Events
  87655. /**
  87656. * An observable triggered before computing the skeleton's matrices
  87657. */
  87658. this.onBeforeComputeObservable = new BABYLON.Observable();
  87659. this.bones = [];
  87660. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87661. scene.skeletons.push(this);
  87662. //make sure it will recalculate the matrix next time prepare is called.
  87663. this._isDirty = true;
  87664. }
  87665. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  87666. /**
  87667. * Gets or sets the animation properties override
  87668. */
  87669. get: function () {
  87670. if (!this._animationPropertiesOverride) {
  87671. return this._scene.animationPropertiesOverride;
  87672. }
  87673. return this._animationPropertiesOverride;
  87674. },
  87675. set: function (value) {
  87676. this._animationPropertiesOverride = value;
  87677. },
  87678. enumerable: true,
  87679. configurable: true
  87680. });
  87681. // Members
  87682. /**
  87683. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  87684. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  87685. * @returns a Float32Array containing matrices data
  87686. */
  87687. Skeleton.prototype.getTransformMatrices = function (mesh) {
  87688. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  87689. return mesh._bonesTransformMatrices;
  87690. }
  87691. if (!this._transformMatrices) {
  87692. this.prepare();
  87693. }
  87694. return this._transformMatrices;
  87695. };
  87696. /**
  87697. * Gets the current hosting scene
  87698. * @returns a scene object
  87699. */
  87700. Skeleton.prototype.getScene = function () {
  87701. return this._scene;
  87702. };
  87703. // Methods
  87704. /**
  87705. * Gets a string representing the current skeleton data
  87706. * @param fullDetails defines a boolean indicating if we want a verbose version
  87707. * @returns a string representing the current skeleton data
  87708. */
  87709. Skeleton.prototype.toString = function (fullDetails) {
  87710. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  87711. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  87712. if (fullDetails) {
  87713. ret += ", Ranges: {";
  87714. var first = true;
  87715. for (var name_1 in this._ranges) {
  87716. if (first) {
  87717. ret += ", ";
  87718. first = false;
  87719. }
  87720. ret += name_1;
  87721. }
  87722. ret += "}";
  87723. }
  87724. return ret;
  87725. };
  87726. /**
  87727. * Get bone's index searching by name
  87728. * @param name defines bone's name to search for
  87729. * @return the indice of the bone. Returns -1 if not found
  87730. */
  87731. Skeleton.prototype.getBoneIndexByName = function (name) {
  87732. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  87733. if (this.bones[boneIndex].name === name) {
  87734. return boneIndex;
  87735. }
  87736. }
  87737. return -1;
  87738. };
  87739. /**
  87740. * Creater a new animation range
  87741. * @param name defines the name of the range
  87742. * @param from defines the start key
  87743. * @param to defines the end key
  87744. */
  87745. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  87746. // check name not already in use
  87747. if (!this._ranges[name]) {
  87748. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  87749. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87750. if (this.bones[i].animations[0]) {
  87751. this.bones[i].animations[0].createRange(name, from, to);
  87752. }
  87753. }
  87754. }
  87755. };
  87756. /**
  87757. * Delete a specific animation range
  87758. * @param name defines the name of the range
  87759. * @param deleteFrames defines if frames must be removed as well
  87760. */
  87761. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  87762. if (deleteFrames === void 0) { deleteFrames = true; }
  87763. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87764. if (this.bones[i].animations[0]) {
  87765. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  87766. }
  87767. }
  87768. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  87769. };
  87770. /**
  87771. * Gets a specific animation range
  87772. * @param name defines the name of the range to look for
  87773. * @returns the requested animation range or null if not found
  87774. */
  87775. Skeleton.prototype.getAnimationRange = function (name) {
  87776. return this._ranges[name];
  87777. };
  87778. /**
  87779. * Gets the list of all animation ranges defined on this skeleton
  87780. * @returns an array
  87781. */
  87782. Skeleton.prototype.getAnimationRanges = function () {
  87783. var animationRanges = [];
  87784. var name;
  87785. var i = 0;
  87786. for (name in this._ranges) {
  87787. animationRanges[i] = this._ranges[name];
  87788. i++;
  87789. }
  87790. return animationRanges;
  87791. };
  87792. /**
  87793. * Copy animation range from a source skeleton.
  87794. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  87795. * @param source defines the source skeleton
  87796. * @param name defines the name of the range to copy
  87797. * @param rescaleAsRequired defines if rescaling must be applied if required
  87798. * @returns true if operation was successful
  87799. */
  87800. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  87801. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  87802. if (this._ranges[name] || !source.getAnimationRange(name)) {
  87803. return false;
  87804. }
  87805. var ret = true;
  87806. var frameOffset = this._getHighestAnimationFrame() + 1;
  87807. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  87808. var boneDict = {};
  87809. var sourceBones = source.bones;
  87810. var nBones;
  87811. var i;
  87812. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  87813. boneDict[sourceBones[i].name] = sourceBones[i];
  87814. }
  87815. if (this.bones.length !== sourceBones.length) {
  87816. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  87817. ret = false;
  87818. }
  87819. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  87820. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  87821. var boneName = this.bones[i].name;
  87822. var sourceBone = boneDict[boneName];
  87823. if (sourceBone) {
  87824. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  87825. }
  87826. else {
  87827. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  87828. ret = false;
  87829. }
  87830. }
  87831. // do not call createAnimationRange(), since it also is done to bones, which was already done
  87832. var range = source.getAnimationRange(name);
  87833. if (range) {
  87834. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  87835. }
  87836. return ret;
  87837. };
  87838. /**
  87839. * Forces the skeleton to go to rest pose
  87840. */
  87841. Skeleton.prototype.returnToRest = function () {
  87842. for (var index = 0; index < this.bones.length; index++) {
  87843. this.bones[index].returnToRest();
  87844. }
  87845. };
  87846. Skeleton.prototype._getHighestAnimationFrame = function () {
  87847. var ret = 0;
  87848. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  87849. if (this.bones[i].animations[0]) {
  87850. var highest = this.bones[i].animations[0].getHighestFrame();
  87851. if (ret < highest) {
  87852. ret = highest;
  87853. }
  87854. }
  87855. }
  87856. return ret;
  87857. };
  87858. /**
  87859. * Begin a specific animation range
  87860. * @param name defines the name of the range to start
  87861. * @param loop defines if looping must be turned on (false by default)
  87862. * @param speedRatio defines the speed ratio to apply (1 by default)
  87863. * @param onAnimationEnd defines a callback which will be called when animation will end
  87864. * @returns a new animatable
  87865. */
  87866. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  87867. var range = this.getAnimationRange(name);
  87868. if (!range) {
  87869. return null;
  87870. }
  87871. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  87872. };
  87873. /** @hidden */
  87874. Skeleton.prototype._markAsDirty = function () {
  87875. this._isDirty = true;
  87876. };
  87877. /** @hidden */
  87878. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  87879. this._meshesWithPoseMatrix.push(mesh);
  87880. };
  87881. /** @hidden */
  87882. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  87883. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  87884. if (index > -1) {
  87885. this._meshesWithPoseMatrix.splice(index, 1);
  87886. }
  87887. };
  87888. /** @hidden */
  87889. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  87890. this.onBeforeComputeObservable.notifyObservers(this);
  87891. for (var index = 0; index < this.bones.length; index++) {
  87892. var bone = this.bones[index];
  87893. var parentBone = bone.getParent();
  87894. if (parentBone) {
  87895. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  87896. }
  87897. else {
  87898. if (initialSkinMatrix) {
  87899. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  87900. }
  87901. else {
  87902. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  87903. }
  87904. }
  87905. if (bone._index !== -1) {
  87906. var mappedIndex = bone._index === null ? index : bone._index;
  87907. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  87908. }
  87909. }
  87910. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  87911. };
  87912. /**
  87913. * Build all resources required to render a skeleton
  87914. */
  87915. Skeleton.prototype.prepare = function () {
  87916. if (!this._isDirty) {
  87917. return;
  87918. }
  87919. if (this.needInitialSkinMatrix) {
  87920. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  87921. var mesh = this._meshesWithPoseMatrix[index];
  87922. var poseMatrix = mesh.getPoseMatrix();
  87923. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  87924. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  87925. }
  87926. if (this._synchronizedWithMesh !== mesh) {
  87927. this._synchronizedWithMesh = mesh;
  87928. // Prepare bones
  87929. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  87930. var bone = this.bones[boneIndex];
  87931. if (!bone.getParent()) {
  87932. var matrix = bone.getBaseMatrix();
  87933. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  87934. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  87935. }
  87936. }
  87937. }
  87938. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  87939. }
  87940. }
  87941. else {
  87942. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  87943. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  87944. }
  87945. this._computeTransformMatrices(this._transformMatrices, null);
  87946. }
  87947. this._isDirty = false;
  87948. this._scene._activeBones.addCount(this.bones.length, false);
  87949. };
  87950. /**
  87951. * Gets the list of animatables currently running for this skeleton
  87952. * @returns an array of animatables
  87953. */
  87954. Skeleton.prototype.getAnimatables = function () {
  87955. if (!this._animatables || this._animatables.length !== this.bones.length) {
  87956. this._animatables = [];
  87957. for (var index = 0; index < this.bones.length; index++) {
  87958. this._animatables.push(this.bones[index]);
  87959. }
  87960. }
  87961. return this._animatables;
  87962. };
  87963. /**
  87964. * Clone the current skeleton
  87965. * @param name defines the name of the new skeleton
  87966. * @param id defines the id of the enw skeleton
  87967. * @returns the new skeleton
  87968. */
  87969. Skeleton.prototype.clone = function (name, id) {
  87970. var result = new Skeleton(name, id || name, this._scene);
  87971. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  87972. for (var index = 0; index < this.bones.length; index++) {
  87973. var source = this.bones[index];
  87974. var parentBone = null;
  87975. var parent_1 = source.getParent();
  87976. if (parent_1) {
  87977. var parentIndex = this.bones.indexOf(parent_1);
  87978. parentBone = result.bones[parentIndex];
  87979. }
  87980. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  87981. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  87982. }
  87983. if (this._ranges) {
  87984. result._ranges = {};
  87985. for (var rangeName in this._ranges) {
  87986. var range = this._ranges[rangeName];
  87987. if (range) {
  87988. result._ranges[rangeName] = range.clone();
  87989. }
  87990. }
  87991. }
  87992. this._isDirty = true;
  87993. return result;
  87994. };
  87995. /**
  87996. * Enable animation blending for this skeleton
  87997. * @param blendingSpeed defines the blending speed to apply
  87998. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  87999. */
  88000. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  88001. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  88002. this.bones.forEach(function (bone) {
  88003. bone.animations.forEach(function (animation) {
  88004. animation.enableBlending = true;
  88005. animation.blendingSpeed = blendingSpeed;
  88006. });
  88007. });
  88008. };
  88009. /**
  88010. * Releases all resources associated with the current skeleton
  88011. */
  88012. Skeleton.prototype.dispose = function () {
  88013. this._meshesWithPoseMatrix = [];
  88014. // Animations
  88015. this.getScene().stopAnimation(this);
  88016. // Remove from scene
  88017. this.getScene().removeSkeleton(this);
  88018. };
  88019. /**
  88020. * Serialize the skeleton in a JSON object
  88021. * @returns a JSON object
  88022. */
  88023. Skeleton.prototype.serialize = function () {
  88024. var serializationObject = {};
  88025. serializationObject.name = this.name;
  88026. serializationObject.id = this.id;
  88027. if (this.dimensionsAtRest) {
  88028. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  88029. }
  88030. serializationObject.bones = [];
  88031. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  88032. for (var index = 0; index < this.bones.length; index++) {
  88033. var bone = this.bones[index];
  88034. var parent_2 = bone.getParent();
  88035. var serializedBone = {
  88036. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  88037. name: bone.name,
  88038. matrix: bone.getBaseMatrix().toArray(),
  88039. rest: bone.getRestPose().toArray()
  88040. };
  88041. serializationObject.bones.push(serializedBone);
  88042. if (bone.length) {
  88043. serializedBone.length = bone.length;
  88044. }
  88045. if (bone.metadata) {
  88046. serializedBone.metadata = bone.metadata;
  88047. }
  88048. if (bone.animations && bone.animations.length > 0) {
  88049. serializedBone.animation = bone.animations[0].serialize();
  88050. }
  88051. serializationObject.ranges = [];
  88052. for (var name in this._ranges) {
  88053. var source = this._ranges[name];
  88054. if (!source) {
  88055. continue;
  88056. }
  88057. var range = {};
  88058. range.name = name;
  88059. range.from = source.from;
  88060. range.to = source.to;
  88061. serializationObject.ranges.push(range);
  88062. }
  88063. }
  88064. return serializationObject;
  88065. };
  88066. /**
  88067. * Creates a new skeleton from serialized data
  88068. * @param parsedSkeleton defines the serialized data
  88069. * @param scene defines the hosting scene
  88070. * @returns a new skeleton
  88071. */
  88072. Skeleton.Parse = function (parsedSkeleton, scene) {
  88073. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  88074. if (parsedSkeleton.dimensionsAtRest) {
  88075. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  88076. }
  88077. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  88078. var index;
  88079. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  88080. var parsedBone = parsedSkeleton.bones[index];
  88081. var parentBone = null;
  88082. if (parsedBone.parentBoneIndex > -1) {
  88083. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  88084. }
  88085. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  88086. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  88087. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  88088. bone.id = parsedBone.id;
  88089. }
  88090. if (parsedBone.length) {
  88091. bone.length = parsedBone.length;
  88092. }
  88093. if (parsedBone.metadata) {
  88094. bone.metadata = parsedBone.metadata;
  88095. }
  88096. if (parsedBone.animation) {
  88097. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  88098. }
  88099. }
  88100. // placed after bones, so createAnimationRange can cascade down
  88101. if (parsedSkeleton.ranges) {
  88102. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  88103. var data = parsedSkeleton.ranges[index];
  88104. skeleton.createAnimationRange(data.name, data.from, data.to);
  88105. }
  88106. }
  88107. return skeleton;
  88108. };
  88109. /**
  88110. * Compute all node absolute transforms
  88111. * @param forceUpdate defines if computation must be done even if cache is up to date
  88112. */
  88113. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  88114. if (forceUpdate === void 0) { forceUpdate = false; }
  88115. var renderId = this._scene.getRenderId();
  88116. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  88117. this.bones[0].computeAbsoluteTransforms();
  88118. this._lastAbsoluteTransformsUpdateId = renderId;
  88119. }
  88120. };
  88121. /**
  88122. * Gets the root pose matrix
  88123. * @returns a matrix
  88124. */
  88125. Skeleton.prototype.getPoseMatrix = function () {
  88126. var poseMatrix = null;
  88127. if (this._meshesWithPoseMatrix.length > 0) {
  88128. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  88129. }
  88130. return poseMatrix;
  88131. };
  88132. /**
  88133. * Sorts bones per internal index
  88134. */
  88135. Skeleton.prototype.sortBones = function () {
  88136. var bones = new Array();
  88137. var visited = new Array(this.bones.length);
  88138. for (var index = 0; index < this.bones.length; index++) {
  88139. this._sortBones(index, bones, visited);
  88140. }
  88141. this.bones = bones;
  88142. };
  88143. Skeleton.prototype._sortBones = function (index, bones, visited) {
  88144. if (visited[index]) {
  88145. return;
  88146. }
  88147. visited[index] = true;
  88148. var bone = this.bones[index];
  88149. if (bone._index === undefined) {
  88150. bone._index = index;
  88151. }
  88152. var parentBone = bone.getParent();
  88153. if (parentBone) {
  88154. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  88155. }
  88156. bones.push(bone);
  88157. };
  88158. return Skeleton;
  88159. }());
  88160. BABYLON.Skeleton = Skeleton;
  88161. })(BABYLON || (BABYLON = {}));
  88162. //# sourceMappingURL=babylon.skeleton.js.map
  88163. var BABYLON;
  88164. (function (BABYLON) {
  88165. ;
  88166. /**
  88167. * This groups tools to convert HDR texture to native colors array.
  88168. */
  88169. var HDRTools = /** @class */ (function () {
  88170. function HDRTools() {
  88171. }
  88172. HDRTools.Ldexp = function (mantissa, exponent) {
  88173. if (exponent > 1023) {
  88174. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  88175. }
  88176. if (exponent < -1074) {
  88177. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  88178. }
  88179. return mantissa * Math.pow(2, exponent);
  88180. };
  88181. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  88182. if (exponent > 0) { /*nonzero pixel*/
  88183. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  88184. float32array[index + 0] = red * exponent;
  88185. float32array[index + 1] = green * exponent;
  88186. float32array[index + 2] = blue * exponent;
  88187. }
  88188. else {
  88189. float32array[index + 0] = 0;
  88190. float32array[index + 1] = 0;
  88191. float32array[index + 2] = 0;
  88192. }
  88193. };
  88194. HDRTools.readStringLine = function (uint8array, startIndex) {
  88195. var line = "";
  88196. var character = "";
  88197. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  88198. character = String.fromCharCode(uint8array[i]);
  88199. if (character == "\n") {
  88200. break;
  88201. }
  88202. line += character;
  88203. }
  88204. return line;
  88205. };
  88206. /**
  88207. * Reads header information from an RGBE texture stored in a native array.
  88208. * More information on this format are available here:
  88209. * https://en.wikipedia.org/wiki/RGBE_image_format
  88210. *
  88211. * @param uint8array The binary file stored in native array.
  88212. * @return The header information.
  88213. */
  88214. HDRTools.RGBE_ReadHeader = function (uint8array) {
  88215. var height = 0;
  88216. var width = 0;
  88217. var line = this.readStringLine(uint8array, 0);
  88218. if (line[0] != '#' || line[1] != '?') {
  88219. throw "Bad HDR Format.";
  88220. }
  88221. var endOfHeader = false;
  88222. var findFormat = false;
  88223. var lineIndex = 0;
  88224. do {
  88225. lineIndex += (line.length + 1);
  88226. line = this.readStringLine(uint8array, lineIndex);
  88227. if (line == "FORMAT=32-bit_rle_rgbe") {
  88228. findFormat = true;
  88229. }
  88230. else if (line.length == 0) {
  88231. endOfHeader = true;
  88232. }
  88233. } while (!endOfHeader);
  88234. if (!findFormat) {
  88235. throw "HDR Bad header format, unsupported FORMAT";
  88236. }
  88237. lineIndex += (line.length + 1);
  88238. line = this.readStringLine(uint8array, lineIndex);
  88239. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  88240. var match = sizeRegexp.exec(line);
  88241. // TODO. Support +Y and -X if needed.
  88242. if (!match || match.length < 3) {
  88243. throw "HDR Bad header format, no size";
  88244. }
  88245. width = parseInt(match[2]);
  88246. height = parseInt(match[1]);
  88247. if (width < 8 || width > 0x7fff) {
  88248. throw "HDR Bad header format, unsupported size";
  88249. }
  88250. lineIndex += (line.length + 1);
  88251. return {
  88252. height: height,
  88253. width: width,
  88254. dataPosition: lineIndex
  88255. };
  88256. };
  88257. /**
  88258. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  88259. * This RGBE texture needs to store the information as a panorama.
  88260. *
  88261. * More information on this format are available here:
  88262. * https://en.wikipedia.org/wiki/RGBE_image_format
  88263. *
  88264. * @param buffer The binary file stored in an array buffer.
  88265. * @param size The expected size of the extracted cubemap.
  88266. * @return The Cube Map information.
  88267. */
  88268. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  88269. var uint8array = new Uint8Array(buffer);
  88270. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  88271. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88272. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  88273. return cubeMapData;
  88274. };
  88275. /**
  88276. * Returns the pixels data extracted from an RGBE texture.
  88277. * This pixels will be stored left to right up to down in the R G B order in one array.
  88278. *
  88279. * More information on this format are available here:
  88280. * https://en.wikipedia.org/wiki/RGBE_image_format
  88281. *
  88282. * @param uint8array The binary file stored in an array buffer.
  88283. * @param hdrInfo The header information of the file.
  88284. * @return The pixels data in RGB right to left up to down order.
  88285. */
  88286. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  88287. // Keep for multi format supports.
  88288. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  88289. };
  88290. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  88291. var num_scanlines = hdrInfo.height;
  88292. var scanline_width = hdrInfo.width;
  88293. var a, b, c, d, count;
  88294. var dataIndex = hdrInfo.dataPosition;
  88295. var index = 0, endIndex = 0, i = 0;
  88296. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  88297. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  88298. // 3 channels of 4 bytes per pixel in float.
  88299. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  88300. var resultArray = new Float32Array(resultBuffer);
  88301. // read in each successive scanline
  88302. while (num_scanlines > 0) {
  88303. a = uint8array[dataIndex++];
  88304. b = uint8array[dataIndex++];
  88305. c = uint8array[dataIndex++];
  88306. d = uint8array[dataIndex++];
  88307. if (a != 2 || b != 2 || (c & 0x80)) {
  88308. // this file is not run length encoded
  88309. throw "HDR Bad header format, not RLE";
  88310. }
  88311. if (((c << 8) | d) != scanline_width) {
  88312. throw "HDR Bad header format, wrong scan line width";
  88313. }
  88314. index = 0;
  88315. // read each of the four channels for the scanline into the buffer
  88316. for (i = 0; i < 4; i++) {
  88317. endIndex = (i + 1) * scanline_width;
  88318. while (index < endIndex) {
  88319. a = uint8array[dataIndex++];
  88320. b = uint8array[dataIndex++];
  88321. if (a > 128) {
  88322. // a run of the same value
  88323. count = a - 128;
  88324. if ((count == 0) || (count > endIndex - index)) {
  88325. throw "HDR Bad Format, bad scanline data (run)";
  88326. }
  88327. while (count-- > 0) {
  88328. scanLineArray[index++] = b;
  88329. }
  88330. }
  88331. else {
  88332. // a non-run
  88333. count = a;
  88334. if ((count == 0) || (count > endIndex - index)) {
  88335. throw "HDR Bad Format, bad scanline data (non-run)";
  88336. }
  88337. scanLineArray[index++] = b;
  88338. if (--count > 0) {
  88339. for (var j = 0; j < count; j++) {
  88340. scanLineArray[index++] = uint8array[dataIndex++];
  88341. }
  88342. }
  88343. }
  88344. }
  88345. }
  88346. // now convert data from buffer into floats
  88347. for (i = 0; i < scanline_width; i++) {
  88348. a = scanLineArray[i];
  88349. b = scanLineArray[i + scanline_width];
  88350. c = scanLineArray[i + 2 * scanline_width];
  88351. d = scanLineArray[i + 3 * scanline_width];
  88352. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  88353. }
  88354. num_scanlines--;
  88355. }
  88356. return resultArray;
  88357. };
  88358. return HDRTools;
  88359. }());
  88360. BABYLON.HDRTools = HDRTools;
  88361. })(BABYLON || (BABYLON = {}));
  88362. //# sourceMappingURL=babylon.hdr.js.map
  88363. var BABYLON;
  88364. (function (BABYLON) {
  88365. /**
  88366. * This represents a texture coming from an HDR input.
  88367. *
  88368. * The only supported format is currently panorama picture stored in RGBE format.
  88369. * Example of such files can be found on HDRLib: http://hdrlib.com/
  88370. */
  88371. var HDRCubeTexture = /** @class */ (function (_super) {
  88372. __extends(HDRCubeTexture, _super);
  88373. /**
  88374. * Instantiates an HDRTexture from the following parameters.
  88375. *
  88376. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  88377. * @param scene The scene the texture will be used in
  88378. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  88379. * @param noMipmap Forces to not generate the mipmap if true
  88380. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  88381. * @param gammaSpace 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)
  88382. * @param reserved Reserved flag for internal use.
  88383. */
  88384. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  88385. if (noMipmap === void 0) { noMipmap = false; }
  88386. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88387. if (gammaSpace === void 0) { gammaSpace = false; }
  88388. if (reserved === void 0) { reserved = false; }
  88389. if (onLoad === void 0) { onLoad = null; }
  88390. if (onError === void 0) { onError = null; }
  88391. var _this = _super.call(this, scene) || this;
  88392. _this._generateHarmonics = true;
  88393. _this._onLoad = null;
  88394. _this._onError = null;
  88395. /**
  88396. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  88397. */
  88398. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  88399. _this._isBlocking = true;
  88400. _this._rotationY = 0;
  88401. /**
  88402. * Gets or sets the center of the bounding box associated with the cube texture
  88403. * It must define where the camera used to render the texture was set
  88404. */
  88405. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  88406. if (!url) {
  88407. return _this;
  88408. }
  88409. _this.name = url;
  88410. _this.url = url;
  88411. _this.hasAlpha = false;
  88412. _this.isCube = true;
  88413. _this._textureMatrix = BABYLON.Matrix.Identity();
  88414. _this._onLoad = onLoad;
  88415. _this._onError = onError;
  88416. _this.gammaSpace = gammaSpace;
  88417. _this._noMipmap = noMipmap;
  88418. _this._size = size;
  88419. _this._texture = _this._getFromCache(url, _this._noMipmap);
  88420. if (!_this._texture) {
  88421. if (!scene.useDelayedTextureLoading) {
  88422. _this.loadTexture();
  88423. }
  88424. else {
  88425. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  88426. }
  88427. }
  88428. return _this;
  88429. }
  88430. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  88431. /**
  88432. * Gets wether or not the texture is blocking during loading.
  88433. */
  88434. get: function () {
  88435. return this._isBlocking;
  88436. },
  88437. /**
  88438. * Sets wether or not the texture is blocking during loading.
  88439. */
  88440. set: function (value) {
  88441. this._isBlocking = value;
  88442. },
  88443. enumerable: true,
  88444. configurable: true
  88445. });
  88446. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  88447. /**
  88448. * Gets texture matrix rotation angle around Y axis radians.
  88449. */
  88450. get: function () {
  88451. return this._rotationY;
  88452. },
  88453. /**
  88454. * Sets texture matrix rotation angle around Y axis in radians.
  88455. */
  88456. set: function (value) {
  88457. this._rotationY = value;
  88458. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  88459. },
  88460. enumerable: true,
  88461. configurable: true
  88462. });
  88463. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  88464. get: function () {
  88465. return this._boundingBoxSize;
  88466. },
  88467. /**
  88468. * Gets or sets the size of the bounding box associated with the cube texture
  88469. * When defined, the cubemap will switch to local mode
  88470. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  88471. * @example https://www.babylonjs-playground.com/#RNASML
  88472. */
  88473. set: function (value) {
  88474. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  88475. return;
  88476. }
  88477. this._boundingBoxSize = value;
  88478. var scene = this.getScene();
  88479. if (scene) {
  88480. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  88481. }
  88482. },
  88483. enumerable: true,
  88484. configurable: true
  88485. });
  88486. /**
  88487. * Occurs when the file is raw .hdr file.
  88488. */
  88489. HDRCubeTexture.prototype.loadTexture = function () {
  88490. var _this = this;
  88491. var callback = function (buffer) {
  88492. _this.lodGenerationOffset = 0.0;
  88493. _this.lodGenerationScale = 0.8;
  88494. var scene = _this.getScene();
  88495. if (!scene) {
  88496. return null;
  88497. }
  88498. // Extract the raw linear data.
  88499. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  88500. // Generate harmonics if needed.
  88501. if (_this._generateHarmonics) {
  88502. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  88503. _this.sphericalPolynomial = sphericalPolynomial;
  88504. }
  88505. var results = [];
  88506. var byteArray = null;
  88507. // Push each faces.
  88508. for (var j = 0; j < 6; j++) {
  88509. // Create uintarray fallback.
  88510. if (!scene.getEngine().getCaps().textureFloat) {
  88511. // 3 channels of 1 bytes per pixel in bytes.
  88512. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  88513. byteArray = new Uint8Array(byteBuffer);
  88514. }
  88515. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  88516. // If special cases.
  88517. if (_this.gammaSpace || byteArray) {
  88518. for (var i = 0; i < _this._size * _this._size; i++) {
  88519. // Put in gamma space if requested.
  88520. if (_this.gammaSpace) {
  88521. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  88522. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  88523. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  88524. }
  88525. // Convert to int texture for fallback.
  88526. if (byteArray) {
  88527. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  88528. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  88529. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  88530. // May use luminance instead if the result is not accurate.
  88531. var max = Math.max(Math.max(r, g), b);
  88532. if (max > 255) {
  88533. var scale = 255 / max;
  88534. r *= scale;
  88535. g *= scale;
  88536. b *= scale;
  88537. }
  88538. byteArray[(i * 3) + 0] = r;
  88539. byteArray[(i * 3) + 1] = g;
  88540. byteArray[(i * 3) + 2] = b;
  88541. }
  88542. }
  88543. }
  88544. if (byteArray) {
  88545. results.push(byteArray);
  88546. }
  88547. else {
  88548. results.push(dataFace);
  88549. }
  88550. }
  88551. return results;
  88552. };
  88553. var scene = this.getScene();
  88554. if (scene) {
  88555. 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, null, this._onLoad, this._onError);
  88556. }
  88557. };
  88558. HDRCubeTexture.prototype.clone = function () {
  88559. var scene = this.getScene();
  88560. if (!scene) {
  88561. return this;
  88562. }
  88563. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  88564. // Base texture
  88565. newTexture.level = this.level;
  88566. newTexture.wrapU = this.wrapU;
  88567. newTexture.wrapV = this.wrapV;
  88568. newTexture.coordinatesIndex = this.coordinatesIndex;
  88569. newTexture.coordinatesMode = this.coordinatesMode;
  88570. return newTexture;
  88571. };
  88572. // Methods
  88573. HDRCubeTexture.prototype.delayLoad = function () {
  88574. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88575. return;
  88576. }
  88577. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88578. this._texture = this._getFromCache(this.url, this._noMipmap);
  88579. if (!this._texture) {
  88580. this.loadTexture();
  88581. }
  88582. };
  88583. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  88584. return this._textureMatrix;
  88585. };
  88586. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  88587. this._textureMatrix = value;
  88588. };
  88589. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88590. var texture = null;
  88591. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88592. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  88593. texture.name = parsedTexture.name;
  88594. texture.hasAlpha = parsedTexture.hasAlpha;
  88595. texture.level = parsedTexture.level;
  88596. texture.coordinatesMode = parsedTexture.coordinatesMode;
  88597. texture.isBlocking = parsedTexture.isBlocking;
  88598. }
  88599. if (texture) {
  88600. if (parsedTexture.boundingBoxPosition) {
  88601. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  88602. }
  88603. if (parsedTexture.boundingBoxSize) {
  88604. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  88605. }
  88606. if (parsedTexture.rotationY) {
  88607. texture.rotationY = parsedTexture.rotationY;
  88608. }
  88609. }
  88610. return texture;
  88611. };
  88612. HDRCubeTexture.prototype.serialize = function () {
  88613. if (!this.name) {
  88614. return null;
  88615. }
  88616. var serializationObject = {};
  88617. serializationObject.name = this.name;
  88618. serializationObject.hasAlpha = this.hasAlpha;
  88619. serializationObject.isCube = true;
  88620. serializationObject.level = this.level;
  88621. serializationObject.size = this._size;
  88622. serializationObject.coordinatesMode = this.coordinatesMode;
  88623. serializationObject.useInGammaSpace = this.gammaSpace;
  88624. serializationObject.generateHarmonics = this._generateHarmonics;
  88625. serializationObject.customType = "BABYLON.HDRCubeTexture";
  88626. serializationObject.noMipmap = this._noMipmap;
  88627. serializationObject.isBlocking = this._isBlocking;
  88628. serializationObject.rotationY = this._rotationY;
  88629. return serializationObject;
  88630. };
  88631. HDRCubeTexture._facesMapping = [
  88632. "right",
  88633. "left",
  88634. "up",
  88635. "down",
  88636. "front",
  88637. "back"
  88638. ];
  88639. return HDRCubeTexture;
  88640. }(BABYLON.BaseTexture));
  88641. BABYLON.HDRCubeTexture = HDRCubeTexture;
  88642. })(BABYLON || (BABYLON = {}));
  88643. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  88644. var BABYLON;
  88645. (function (BABYLON) {
  88646. /**
  88647. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  88648. */
  88649. var PanoramaToCubeMapTools = /** @class */ (function () {
  88650. function PanoramaToCubeMapTools() {
  88651. }
  88652. /**
  88653. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  88654. *
  88655. * @param float32Array The source data.
  88656. * @param inputWidth The width of the input panorama.
  88657. * @param inputhHeight The height of the input panorama.
  88658. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  88659. * @return The cubemap data
  88660. */
  88661. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  88662. if (!float32Array) {
  88663. throw "ConvertPanoramaToCubemap: input cannot be null";
  88664. }
  88665. if (float32Array.length != inputWidth * inputHeight * 3) {
  88666. throw "ConvertPanoramaToCubemap: input size is wrong";
  88667. }
  88668. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  88669. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  88670. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  88671. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  88672. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  88673. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  88674. return {
  88675. front: textureFront,
  88676. back: textureBack,
  88677. left: textureLeft,
  88678. right: textureRight,
  88679. up: textureUp,
  88680. down: textureDown,
  88681. size: size,
  88682. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  88683. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  88684. gammaSpace: false,
  88685. };
  88686. };
  88687. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  88688. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  88689. var textureArray = new Float32Array(buffer);
  88690. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  88691. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  88692. var dy = 1 / texSize;
  88693. var fy = 0;
  88694. for (var y = 0; y < texSize; y++) {
  88695. var xv1 = faceData[0];
  88696. var xv2 = faceData[2];
  88697. for (var x = 0; x < texSize; x++) {
  88698. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  88699. v.normalize();
  88700. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  88701. // 3 channels per pixels
  88702. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  88703. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  88704. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  88705. xv1 = xv1.add(rotDX1);
  88706. xv2 = xv2.add(rotDX2);
  88707. }
  88708. fy += dy;
  88709. }
  88710. return textureArray;
  88711. };
  88712. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  88713. var theta = Math.atan2(vDir.z, vDir.x);
  88714. var phi = Math.acos(vDir.y);
  88715. while (theta < -Math.PI)
  88716. theta += 2 * Math.PI;
  88717. while (theta > Math.PI)
  88718. theta -= 2 * Math.PI;
  88719. var dx = theta / Math.PI;
  88720. var dy = phi / Math.PI;
  88721. // recenter.
  88722. dx = dx * 0.5 + 0.5;
  88723. var px = Math.round(dx * inputWidth);
  88724. if (px < 0)
  88725. px = 0;
  88726. else if (px >= inputWidth)
  88727. px = inputWidth - 1;
  88728. var py = Math.round(dy * inputHeight);
  88729. if (py < 0)
  88730. py = 0;
  88731. else if (py >= inputHeight)
  88732. py = inputHeight - 1;
  88733. var inputY = (inputHeight - py - 1);
  88734. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  88735. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  88736. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  88737. return {
  88738. r: r,
  88739. g: g,
  88740. b: b
  88741. };
  88742. };
  88743. PanoramaToCubeMapTools.FACE_FRONT = [
  88744. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88745. new BABYLON.Vector3(1.0, -1.0, -1.0),
  88746. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  88747. new BABYLON.Vector3(1.0, 1.0, -1.0)
  88748. ];
  88749. PanoramaToCubeMapTools.FACE_BACK = [
  88750. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88751. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88752. new BABYLON.Vector3(1.0, 1.0, 1.0),
  88753. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  88754. ];
  88755. PanoramaToCubeMapTools.FACE_RIGHT = [
  88756. new BABYLON.Vector3(1.0, -1.0, -1.0),
  88757. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88758. new BABYLON.Vector3(1.0, 1.0, -1.0),
  88759. new BABYLON.Vector3(1.0, 1.0, 1.0)
  88760. ];
  88761. PanoramaToCubeMapTools.FACE_LEFT = [
  88762. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88763. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88764. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  88765. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  88766. ];
  88767. PanoramaToCubeMapTools.FACE_DOWN = [
  88768. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  88769. new BABYLON.Vector3(1.0, 1.0, -1.0),
  88770. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  88771. new BABYLON.Vector3(1.0, 1.0, 1.0)
  88772. ];
  88773. PanoramaToCubeMapTools.FACE_UP = [
  88774. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  88775. new BABYLON.Vector3(1.0, -1.0, 1.0),
  88776. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  88777. new BABYLON.Vector3(1.0, -1.0, -1.0)
  88778. ];
  88779. return PanoramaToCubeMapTools;
  88780. }());
  88781. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  88782. })(BABYLON || (BABYLON = {}));
  88783. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  88784. var BABYLON;
  88785. (function (BABYLON) {
  88786. var IndexedVector2 = /** @class */ (function (_super) {
  88787. __extends(IndexedVector2, _super);
  88788. function IndexedVector2(original, index) {
  88789. var _this = _super.call(this, original.x, original.y) || this;
  88790. _this.index = index;
  88791. return _this;
  88792. }
  88793. return IndexedVector2;
  88794. }(BABYLON.Vector2));
  88795. var PolygonPoints = /** @class */ (function () {
  88796. function PolygonPoints() {
  88797. this.elements = new Array();
  88798. }
  88799. PolygonPoints.prototype.add = function (originalPoints) {
  88800. var _this = this;
  88801. var result = new Array();
  88802. originalPoints.forEach(function (point) {
  88803. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  88804. var newPoint = new IndexedVector2(point, _this.elements.length);
  88805. result.push(newPoint);
  88806. _this.elements.push(newPoint);
  88807. }
  88808. });
  88809. return result;
  88810. };
  88811. PolygonPoints.prototype.computeBounds = function () {
  88812. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  88813. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  88814. this.elements.forEach(function (point) {
  88815. // x
  88816. if (point.x < lmin.x) {
  88817. lmin.x = point.x;
  88818. }
  88819. else if (point.x > lmax.x) {
  88820. lmax.x = point.x;
  88821. }
  88822. // y
  88823. if (point.y < lmin.y) {
  88824. lmin.y = point.y;
  88825. }
  88826. else if (point.y > lmax.y) {
  88827. lmax.y = point.y;
  88828. }
  88829. });
  88830. return {
  88831. min: lmin,
  88832. max: lmax,
  88833. width: lmax.x - lmin.x,
  88834. height: lmax.y - lmin.y
  88835. };
  88836. };
  88837. return PolygonPoints;
  88838. }());
  88839. var Polygon = /** @class */ (function () {
  88840. function Polygon() {
  88841. }
  88842. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  88843. return [
  88844. new BABYLON.Vector2(xmin, ymin),
  88845. new BABYLON.Vector2(xmax, ymin),
  88846. new BABYLON.Vector2(xmax, ymax),
  88847. new BABYLON.Vector2(xmin, ymax)
  88848. ];
  88849. };
  88850. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  88851. if (cx === void 0) { cx = 0; }
  88852. if (cy === void 0) { cy = 0; }
  88853. if (numberOfSides === void 0) { numberOfSides = 32; }
  88854. var result = new Array();
  88855. var angle = 0;
  88856. var increment = (Math.PI * 2) / numberOfSides;
  88857. for (var i = 0; i < numberOfSides; i++) {
  88858. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  88859. angle -= increment;
  88860. }
  88861. return result;
  88862. };
  88863. Polygon.Parse = function (input) {
  88864. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  88865. var i, result = [];
  88866. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  88867. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  88868. }
  88869. return result;
  88870. };
  88871. Polygon.StartingAt = function (x, y) {
  88872. return BABYLON.Path2.StartingAt(x, y);
  88873. };
  88874. return Polygon;
  88875. }());
  88876. BABYLON.Polygon = Polygon;
  88877. var PolygonMeshBuilder = /** @class */ (function () {
  88878. function PolygonMeshBuilder(name, contours, scene) {
  88879. this._points = new PolygonPoints();
  88880. this._outlinepoints = new PolygonPoints();
  88881. this._holes = new Array();
  88882. this._epoints = new Array();
  88883. this._eholes = new Array();
  88884. this._name = name;
  88885. this._scene = scene;
  88886. var points;
  88887. if (contours instanceof BABYLON.Path2) {
  88888. points = contours.getPoints();
  88889. }
  88890. else {
  88891. points = contours;
  88892. }
  88893. this._addToepoint(points);
  88894. this._points.add(points);
  88895. this._outlinepoints.add(points);
  88896. if (typeof earcut === 'undefined') {
  88897. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  88898. }
  88899. }
  88900. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  88901. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  88902. var p = points_1[_i];
  88903. this._epoints.push(p.x, p.y);
  88904. }
  88905. };
  88906. PolygonMeshBuilder.prototype.addHole = function (hole) {
  88907. this._points.add(hole);
  88908. var holepoints = new PolygonPoints();
  88909. holepoints.add(hole);
  88910. this._holes.push(holepoints);
  88911. this._eholes.push(this._epoints.length / 2);
  88912. this._addToepoint(hole);
  88913. return this;
  88914. };
  88915. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  88916. var _this = this;
  88917. if (updatable === void 0) { updatable = false; }
  88918. if (depth === void 0) { depth = 0; }
  88919. var result = new BABYLON.Mesh(this._name, this._scene);
  88920. var normals = new Array();
  88921. var positions = new Array();
  88922. var uvs = new Array();
  88923. var bounds = this._points.computeBounds();
  88924. this._points.elements.forEach(function (p) {
  88925. normals.push(0, 1.0, 0);
  88926. positions.push(p.x, 0, p.y);
  88927. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  88928. });
  88929. var indices = new Array();
  88930. var res = earcut(this._epoints, this._eholes, 2);
  88931. for (var i = 0; i < res.length; i++) {
  88932. indices.push(res[i]);
  88933. }
  88934. if (depth > 0) {
  88935. var positionscount = (positions.length / 3); //get the current pointcount
  88936. this._points.elements.forEach(function (p) {
  88937. normals.push(0, -1.0, 0);
  88938. positions.push(p.x, -depth, p.y);
  88939. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  88940. });
  88941. var totalCount = indices.length;
  88942. for (var i = 0; i < totalCount; i += 3) {
  88943. var i0 = indices[i + 0];
  88944. var i1 = indices[i + 1];
  88945. var i2 = indices[i + 2];
  88946. indices.push(i2 + positionscount);
  88947. indices.push(i1 + positionscount);
  88948. indices.push(i0 + positionscount);
  88949. }
  88950. //Add the sides
  88951. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  88952. this._holes.forEach(function (hole) {
  88953. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  88954. });
  88955. }
  88956. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  88957. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  88958. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  88959. result.setIndices(indices);
  88960. return result;
  88961. };
  88962. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  88963. var StartIndex = positions.length / 3;
  88964. var ulength = 0;
  88965. for (var i = 0; i < points.elements.length; i++) {
  88966. var p = points.elements[i];
  88967. var p1;
  88968. if ((i + 1) > points.elements.length - 1) {
  88969. p1 = points.elements[0];
  88970. }
  88971. else {
  88972. p1 = points.elements[i + 1];
  88973. }
  88974. positions.push(p.x, 0, p.y);
  88975. positions.push(p.x, -depth, p.y);
  88976. positions.push(p1.x, 0, p1.y);
  88977. positions.push(p1.x, -depth, p1.y);
  88978. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  88979. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  88980. var v3 = v2.subtract(v1);
  88981. var v4 = new BABYLON.Vector3(0, 1, 0);
  88982. var vn = BABYLON.Vector3.Cross(v3, v4);
  88983. vn = vn.normalize();
  88984. uvs.push(ulength / bounds.width, 0);
  88985. uvs.push(ulength / bounds.width, 1);
  88986. ulength += v3.length();
  88987. uvs.push((ulength / bounds.width), 0);
  88988. uvs.push((ulength / bounds.width), 1);
  88989. if (!flip) {
  88990. normals.push(-vn.x, -vn.y, -vn.z);
  88991. normals.push(-vn.x, -vn.y, -vn.z);
  88992. normals.push(-vn.x, -vn.y, -vn.z);
  88993. normals.push(-vn.x, -vn.y, -vn.z);
  88994. indices.push(StartIndex);
  88995. indices.push(StartIndex + 1);
  88996. indices.push(StartIndex + 2);
  88997. indices.push(StartIndex + 1);
  88998. indices.push(StartIndex + 3);
  88999. indices.push(StartIndex + 2);
  89000. }
  89001. else {
  89002. normals.push(vn.x, vn.y, vn.z);
  89003. normals.push(vn.x, vn.y, vn.z);
  89004. normals.push(vn.x, vn.y, vn.z);
  89005. normals.push(vn.x, vn.y, vn.z);
  89006. indices.push(StartIndex);
  89007. indices.push(StartIndex + 2);
  89008. indices.push(StartIndex + 1);
  89009. indices.push(StartIndex + 1);
  89010. indices.push(StartIndex + 2);
  89011. indices.push(StartIndex + 3);
  89012. }
  89013. StartIndex += 4;
  89014. }
  89015. ;
  89016. };
  89017. return PolygonMeshBuilder;
  89018. }());
  89019. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  89020. })(BABYLON || (BABYLON = {}));
  89021. //# sourceMappingURL=babylon.polygonMesh.js.map
  89022. var BABYLON;
  89023. (function (BABYLON) {
  89024. // Unique ID when we import meshes from Babylon to CSG
  89025. var currentCSGMeshId = 0;
  89026. // # class Vertex
  89027. // Represents a vertex of a polygon. Use your own vertex class instead of this
  89028. // one to provide additional features like texture coordinates and vertex
  89029. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  89030. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  89031. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  89032. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  89033. // is not used anywhere else.
  89034. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  89035. var Vertex = /** @class */ (function () {
  89036. function Vertex(pos, normal, uv) {
  89037. this.pos = pos;
  89038. this.normal = normal;
  89039. this.uv = uv;
  89040. }
  89041. Vertex.prototype.clone = function () {
  89042. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  89043. };
  89044. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  89045. // orientation of a polygon is flipped.
  89046. Vertex.prototype.flip = function () {
  89047. this.normal = this.normal.scale(-1);
  89048. };
  89049. // Create a new vertex between this vertex and `other` by linearly
  89050. // interpolating all properties using a parameter of `t`. Subclasses should
  89051. // override this to interpolate additional properties.
  89052. Vertex.prototype.interpolate = function (other, t) {
  89053. 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));
  89054. };
  89055. return Vertex;
  89056. }());
  89057. // # class Plane
  89058. // Represents a plane in 3D space.
  89059. var Plane = /** @class */ (function () {
  89060. function Plane(normal, w) {
  89061. this.normal = normal;
  89062. this.w = w;
  89063. }
  89064. Plane.FromPoints = function (a, b, c) {
  89065. var v0 = c.subtract(a);
  89066. var v1 = b.subtract(a);
  89067. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  89068. return null;
  89069. }
  89070. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  89071. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  89072. };
  89073. Plane.prototype.clone = function () {
  89074. return new Plane(this.normal.clone(), this.w);
  89075. };
  89076. Plane.prototype.flip = function () {
  89077. this.normal.scaleInPlace(-1);
  89078. this.w = -this.w;
  89079. };
  89080. // Split `polygon` by this plane if needed, then put the polygon or polygon
  89081. // fragments in the appropriate lists. Coplanar polygons go into either
  89082. // `coplanarFront` or `coplanarBack` depending on their orientation with
  89083. // respect to this plane. Polygons in front or in back of this plane go into
  89084. // either `front` or `back`.
  89085. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  89086. var COPLANAR = 0;
  89087. var FRONT = 1;
  89088. var BACK = 2;
  89089. var SPANNING = 3;
  89090. // Classify each point as well as the entire polygon into one of the above
  89091. // four classes.
  89092. var polygonType = 0;
  89093. var types = [];
  89094. var i;
  89095. var t;
  89096. for (i = 0; i < polygon.vertices.length; i++) {
  89097. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  89098. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  89099. polygonType |= type;
  89100. types.push(type);
  89101. }
  89102. // Put the polygon in the correct list, splitting it when necessary.
  89103. switch (polygonType) {
  89104. case COPLANAR:
  89105. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  89106. break;
  89107. case FRONT:
  89108. front.push(polygon);
  89109. break;
  89110. case BACK:
  89111. back.push(polygon);
  89112. break;
  89113. case SPANNING:
  89114. var f = [], b = [];
  89115. for (i = 0; i < polygon.vertices.length; i++) {
  89116. var j = (i + 1) % polygon.vertices.length;
  89117. var ti = types[i], tj = types[j];
  89118. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  89119. if (ti !== BACK)
  89120. f.push(vi);
  89121. if (ti !== FRONT)
  89122. b.push(ti !== BACK ? vi.clone() : vi);
  89123. if ((ti | tj) === SPANNING) {
  89124. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  89125. var v = vi.interpolate(vj, t);
  89126. f.push(v);
  89127. b.push(v.clone());
  89128. }
  89129. }
  89130. var poly;
  89131. if (f.length >= 3) {
  89132. poly = new Polygon(f, polygon.shared);
  89133. if (poly.plane)
  89134. front.push(poly);
  89135. }
  89136. if (b.length >= 3) {
  89137. poly = new Polygon(b, polygon.shared);
  89138. if (poly.plane)
  89139. back.push(poly);
  89140. }
  89141. break;
  89142. }
  89143. };
  89144. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  89145. // point is on the plane.
  89146. Plane.EPSILON = 1e-5;
  89147. return Plane;
  89148. }());
  89149. // # class Polygon
  89150. // Represents a convex polygon. The vertices used to initialize a polygon must
  89151. // be coplanar and form a convex loop.
  89152. //
  89153. // Each convex polygon has a `shared` property, which is shared between all
  89154. // polygons that are clones of each other or were split from the same polygon.
  89155. // This can be used to define per-polygon properties (such as surface color).
  89156. var Polygon = /** @class */ (function () {
  89157. function Polygon(vertices, shared) {
  89158. this.vertices = vertices;
  89159. this.shared = shared;
  89160. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  89161. }
  89162. Polygon.prototype.clone = function () {
  89163. var vertices = this.vertices.map(function (v) { return v.clone(); });
  89164. return new Polygon(vertices, this.shared);
  89165. };
  89166. Polygon.prototype.flip = function () {
  89167. this.vertices.reverse().map(function (v) { v.flip(); });
  89168. this.plane.flip();
  89169. };
  89170. return Polygon;
  89171. }());
  89172. // # class Node
  89173. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  89174. // by picking a polygon to split along. That polygon (and all other coplanar
  89175. // polygons) are added directly to that node and the other polygons are added to
  89176. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  89177. // no distinction between internal and leaf nodes.
  89178. var Node = /** @class */ (function () {
  89179. function Node(polygons) {
  89180. this.plane = null;
  89181. this.front = null;
  89182. this.back = null;
  89183. this.polygons = new Array();
  89184. if (polygons) {
  89185. this.build(polygons);
  89186. }
  89187. }
  89188. Node.prototype.clone = function () {
  89189. var node = new Node();
  89190. node.plane = this.plane && this.plane.clone();
  89191. node.front = this.front && this.front.clone();
  89192. node.back = this.back && this.back.clone();
  89193. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  89194. return node;
  89195. };
  89196. // Convert solid space to empty space and empty space to solid space.
  89197. Node.prototype.invert = function () {
  89198. for (var i = 0; i < this.polygons.length; i++) {
  89199. this.polygons[i].flip();
  89200. }
  89201. if (this.plane) {
  89202. this.plane.flip();
  89203. }
  89204. if (this.front) {
  89205. this.front.invert();
  89206. }
  89207. if (this.back) {
  89208. this.back.invert();
  89209. }
  89210. var temp = this.front;
  89211. this.front = this.back;
  89212. this.back = temp;
  89213. };
  89214. // Recursively remove all polygons in `polygons` that are inside this BSP
  89215. // tree.
  89216. Node.prototype.clipPolygons = function (polygons) {
  89217. if (!this.plane)
  89218. return polygons.slice();
  89219. var front = new Array(), back = new Array();
  89220. for (var i = 0; i < polygons.length; i++) {
  89221. this.plane.splitPolygon(polygons[i], front, back, front, back);
  89222. }
  89223. if (this.front) {
  89224. front = this.front.clipPolygons(front);
  89225. }
  89226. if (this.back) {
  89227. back = this.back.clipPolygons(back);
  89228. }
  89229. else {
  89230. back = [];
  89231. }
  89232. return front.concat(back);
  89233. };
  89234. // Remove all polygons in this BSP tree that are inside the other BSP tree
  89235. // `bsp`.
  89236. Node.prototype.clipTo = function (bsp) {
  89237. this.polygons = bsp.clipPolygons(this.polygons);
  89238. if (this.front)
  89239. this.front.clipTo(bsp);
  89240. if (this.back)
  89241. this.back.clipTo(bsp);
  89242. };
  89243. // Return a list of all polygons in this BSP tree.
  89244. Node.prototype.allPolygons = function () {
  89245. var polygons = this.polygons.slice();
  89246. if (this.front)
  89247. polygons = polygons.concat(this.front.allPolygons());
  89248. if (this.back)
  89249. polygons = polygons.concat(this.back.allPolygons());
  89250. return polygons;
  89251. };
  89252. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  89253. // new polygons are filtered down to the bottom of the tree and become new
  89254. // nodes there. Each set of polygons is partitioned using the first polygon
  89255. // (no heuristic is used to pick a good split).
  89256. Node.prototype.build = function (polygons) {
  89257. if (!polygons.length)
  89258. return;
  89259. if (!this.plane)
  89260. this.plane = polygons[0].plane.clone();
  89261. var front = new Array(), back = new Array();
  89262. for (var i = 0; i < polygons.length; i++) {
  89263. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  89264. }
  89265. if (front.length) {
  89266. if (!this.front)
  89267. this.front = new Node();
  89268. this.front.build(front);
  89269. }
  89270. if (back.length) {
  89271. if (!this.back)
  89272. this.back = new Node();
  89273. this.back.build(back);
  89274. }
  89275. };
  89276. return Node;
  89277. }());
  89278. var CSG = /** @class */ (function () {
  89279. function CSG() {
  89280. this.polygons = new Array();
  89281. }
  89282. // Convert BABYLON.Mesh to BABYLON.CSG
  89283. CSG.FromMesh = function (mesh) {
  89284. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  89285. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  89286. if (mesh instanceof BABYLON.Mesh) {
  89287. mesh.computeWorldMatrix(true);
  89288. matrix = mesh.getWorldMatrix();
  89289. meshPosition = mesh.position.clone();
  89290. meshRotation = mesh.rotation.clone();
  89291. if (mesh.rotationQuaternion) {
  89292. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  89293. }
  89294. meshScaling = mesh.scaling.clone();
  89295. }
  89296. else {
  89297. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  89298. }
  89299. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89300. var subMeshes = mesh.subMeshes;
  89301. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  89302. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  89303. vertices = [];
  89304. for (var j = 0; j < 3; j++) {
  89305. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  89306. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  89307. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  89308. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  89309. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  89310. vertex = new Vertex(position, normal, uv);
  89311. vertices.push(vertex);
  89312. }
  89313. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  89314. // To handle the case of degenerated triangle
  89315. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  89316. if (polygon.plane)
  89317. polygons.push(polygon);
  89318. }
  89319. }
  89320. var csg = CSG.FromPolygons(polygons);
  89321. csg.matrix = matrix;
  89322. csg.position = meshPosition;
  89323. csg.rotation = meshRotation;
  89324. csg.scaling = meshScaling;
  89325. csg.rotationQuaternion = meshRotationQuaternion;
  89326. currentCSGMeshId++;
  89327. return csg;
  89328. };
  89329. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  89330. CSG.FromPolygons = function (polygons) {
  89331. var csg = new CSG();
  89332. csg.polygons = polygons;
  89333. return csg;
  89334. };
  89335. CSG.prototype.clone = function () {
  89336. var csg = new CSG();
  89337. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  89338. csg.copyTransformAttributes(this);
  89339. return csg;
  89340. };
  89341. CSG.prototype.union = function (csg) {
  89342. var a = new Node(this.clone().polygons);
  89343. var b = new Node(csg.clone().polygons);
  89344. a.clipTo(b);
  89345. b.clipTo(a);
  89346. b.invert();
  89347. b.clipTo(a);
  89348. b.invert();
  89349. a.build(b.allPolygons());
  89350. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89351. };
  89352. CSG.prototype.unionInPlace = function (csg) {
  89353. var a = new Node(this.polygons);
  89354. var b = new Node(csg.polygons);
  89355. a.clipTo(b);
  89356. b.clipTo(a);
  89357. b.invert();
  89358. b.clipTo(a);
  89359. b.invert();
  89360. a.build(b.allPolygons());
  89361. this.polygons = a.allPolygons();
  89362. };
  89363. CSG.prototype.subtract = function (csg) {
  89364. var a = new Node(this.clone().polygons);
  89365. var b = new Node(csg.clone().polygons);
  89366. a.invert();
  89367. a.clipTo(b);
  89368. b.clipTo(a);
  89369. b.invert();
  89370. b.clipTo(a);
  89371. b.invert();
  89372. a.build(b.allPolygons());
  89373. a.invert();
  89374. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89375. };
  89376. CSG.prototype.subtractInPlace = function (csg) {
  89377. var a = new Node(this.polygons);
  89378. var b = new Node(csg.polygons);
  89379. a.invert();
  89380. a.clipTo(b);
  89381. b.clipTo(a);
  89382. b.invert();
  89383. b.clipTo(a);
  89384. b.invert();
  89385. a.build(b.allPolygons());
  89386. a.invert();
  89387. this.polygons = a.allPolygons();
  89388. };
  89389. CSG.prototype.intersect = function (csg) {
  89390. var a = new Node(this.clone().polygons);
  89391. var b = new Node(csg.clone().polygons);
  89392. a.invert();
  89393. b.clipTo(a);
  89394. b.invert();
  89395. a.clipTo(b);
  89396. b.clipTo(a);
  89397. a.build(b.allPolygons());
  89398. a.invert();
  89399. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  89400. };
  89401. CSG.prototype.intersectInPlace = function (csg) {
  89402. var a = new Node(this.polygons);
  89403. var b = new Node(csg.polygons);
  89404. a.invert();
  89405. b.clipTo(a);
  89406. b.invert();
  89407. a.clipTo(b);
  89408. b.clipTo(a);
  89409. a.build(b.allPolygons());
  89410. a.invert();
  89411. this.polygons = a.allPolygons();
  89412. };
  89413. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  89414. // not modified.
  89415. CSG.prototype.inverse = function () {
  89416. var csg = this.clone();
  89417. csg.inverseInPlace();
  89418. return csg;
  89419. };
  89420. CSG.prototype.inverseInPlace = function () {
  89421. this.polygons.map(function (p) { p.flip(); });
  89422. };
  89423. // This is used to keep meshes transformations so they can be restored
  89424. // when we build back a Babylon Mesh
  89425. // NB : All CSG operations are performed in world coordinates
  89426. CSG.prototype.copyTransformAttributes = function (csg) {
  89427. this.matrix = csg.matrix;
  89428. this.position = csg.position;
  89429. this.rotation = csg.rotation;
  89430. this.scaling = csg.scaling;
  89431. this.rotationQuaternion = csg.rotationQuaternion;
  89432. return this;
  89433. };
  89434. // Build Raw mesh from CSG
  89435. // Coordinates here are in world space
  89436. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  89437. var matrix = this.matrix.clone();
  89438. matrix.invert();
  89439. 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;
  89440. if (keepSubMeshes) {
  89441. // Sort Polygons, since subMeshes are indices range
  89442. polygons.sort(function (a, b) {
  89443. if (a.shared.meshId === b.shared.meshId) {
  89444. return a.shared.subMeshId - b.shared.subMeshId;
  89445. }
  89446. else {
  89447. return a.shared.meshId - b.shared.meshId;
  89448. }
  89449. });
  89450. }
  89451. for (var i = 0, il = polygons.length; i < il; i++) {
  89452. polygon = polygons[i];
  89453. // Building SubMeshes
  89454. if (!subMesh_dict[polygon.shared.meshId]) {
  89455. subMesh_dict[polygon.shared.meshId] = {};
  89456. }
  89457. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  89458. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  89459. indexStart: +Infinity,
  89460. indexEnd: -Infinity,
  89461. materialIndex: polygon.shared.materialIndex
  89462. };
  89463. }
  89464. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  89465. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  89466. polygonIndices[0] = 0;
  89467. polygonIndices[1] = j - 1;
  89468. polygonIndices[2] = j;
  89469. for (var k = 0; k < 3; k++) {
  89470. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  89471. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  89472. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  89473. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  89474. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  89475. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  89476. // Check if 2 points can be merged
  89477. if (!(typeof vertex_idx !== 'undefined' &&
  89478. normals[vertex_idx * 3] === localNormal.x &&
  89479. normals[vertex_idx * 3 + 1] === localNormal.y &&
  89480. normals[vertex_idx * 3 + 2] === localNormal.z &&
  89481. uvs[vertex_idx * 2] === uv.x &&
  89482. uvs[vertex_idx * 2 + 1] === uv.y)) {
  89483. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  89484. uvs.push(uv.x, uv.y);
  89485. normals.push(normal.x, normal.y, normal.z);
  89486. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  89487. }
  89488. indices.push(vertex_idx);
  89489. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  89490. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  89491. currentIndex++;
  89492. }
  89493. }
  89494. }
  89495. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  89496. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  89497. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  89498. mesh.setIndices(indices, null);
  89499. if (keepSubMeshes) {
  89500. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  89501. var materialIndexOffset = 0, materialMaxIndex;
  89502. mesh.subMeshes = new Array();
  89503. for (var m in subMesh_dict) {
  89504. materialMaxIndex = -1;
  89505. for (var sm in subMesh_dict[m]) {
  89506. subMesh_obj = subMesh_dict[m][sm];
  89507. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  89508. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  89509. }
  89510. materialIndexOffset += ++materialMaxIndex;
  89511. }
  89512. }
  89513. return mesh;
  89514. };
  89515. // Build Mesh from CSG taking material and transforms into account
  89516. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  89517. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  89518. mesh.material = material;
  89519. mesh.position.copyFrom(this.position);
  89520. mesh.rotation.copyFrom(this.rotation);
  89521. if (this.rotationQuaternion) {
  89522. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  89523. }
  89524. mesh.scaling.copyFrom(this.scaling);
  89525. mesh.computeWorldMatrix(true);
  89526. return mesh;
  89527. };
  89528. return CSG;
  89529. }());
  89530. BABYLON.CSG = CSG;
  89531. })(BABYLON || (BABYLON = {}));
  89532. //# sourceMappingURL=babylon.csg.js.map
  89533. var BABYLON;
  89534. (function (BABYLON) {
  89535. var LensFlare = /** @class */ (function () {
  89536. function LensFlare(size, position, color, imgUrl, system) {
  89537. this.size = size;
  89538. this.position = position;
  89539. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  89540. this.color = color || new BABYLON.Color3(1, 1, 1);
  89541. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  89542. this._system = system;
  89543. system.lensFlares.push(this);
  89544. }
  89545. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  89546. return new LensFlare(size, position, color, imgUrl, system);
  89547. };
  89548. LensFlare.prototype.dispose = function () {
  89549. if (this.texture) {
  89550. this.texture.dispose();
  89551. }
  89552. // Remove from scene
  89553. var index = this._system.lensFlares.indexOf(this);
  89554. this._system.lensFlares.splice(index, 1);
  89555. };
  89556. ;
  89557. return LensFlare;
  89558. }());
  89559. BABYLON.LensFlare = LensFlare;
  89560. })(BABYLON || (BABYLON = {}));
  89561. //# sourceMappingURL=babylon.lensFlare.js.map
  89562. var BABYLON;
  89563. (function (BABYLON) {
  89564. // Adds the parser to the scene parsers.
  89565. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  89566. // Lens flares
  89567. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  89568. if (!container.lensFlareSystems) {
  89569. container.lensFlareSystems = new Array();
  89570. }
  89571. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  89572. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  89573. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  89574. container.lensFlareSystems.push(lf);
  89575. }
  89576. }
  89577. });
  89578. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  89579. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89580. if (this.lensFlareSystems[index].name === name) {
  89581. return this.lensFlareSystems[index];
  89582. }
  89583. }
  89584. return null;
  89585. };
  89586. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  89587. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  89588. if (this.lensFlareSystems[index].id === id) {
  89589. return this.lensFlareSystems[index];
  89590. }
  89591. }
  89592. return null;
  89593. };
  89594. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  89595. var index = this.lensFlareSystems.indexOf(toRemove);
  89596. if (index !== -1) {
  89597. this.lensFlareSystems.splice(index, 1);
  89598. }
  89599. return index;
  89600. };
  89601. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  89602. this.lensFlareSystems.push(newLensFlareSystem);
  89603. };
  89604. /**
  89605. * Defines the lens flare scene component responsible to manage any lens flares
  89606. * in a given scene.
  89607. */
  89608. var LensFlareSystemSceneComponent = /** @class */ (function () {
  89609. /**
  89610. * Creates a new instance of the component for the given scene
  89611. * @param scene Defines the scene to register the component in
  89612. */
  89613. function LensFlareSystemSceneComponent(scene) {
  89614. /**
  89615. * The component name helpfull to identify the component in the list of scene components.
  89616. */
  89617. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  89618. this.scene = scene;
  89619. scene.lensFlareSystems = new Array();
  89620. }
  89621. /**
  89622. * Registers the component in a given scene
  89623. */
  89624. LensFlareSystemSceneComponent.prototype.register = function () {
  89625. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  89626. };
  89627. /**
  89628. * Rebuilds the elements related to this component in case of
  89629. * context lost for instance.
  89630. */
  89631. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  89632. // Nothing to do for lens flare
  89633. };
  89634. /**
  89635. * Adds all the element from the container to the scene
  89636. * @param container the container holding the elements
  89637. */
  89638. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  89639. var _this = this;
  89640. if (!container.lensFlareSystems) {
  89641. return;
  89642. }
  89643. container.lensFlareSystems.forEach(function (o) {
  89644. _this.scene.addLensFlareSystem(o);
  89645. });
  89646. };
  89647. /**
  89648. * Removes all the elements in the container from the scene
  89649. * @param container contains the elements to remove
  89650. */
  89651. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  89652. var _this = this;
  89653. if (!container.lensFlareSystems) {
  89654. return;
  89655. }
  89656. container.lensFlareSystems.forEach(function (o) {
  89657. _this.scene.removeLensFlareSystem(o);
  89658. });
  89659. };
  89660. /**
  89661. * Serializes the component data to the specified json object
  89662. * @param serializationObject The object to serialize to
  89663. */
  89664. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  89665. // Lens flares
  89666. serializationObject.lensFlareSystems = [];
  89667. var lensFlareSystems = this.scene.lensFlareSystems;
  89668. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  89669. var lensFlareSystem = lensFlareSystems_1[_i];
  89670. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  89671. }
  89672. };
  89673. /**
  89674. * Disposes the component and the associated ressources.
  89675. */
  89676. LensFlareSystemSceneComponent.prototype.dispose = function () {
  89677. var lensFlareSystems = this.scene.lensFlareSystems;
  89678. while (lensFlareSystems.length) {
  89679. lensFlareSystems[0].dispose();
  89680. }
  89681. };
  89682. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  89683. // Lens flares
  89684. if (this.scene.lensFlaresEnabled) {
  89685. var lensFlareSystems = this.scene.lensFlareSystems;
  89686. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  89687. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  89688. var lensFlareSystem = lensFlareSystems_2[_i];
  89689. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  89690. lensFlareSystem.render();
  89691. }
  89692. }
  89693. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  89694. }
  89695. };
  89696. return LensFlareSystemSceneComponent;
  89697. }());
  89698. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  89699. })(BABYLON || (BABYLON = {}));
  89700. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  89701. var BABYLON;
  89702. (function (BABYLON) {
  89703. var LensFlareSystem = /** @class */ (function () {
  89704. function LensFlareSystem(name, emitter, scene) {
  89705. this.name = name;
  89706. this.lensFlares = new Array();
  89707. this.borderLimit = 300;
  89708. this.viewportBorder = 0;
  89709. this.layerMask = 0x0FFFFFFF;
  89710. this._vertexBuffers = {};
  89711. this._isEnabled = true;
  89712. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89713. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  89714. if (!component) {
  89715. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  89716. scene._addComponent(component);
  89717. }
  89718. this._emitter = emitter;
  89719. this.id = name;
  89720. scene.lensFlareSystems.push(this);
  89721. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  89722. var engine = scene.getEngine();
  89723. // VBO
  89724. var vertices = [];
  89725. vertices.push(1, 1);
  89726. vertices.push(-1, 1);
  89727. vertices.push(-1, -1);
  89728. vertices.push(1, -1);
  89729. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89730. // Indices
  89731. var indices = [];
  89732. indices.push(0);
  89733. indices.push(1);
  89734. indices.push(2);
  89735. indices.push(0);
  89736. indices.push(2);
  89737. indices.push(3);
  89738. this._indexBuffer = engine.createIndexBuffer(indices);
  89739. // Effects
  89740. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  89741. }
  89742. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  89743. get: function () {
  89744. return this._isEnabled;
  89745. },
  89746. set: function (value) {
  89747. this._isEnabled = value;
  89748. },
  89749. enumerable: true,
  89750. configurable: true
  89751. });
  89752. LensFlareSystem.prototype.getScene = function () {
  89753. return this._scene;
  89754. };
  89755. LensFlareSystem.prototype.getEmitter = function () {
  89756. return this._emitter;
  89757. };
  89758. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  89759. this._emitter = newEmitter;
  89760. };
  89761. LensFlareSystem.prototype.getEmitterPosition = function () {
  89762. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  89763. };
  89764. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  89765. var position = this.getEmitterPosition();
  89766. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  89767. this._positionX = position.x;
  89768. this._positionY = position.y;
  89769. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  89770. if (this.viewportBorder > 0) {
  89771. globalViewport.x -= this.viewportBorder;
  89772. globalViewport.y -= this.viewportBorder;
  89773. globalViewport.width += this.viewportBorder * 2;
  89774. globalViewport.height += this.viewportBorder * 2;
  89775. position.x += this.viewportBorder;
  89776. position.y += this.viewportBorder;
  89777. this._positionX += this.viewportBorder;
  89778. this._positionY += this.viewportBorder;
  89779. }
  89780. if (position.z > 0) {
  89781. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  89782. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  89783. return true;
  89784. }
  89785. return true;
  89786. }
  89787. return false;
  89788. };
  89789. /** @hidden */
  89790. LensFlareSystem.prototype._isVisible = function () {
  89791. if (!this._isEnabled || !this._scene.activeCamera) {
  89792. return false;
  89793. }
  89794. var emitterPosition = this.getEmitterPosition();
  89795. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  89796. var distance = direction.length();
  89797. direction.normalize();
  89798. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  89799. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  89800. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  89801. };
  89802. LensFlareSystem.prototype.render = function () {
  89803. if (!this._effect.isReady() || !this._scene.activeCamera)
  89804. return false;
  89805. var engine = this._scene.getEngine();
  89806. var viewport = this._scene.activeCamera.viewport;
  89807. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  89808. // Position
  89809. if (!this.computeEffectivePosition(globalViewport)) {
  89810. return false;
  89811. }
  89812. // Visibility
  89813. if (!this._isVisible()) {
  89814. return false;
  89815. }
  89816. // Intensity
  89817. var awayX;
  89818. var awayY;
  89819. if (this._positionX < this.borderLimit + globalViewport.x) {
  89820. awayX = this.borderLimit + globalViewport.x - this._positionX;
  89821. }
  89822. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  89823. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  89824. }
  89825. else {
  89826. awayX = 0;
  89827. }
  89828. if (this._positionY < this.borderLimit + globalViewport.y) {
  89829. awayY = this.borderLimit + globalViewport.y - this._positionY;
  89830. }
  89831. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  89832. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  89833. }
  89834. else {
  89835. awayY = 0;
  89836. }
  89837. var away = (awayX > awayY) ? awayX : awayY;
  89838. away -= this.viewportBorder;
  89839. if (away > this.borderLimit) {
  89840. away = this.borderLimit;
  89841. }
  89842. var intensity = 1.0 - (away / this.borderLimit);
  89843. if (intensity < 0) {
  89844. return false;
  89845. }
  89846. if (intensity > 1.0) {
  89847. intensity = 1.0;
  89848. }
  89849. if (this.viewportBorder > 0) {
  89850. globalViewport.x += this.viewportBorder;
  89851. globalViewport.y += this.viewportBorder;
  89852. globalViewport.width -= this.viewportBorder * 2;
  89853. globalViewport.height -= this.viewportBorder * 2;
  89854. this._positionX -= this.viewportBorder;
  89855. this._positionY -= this.viewportBorder;
  89856. }
  89857. // Position
  89858. var centerX = globalViewport.x + globalViewport.width / 2;
  89859. var centerY = globalViewport.y + globalViewport.height / 2;
  89860. var distX = centerX - this._positionX;
  89861. var distY = centerY - this._positionY;
  89862. // Effects
  89863. engine.enableEffect(this._effect);
  89864. engine.setState(false);
  89865. engine.setDepthBuffer(false);
  89866. // VBOs
  89867. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  89868. // Flares
  89869. for (var index = 0; index < this.lensFlares.length; index++) {
  89870. var flare = this.lensFlares[index];
  89871. engine.setAlphaMode(flare.alphaMode);
  89872. var x = centerX - (distX * flare.position);
  89873. var y = centerY - (distY * flare.position);
  89874. var cw = flare.size;
  89875. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  89876. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  89877. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  89878. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  89879. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  89880. // Texture
  89881. this._effect.setTexture("textureSampler", flare.texture);
  89882. // Color
  89883. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  89884. // Draw order
  89885. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89886. }
  89887. engine.setDepthBuffer(true);
  89888. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89889. return true;
  89890. };
  89891. LensFlareSystem.prototype.dispose = function () {
  89892. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89893. if (vertexBuffer) {
  89894. vertexBuffer.dispose();
  89895. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89896. }
  89897. if (this._indexBuffer) {
  89898. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89899. this._indexBuffer = null;
  89900. }
  89901. while (this.lensFlares.length) {
  89902. this.lensFlares[0].dispose();
  89903. }
  89904. // Remove from scene
  89905. var index = this._scene.lensFlareSystems.indexOf(this);
  89906. this._scene.lensFlareSystems.splice(index, 1);
  89907. };
  89908. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  89909. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  89910. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  89911. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  89912. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  89913. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  89914. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  89915. var parsedFlare = parsedLensFlareSystem.flares[index];
  89916. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  89917. }
  89918. return lensFlareSystem;
  89919. };
  89920. LensFlareSystem.prototype.serialize = function () {
  89921. var serializationObject = {};
  89922. serializationObject.id = this.id;
  89923. serializationObject.name = this.name;
  89924. serializationObject.emitterId = this.getEmitter().id;
  89925. serializationObject.borderLimit = this.borderLimit;
  89926. serializationObject.flares = [];
  89927. for (var index = 0; index < this.lensFlares.length; index++) {
  89928. var flare = this.lensFlares[index];
  89929. serializationObject.flares.push({
  89930. size: flare.size,
  89931. position: flare.position,
  89932. color: flare.color.asArray(),
  89933. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  89934. });
  89935. }
  89936. return serializationObject;
  89937. };
  89938. return LensFlareSystem;
  89939. }());
  89940. BABYLON.LensFlareSystem = LensFlareSystem;
  89941. })(BABYLON || (BABYLON = {}));
  89942. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  89943. var BABYLON;
  89944. (function (BABYLON) {
  89945. /**
  89946. * This is a holder class for the physics joint created by the physics plugin.
  89947. * It holds a set of functions to control the underlying joint.
  89948. */
  89949. var PhysicsJoint = /** @class */ (function () {
  89950. function PhysicsJoint(type, jointData) {
  89951. this.type = type;
  89952. this.jointData = jointData;
  89953. jointData.nativeParams = jointData.nativeParams || {};
  89954. }
  89955. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  89956. get: function () {
  89957. return this._physicsJoint;
  89958. },
  89959. set: function (newJoint) {
  89960. if (this._physicsJoint) {
  89961. //remove from the wolrd
  89962. }
  89963. this._physicsJoint = newJoint;
  89964. },
  89965. enumerable: true,
  89966. configurable: true
  89967. });
  89968. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  89969. set: function (physicsPlugin) {
  89970. this._physicsPlugin = physicsPlugin;
  89971. },
  89972. enumerable: true,
  89973. configurable: true
  89974. });
  89975. /**
  89976. * Execute a function that is physics-plugin specific.
  89977. * @param {Function} func the function that will be executed.
  89978. * It accepts two parameters: the physics world and the physics joint.
  89979. */
  89980. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  89981. func(this._physicsPlugin.world, this._physicsJoint);
  89982. };
  89983. //TODO check if the native joints are the same
  89984. //Joint Types
  89985. PhysicsJoint.DistanceJoint = 0;
  89986. PhysicsJoint.HingeJoint = 1;
  89987. PhysicsJoint.BallAndSocketJoint = 2;
  89988. PhysicsJoint.WheelJoint = 3;
  89989. PhysicsJoint.SliderJoint = 4;
  89990. //OIMO
  89991. PhysicsJoint.PrismaticJoint = 5;
  89992. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  89993. PhysicsJoint.UniversalJoint = 6;
  89994. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  89995. //Cannon
  89996. //Similar to a Ball-Joint. Different in params
  89997. PhysicsJoint.PointToPointJoint = 8;
  89998. //Cannon only at the moment
  89999. PhysicsJoint.SpringJoint = 9;
  90000. PhysicsJoint.LockJoint = 10;
  90001. return PhysicsJoint;
  90002. }());
  90003. BABYLON.PhysicsJoint = PhysicsJoint;
  90004. /**
  90005. * A class representing a physics distance joint.
  90006. */
  90007. var DistanceJoint = /** @class */ (function (_super) {
  90008. __extends(DistanceJoint, _super);
  90009. function DistanceJoint(jointData) {
  90010. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  90011. }
  90012. /**
  90013. * Update the predefined distance.
  90014. */
  90015. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  90016. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  90017. };
  90018. return DistanceJoint;
  90019. }(PhysicsJoint));
  90020. BABYLON.DistanceJoint = DistanceJoint;
  90021. var MotorEnabledJoint = /** @class */ (function (_super) {
  90022. __extends(MotorEnabledJoint, _super);
  90023. function MotorEnabledJoint(type, jointData) {
  90024. return _super.call(this, type, jointData) || this;
  90025. }
  90026. /**
  90027. * Set the motor values.
  90028. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90029. * @param {number} force the force to apply
  90030. * @param {number} maxForce max force for this motor.
  90031. */
  90032. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  90033. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90034. };
  90035. /**
  90036. * Set the motor's limits.
  90037. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90038. */
  90039. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90040. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90041. };
  90042. return MotorEnabledJoint;
  90043. }(PhysicsJoint));
  90044. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  90045. /**
  90046. * This class represents a single hinge physics joint
  90047. */
  90048. var HingeJoint = /** @class */ (function (_super) {
  90049. __extends(HingeJoint, _super);
  90050. function HingeJoint(jointData) {
  90051. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  90052. }
  90053. /**
  90054. * Set the motor values.
  90055. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90056. * @param {number} force the force to apply
  90057. * @param {number} maxForce max force for this motor.
  90058. */
  90059. HingeJoint.prototype.setMotor = function (force, maxForce) {
  90060. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  90061. };
  90062. /**
  90063. * Set the motor's limits.
  90064. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90065. */
  90066. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  90067. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  90068. };
  90069. return HingeJoint;
  90070. }(MotorEnabledJoint));
  90071. BABYLON.HingeJoint = HingeJoint;
  90072. /**
  90073. * This class represents a dual hinge physics joint (same as wheel joint)
  90074. */
  90075. var Hinge2Joint = /** @class */ (function (_super) {
  90076. __extends(Hinge2Joint, _super);
  90077. function Hinge2Joint(jointData) {
  90078. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  90079. }
  90080. /**
  90081. * Set the motor values.
  90082. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90083. * @param {number} force the force to apply
  90084. * @param {number} maxForce max force for this motor.
  90085. * @param {motorIndex} the motor's index, 0 or 1.
  90086. */
  90087. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  90088. if (motorIndex === void 0) { motorIndex = 0; }
  90089. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  90090. };
  90091. /**
  90092. * Set the motor limits.
  90093. * Attention, this function is plugin specific. Engines won't react 100% the same.
  90094. * @param {number} upperLimit the upper limit
  90095. * @param {number} lowerLimit lower limit
  90096. * @param {motorIndex} the motor's index, 0 or 1.
  90097. */
  90098. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  90099. if (motorIndex === void 0) { motorIndex = 0; }
  90100. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  90101. };
  90102. return Hinge2Joint;
  90103. }(MotorEnabledJoint));
  90104. BABYLON.Hinge2Joint = Hinge2Joint;
  90105. })(BABYLON || (BABYLON = {}));
  90106. //# sourceMappingURL=babylon.physicsJoint.js.map
  90107. var BABYLON;
  90108. (function (BABYLON) {
  90109. var PhysicsImpostor = /** @class */ (function () {
  90110. function PhysicsImpostor(object, type, _options, _scene) {
  90111. if (_options === void 0) { _options = { mass: 0 }; }
  90112. var _this = this;
  90113. this.object = object;
  90114. this.type = type;
  90115. this._options = _options;
  90116. this._scene = _scene;
  90117. this._bodyUpdateRequired = false;
  90118. this._onBeforePhysicsStepCallbacks = new Array();
  90119. this._onAfterPhysicsStepCallbacks = new Array();
  90120. this._onPhysicsCollideCallbacks = [];
  90121. this._deltaPosition = BABYLON.Vector3.Zero();
  90122. this._isDisposed = false;
  90123. //temp variables for parent rotation calculations
  90124. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  90125. this._tmpQuat = new BABYLON.Quaternion();
  90126. this._tmpQuat2 = new BABYLON.Quaternion();
  90127. /**
  90128. * this function is executed by the physics engine.
  90129. */
  90130. this.beforeStep = function () {
  90131. if (!_this._physicsEngine) {
  90132. return;
  90133. }
  90134. _this.object.translate(_this._deltaPosition, -1);
  90135. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  90136. _this.object.computeWorldMatrix(false);
  90137. if (_this.object.parent && _this.object.rotationQuaternion) {
  90138. _this.getParentsRotation();
  90139. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  90140. }
  90141. else {
  90142. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  90143. }
  90144. if (!_this._options.disableBidirectionalTransformation) {
  90145. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  90146. }
  90147. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  90148. func(_this);
  90149. });
  90150. };
  90151. /**
  90152. * this function is executed by the physics engine.
  90153. */
  90154. this.afterStep = function () {
  90155. if (!_this._physicsEngine) {
  90156. return;
  90157. }
  90158. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  90159. func(_this);
  90160. });
  90161. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  90162. // object has now its world rotation. needs to be converted to local.
  90163. if (_this.object.parent && _this.object.rotationQuaternion) {
  90164. _this.getParentsRotation();
  90165. _this._tmpQuat.conjugateInPlace();
  90166. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  90167. }
  90168. // take the position set and make it the absolute position of this object.
  90169. _this.object.setAbsolutePosition(_this.object.position);
  90170. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  90171. _this.object.translate(_this._deltaPosition, 1);
  90172. };
  90173. /**
  90174. * Legacy collision detection event support
  90175. */
  90176. this.onCollideEvent = null;
  90177. //event and body object due to cannon's event-based architecture.
  90178. this.onCollide = function (e) {
  90179. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  90180. return;
  90181. }
  90182. if (!_this._physicsEngine) {
  90183. return;
  90184. }
  90185. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  90186. if (otherImpostor) {
  90187. // Legacy collision detection event support
  90188. if (_this.onCollideEvent) {
  90189. _this.onCollideEvent(_this, otherImpostor);
  90190. }
  90191. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  90192. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  90193. }).forEach(function (obj) {
  90194. obj.callback(_this, otherImpostor);
  90195. });
  90196. }
  90197. };
  90198. //sanity check!
  90199. if (!this.object) {
  90200. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  90201. return;
  90202. }
  90203. //legacy support for old syntax.
  90204. if (!this._scene && object.getScene) {
  90205. this._scene = object.getScene();
  90206. }
  90207. if (!this._scene) {
  90208. return;
  90209. }
  90210. this._physicsEngine = this._scene.getPhysicsEngine();
  90211. if (!this._physicsEngine) {
  90212. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  90213. }
  90214. else {
  90215. //set the object's quaternion, if not set
  90216. if (!this.object.rotationQuaternion) {
  90217. if (this.object.rotation) {
  90218. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  90219. }
  90220. else {
  90221. this.object.rotationQuaternion = new BABYLON.Quaternion();
  90222. }
  90223. }
  90224. //default options params
  90225. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  90226. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  90227. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  90228. this._joints = [];
  90229. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  90230. if (!this.object.parent || this._options.ignoreParent) {
  90231. this._init();
  90232. }
  90233. else if (this.object.parent.physicsImpostor) {
  90234. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  90235. }
  90236. }
  90237. }
  90238. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  90239. get: function () {
  90240. return this._isDisposed;
  90241. },
  90242. enumerable: true,
  90243. configurable: true
  90244. });
  90245. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  90246. get: function () {
  90247. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  90248. },
  90249. set: function (value) {
  90250. this.setMass(value);
  90251. },
  90252. enumerable: true,
  90253. configurable: true
  90254. });
  90255. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  90256. get: function () {
  90257. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  90258. },
  90259. set: function (value) {
  90260. if (!this._physicsEngine) {
  90261. return;
  90262. }
  90263. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  90264. },
  90265. enumerable: true,
  90266. configurable: true
  90267. });
  90268. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  90269. get: function () {
  90270. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  90271. },
  90272. set: function (value) {
  90273. if (!this._physicsEngine) {
  90274. return;
  90275. }
  90276. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  90277. },
  90278. enumerable: true,
  90279. configurable: true
  90280. });
  90281. /**
  90282. * This function will completly initialize this impostor.
  90283. * It will create a new body - but only if this mesh has no parent.
  90284. * If it has, this impostor will not be used other than to define the impostor
  90285. * of the child mesh.
  90286. * @hidden
  90287. */
  90288. PhysicsImpostor.prototype._init = function () {
  90289. if (!this._physicsEngine) {
  90290. return;
  90291. }
  90292. this._physicsEngine.removeImpostor(this);
  90293. this.physicsBody = null;
  90294. this._parent = this._parent || this._getPhysicsParent();
  90295. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  90296. this._physicsEngine.addImpostor(this);
  90297. }
  90298. };
  90299. PhysicsImpostor.prototype._getPhysicsParent = function () {
  90300. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  90301. var parentMesh = this.object.parent;
  90302. return parentMesh.physicsImpostor;
  90303. }
  90304. return null;
  90305. };
  90306. /**
  90307. * Should a new body be generated.
  90308. */
  90309. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  90310. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  90311. };
  90312. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  90313. this.forceUpdate();
  90314. };
  90315. /**
  90316. * Force a regeneration of this or the parent's impostor's body.
  90317. * Use under cautious - This will remove all joints already implemented.
  90318. */
  90319. PhysicsImpostor.prototype.forceUpdate = function () {
  90320. this._init();
  90321. if (this.parent && !this._options.ignoreParent) {
  90322. this.parent.forceUpdate();
  90323. }
  90324. };
  90325. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  90326. /*public get mesh(): AbstractMesh {
  90327. return this._mesh;
  90328. }*/
  90329. /**
  90330. * Gets the body that holds this impostor. Either its own, or its parent.
  90331. */
  90332. get: function () {
  90333. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  90334. },
  90335. /**
  90336. * Set the physics body. Used mainly by the physics engine/plugin
  90337. */
  90338. set: function (physicsBody) {
  90339. if (this._physicsBody && this._physicsEngine) {
  90340. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  90341. }
  90342. this._physicsBody = physicsBody;
  90343. this.resetUpdateFlags();
  90344. },
  90345. enumerable: true,
  90346. configurable: true
  90347. });
  90348. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  90349. get: function () {
  90350. return !this._options.ignoreParent && this._parent ? this._parent : null;
  90351. },
  90352. set: function (value) {
  90353. this._parent = value;
  90354. },
  90355. enumerable: true,
  90356. configurable: true
  90357. });
  90358. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  90359. this._bodyUpdateRequired = false;
  90360. };
  90361. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  90362. if (this.object.getBoundingInfo) {
  90363. var q = this.object.rotationQuaternion;
  90364. //reset rotation
  90365. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  90366. //calculate the world matrix with no rotation
  90367. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90368. var boundingInfo = this.object.getBoundingInfo();
  90369. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  90370. //bring back the rotation
  90371. this.object.rotationQuaternion = q;
  90372. //calculate the world matrix with the new rotation
  90373. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  90374. return size;
  90375. }
  90376. else {
  90377. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  90378. }
  90379. };
  90380. PhysicsImpostor.prototype.getObjectCenter = function () {
  90381. if (this.object.getBoundingInfo) {
  90382. var boundingInfo = this.object.getBoundingInfo();
  90383. return boundingInfo.boundingBox.centerWorld;
  90384. }
  90385. else {
  90386. return this.object.position;
  90387. }
  90388. };
  90389. /**
  90390. * Get a specific parametes from the options parameter.
  90391. */
  90392. PhysicsImpostor.prototype.getParam = function (paramName) {
  90393. return this._options[paramName];
  90394. };
  90395. /**
  90396. * Sets a specific parameter in the options given to the physics plugin
  90397. */
  90398. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  90399. this._options[paramName] = value;
  90400. this._bodyUpdateRequired = true;
  90401. };
  90402. /**
  90403. * Specifically change the body's mass option. Won't recreate the physics body object
  90404. */
  90405. PhysicsImpostor.prototype.setMass = function (mass) {
  90406. if (this.getParam("mass") !== mass) {
  90407. this.setParam("mass", mass);
  90408. }
  90409. if (this._physicsEngine) {
  90410. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  90411. }
  90412. };
  90413. PhysicsImpostor.prototype.getLinearVelocity = function () {
  90414. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  90415. };
  90416. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  90417. if (this._physicsEngine) {
  90418. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  90419. }
  90420. };
  90421. PhysicsImpostor.prototype.getAngularVelocity = function () {
  90422. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  90423. };
  90424. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  90425. if (this._physicsEngine) {
  90426. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  90427. }
  90428. };
  90429. /**
  90430. * Execute a function with the physics plugin native code.
  90431. * Provide a function the will have two variables - the world object and the physics body object.
  90432. */
  90433. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  90434. if (this._physicsEngine) {
  90435. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  90436. }
  90437. };
  90438. /**
  90439. * Register a function that will be executed before the physics world is stepping forward.
  90440. */
  90441. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  90442. this._onBeforePhysicsStepCallbacks.push(func);
  90443. };
  90444. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  90445. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  90446. if (index > -1) {
  90447. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  90448. }
  90449. else {
  90450. BABYLON.Tools.Warn("Function to remove was not found");
  90451. }
  90452. };
  90453. /**
  90454. * Register a function that will be executed after the physics step
  90455. */
  90456. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  90457. this._onAfterPhysicsStepCallbacks.push(func);
  90458. };
  90459. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  90460. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  90461. if (index > -1) {
  90462. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  90463. }
  90464. else {
  90465. BABYLON.Tools.Warn("Function to remove was not found");
  90466. }
  90467. };
  90468. /**
  90469. * register a function that will be executed when this impostor collides against a different body.
  90470. */
  90471. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  90472. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90473. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  90474. };
  90475. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  90476. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  90477. var index = -1;
  90478. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  90479. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  90480. // chcek the arrays match
  90481. var sameList = cbDef.otherImpostors.every(function (impostor) {
  90482. return collidedAgainstList.indexOf(impostor) > -1;
  90483. });
  90484. if (sameList) {
  90485. index = idx;
  90486. }
  90487. return sameList;
  90488. }
  90489. return false;
  90490. });
  90491. if (found) {
  90492. this._onPhysicsCollideCallbacks.splice(index, 1);
  90493. }
  90494. else {
  90495. BABYLON.Tools.Warn("Function to remove was not found");
  90496. }
  90497. };
  90498. PhysicsImpostor.prototype.getParentsRotation = function () {
  90499. var parent = this.object.parent;
  90500. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  90501. while (parent) {
  90502. if (parent.rotationQuaternion) {
  90503. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  90504. }
  90505. else {
  90506. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  90507. }
  90508. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  90509. parent = parent.parent;
  90510. }
  90511. return this._tmpQuat;
  90512. };
  90513. /**
  90514. * Apply a force
  90515. */
  90516. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  90517. if (this._physicsEngine) {
  90518. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  90519. }
  90520. return this;
  90521. };
  90522. /**
  90523. * Apply an impulse
  90524. */
  90525. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  90526. if (this._physicsEngine) {
  90527. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  90528. }
  90529. return this;
  90530. };
  90531. /**
  90532. * A help function to create a joint.
  90533. */
  90534. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  90535. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  90536. this.addJoint(otherImpostor, joint);
  90537. return this;
  90538. };
  90539. /**
  90540. * Add a joint to this impostor with a different impostor.
  90541. */
  90542. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  90543. this._joints.push({
  90544. otherImpostor: otherImpostor,
  90545. joint: joint
  90546. });
  90547. if (this._physicsEngine) {
  90548. this._physicsEngine.addJoint(this, otherImpostor, joint);
  90549. }
  90550. return this;
  90551. };
  90552. /**
  90553. * Will keep this body still, in a sleep mode.
  90554. */
  90555. PhysicsImpostor.prototype.sleep = function () {
  90556. if (this._physicsEngine) {
  90557. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  90558. }
  90559. return this;
  90560. };
  90561. /**
  90562. * Wake the body up.
  90563. */
  90564. PhysicsImpostor.prototype.wakeUp = function () {
  90565. if (this._physicsEngine) {
  90566. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  90567. }
  90568. return this;
  90569. };
  90570. PhysicsImpostor.prototype.clone = function (newObject) {
  90571. if (!newObject)
  90572. return null;
  90573. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  90574. };
  90575. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  90576. var _this = this;
  90577. //no dispose if no physics engine is available.
  90578. if (!this._physicsEngine) {
  90579. return;
  90580. }
  90581. this._joints.forEach(function (j) {
  90582. if (_this._physicsEngine) {
  90583. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  90584. }
  90585. });
  90586. //dispose the physics body
  90587. this._physicsEngine.removeImpostor(this);
  90588. if (this.parent) {
  90589. this.parent.forceUpdate();
  90590. }
  90591. else {
  90592. /*this._object.getChildMeshes().forEach(function(mesh) {
  90593. if (mesh.physicsImpostor) {
  90594. if (disposeChildren) {
  90595. mesh.physicsImpostor.dispose();
  90596. mesh.physicsImpostor = null;
  90597. }
  90598. }
  90599. })*/
  90600. }
  90601. this._isDisposed = true;
  90602. };
  90603. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  90604. this._deltaPosition.copyFrom(position);
  90605. };
  90606. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  90607. if (!this._deltaRotation) {
  90608. this._deltaRotation = new BABYLON.Quaternion();
  90609. }
  90610. this._deltaRotation.copyFrom(rotation);
  90611. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  90612. };
  90613. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  90614. if (this._physicsEngine) {
  90615. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  90616. }
  90617. return this;
  90618. };
  90619. PhysicsImpostor.prototype.getRadius = function () {
  90620. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  90621. };
  90622. /**
  90623. * Sync a bone with this impostor
  90624. * @param bone The bone to sync to the impostor.
  90625. * @param boneMesh The mesh that the bone is influencing.
  90626. * @param jointPivot The pivot of the joint / bone in local space.
  90627. * @param distToJoint Optional distance from the impostor to the joint.
  90628. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  90629. */
  90630. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  90631. var tempVec = PhysicsImpostor._tmpVecs[0];
  90632. var mesh = this.object;
  90633. if (mesh.rotationQuaternion) {
  90634. if (adjustRotation) {
  90635. var tempQuat = PhysicsImpostor._tmpQuat;
  90636. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  90637. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  90638. }
  90639. else {
  90640. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  90641. }
  90642. }
  90643. tempVec.x = 0;
  90644. tempVec.y = 0;
  90645. tempVec.z = 0;
  90646. if (jointPivot) {
  90647. tempVec.x = jointPivot.x;
  90648. tempVec.y = jointPivot.y;
  90649. tempVec.z = jointPivot.z;
  90650. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  90651. if (distToJoint === undefined || distToJoint === null) {
  90652. distToJoint = jointPivot.length();
  90653. }
  90654. tempVec.x *= distToJoint;
  90655. tempVec.y *= distToJoint;
  90656. tempVec.z *= distToJoint;
  90657. }
  90658. if (bone.getParent()) {
  90659. tempVec.addInPlace(mesh.getAbsolutePosition());
  90660. bone.setAbsolutePosition(tempVec, boneMesh);
  90661. }
  90662. else {
  90663. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  90664. boneMesh.position.x -= tempVec.x;
  90665. boneMesh.position.y -= tempVec.y;
  90666. boneMesh.position.z -= tempVec.z;
  90667. }
  90668. };
  90669. /**
  90670. * Sync impostor to a bone
  90671. * @param bone The bone that the impostor will be synced to.
  90672. * @param boneMesh The mesh that the bone is influencing.
  90673. * @param jointPivot The pivot of the joint / bone in local space.
  90674. * @param distToJoint Optional distance from the impostor to the joint.
  90675. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  90676. * @param boneAxis Optional vector3 axis the bone is aligned with
  90677. */
  90678. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  90679. var mesh = this.object;
  90680. if (mesh.rotationQuaternion) {
  90681. if (adjustRotation) {
  90682. var tempQuat = PhysicsImpostor._tmpQuat;
  90683. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  90684. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  90685. }
  90686. else {
  90687. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  90688. }
  90689. }
  90690. var pos = PhysicsImpostor._tmpVecs[0];
  90691. var boneDir = PhysicsImpostor._tmpVecs[1];
  90692. if (!boneAxis) {
  90693. boneAxis = PhysicsImpostor._tmpVecs[2];
  90694. boneAxis.x = 0;
  90695. boneAxis.y = 1;
  90696. boneAxis.z = 0;
  90697. }
  90698. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  90699. bone.getAbsolutePositionToRef(boneMesh, pos);
  90700. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  90701. distToJoint = jointPivot.length();
  90702. }
  90703. if (distToJoint !== undefined && distToJoint !== null) {
  90704. pos.x += boneDir.x * distToJoint;
  90705. pos.y += boneDir.y * distToJoint;
  90706. pos.z += boneDir.z * distToJoint;
  90707. }
  90708. mesh.setAbsolutePosition(pos);
  90709. };
  90710. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  90711. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  90712. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90713. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  90714. //Impostor types
  90715. PhysicsImpostor.NoImpostor = 0;
  90716. PhysicsImpostor.SphereImpostor = 1;
  90717. PhysicsImpostor.BoxImpostor = 2;
  90718. PhysicsImpostor.PlaneImpostor = 3;
  90719. PhysicsImpostor.MeshImpostor = 4;
  90720. PhysicsImpostor.CylinderImpostor = 7;
  90721. PhysicsImpostor.ParticleImpostor = 8;
  90722. PhysicsImpostor.HeightmapImpostor = 9;
  90723. return PhysicsImpostor;
  90724. }());
  90725. BABYLON.PhysicsImpostor = PhysicsImpostor;
  90726. })(BABYLON || (BABYLON = {}));
  90727. //# sourceMappingURL=babylon.physicsImpostor.js.map
  90728. var BABYLON;
  90729. (function (BABYLON) {
  90730. /**
  90731. * Class used to control physics engine
  90732. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  90733. */
  90734. var PhysicsEngine = /** @class */ (function () {
  90735. /**
  90736. * Creates a new Physics Engine
  90737. * @param gravity defines the gravity vector used by the simulation
  90738. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  90739. */
  90740. function PhysicsEngine(gravity, _physicsPlugin) {
  90741. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  90742. this._physicsPlugin = _physicsPlugin;
  90743. this._impostors = [];
  90744. this._joints = [];
  90745. if (!this._physicsPlugin.isSupported()) {
  90746. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  90747. + "Please make sure it is included.");
  90748. }
  90749. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  90750. this.setGravity(gravity);
  90751. this.setTimeStep();
  90752. }
  90753. /**
  90754. * Sets the gravity vector used by the simulation
  90755. * @param gravity defines the gravity vector to use
  90756. */
  90757. PhysicsEngine.prototype.setGravity = function (gravity) {
  90758. this.gravity = gravity;
  90759. this._physicsPlugin.setGravity(this.gravity);
  90760. };
  90761. /**
  90762. * Set the time step of the physics engine.
  90763. * Default is 1/60.
  90764. * To slow it down, enter 1/600 for example.
  90765. * To speed it up, 1/30
  90766. * @param newTimeStep defines the new timestep to apply to this world.
  90767. */
  90768. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  90769. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  90770. this._physicsPlugin.setTimeStep(newTimeStep);
  90771. };
  90772. /**
  90773. * Get the time step of the physics engine.
  90774. * @returns the current time step
  90775. */
  90776. PhysicsEngine.prototype.getTimeStep = function () {
  90777. return this._physicsPlugin.getTimeStep();
  90778. };
  90779. /**
  90780. * Release all resources
  90781. */
  90782. PhysicsEngine.prototype.dispose = function () {
  90783. this._impostors.forEach(function (impostor) {
  90784. impostor.dispose();
  90785. });
  90786. this._physicsPlugin.dispose();
  90787. };
  90788. /**
  90789. * Gets the name of the current physics plugin
  90790. * @returns the name of the plugin
  90791. */
  90792. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  90793. return this._physicsPlugin.name;
  90794. };
  90795. /**
  90796. * Adding a new impostor for the impostor tracking.
  90797. * This will be done by the impostor itself.
  90798. * @param impostor the impostor to add
  90799. */
  90800. PhysicsEngine.prototype.addImpostor = function (impostor) {
  90801. impostor.uniqueId = this._impostors.push(impostor);
  90802. //if no parent, generate the body
  90803. if (!impostor.parent) {
  90804. this._physicsPlugin.generatePhysicsBody(impostor);
  90805. }
  90806. };
  90807. /**
  90808. * Remove an impostor from the engine.
  90809. * This impostor and its mesh will not longer be updated by the physics engine.
  90810. * @param impostor the impostor to remove
  90811. */
  90812. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  90813. var index = this._impostors.indexOf(impostor);
  90814. if (index > -1) {
  90815. var removed = this._impostors.splice(index, 1);
  90816. //Is it needed?
  90817. if (removed.length) {
  90818. //this will also remove it from the world.
  90819. removed[0].physicsBody = null;
  90820. }
  90821. }
  90822. };
  90823. /**
  90824. * Add a joint to the physics engine
  90825. * @param mainImpostor defines the main impostor to which the joint is added.
  90826. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  90827. * @param joint defines the joint that will connect both impostors.
  90828. */
  90829. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  90830. var impostorJoint = {
  90831. mainImpostor: mainImpostor,
  90832. connectedImpostor: connectedImpostor,
  90833. joint: joint
  90834. };
  90835. joint.physicsPlugin = this._physicsPlugin;
  90836. this._joints.push(impostorJoint);
  90837. this._physicsPlugin.generateJoint(impostorJoint);
  90838. };
  90839. /**
  90840. * Removes a joint from the simulation
  90841. * @param mainImpostor defines the impostor used with the joint
  90842. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  90843. * @param joint defines the joint to remove
  90844. */
  90845. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  90846. var matchingJoints = this._joints.filter(function (impostorJoint) {
  90847. return (impostorJoint.connectedImpostor === connectedImpostor
  90848. && impostorJoint.joint === joint
  90849. && impostorJoint.mainImpostor === mainImpostor);
  90850. });
  90851. if (matchingJoints.length) {
  90852. this._physicsPlugin.removeJoint(matchingJoints[0]);
  90853. //TODO remove it from the list as well
  90854. }
  90855. };
  90856. /**
  90857. * Called by the scene. No need to call it.
  90858. * @param delta defines the timespam between frames
  90859. */
  90860. PhysicsEngine.prototype._step = function (delta) {
  90861. var _this = this;
  90862. //check if any mesh has no body / requires an update
  90863. this._impostors.forEach(function (impostor) {
  90864. if (impostor.isBodyInitRequired()) {
  90865. _this._physicsPlugin.generatePhysicsBody(impostor);
  90866. }
  90867. });
  90868. if (delta > 0.1) {
  90869. delta = 0.1;
  90870. }
  90871. else if (delta <= 0) {
  90872. delta = 1.0 / 60.0;
  90873. }
  90874. this._physicsPlugin.executeStep(delta, this._impostors);
  90875. };
  90876. /**
  90877. * Gets the current plugin used to run the simulation
  90878. * @returns current plugin
  90879. */
  90880. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  90881. return this._physicsPlugin;
  90882. };
  90883. /**
  90884. * Gets the list of physic impostors
  90885. * @returns an array of PhysicsImpostor
  90886. */
  90887. PhysicsEngine.prototype.getImpostors = function () {
  90888. return this._impostors;
  90889. };
  90890. /**
  90891. * Gets the impostor for a physics enabled object
  90892. * @param object defines the object impersonated by the impostor
  90893. * @returns the PhysicsImpostor or null if not found
  90894. */
  90895. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  90896. for (var i = 0; i < this._impostors.length; ++i) {
  90897. if (this._impostors[i].object === object) {
  90898. return this._impostors[i];
  90899. }
  90900. }
  90901. return null;
  90902. };
  90903. /**
  90904. * Gets the impostor for a physics body object
  90905. * @param body defines physics body used by the impostor
  90906. * @returns the PhysicsImpostor or null if not found
  90907. */
  90908. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  90909. for (var i = 0; i < this._impostors.length; ++i) {
  90910. if (this._impostors[i].physicsBody === body) {
  90911. return this._impostors[i];
  90912. }
  90913. }
  90914. return null;
  90915. };
  90916. /**
  90917. * Global value used to control the smallest number supported by the simulation
  90918. */
  90919. PhysicsEngine.Epsilon = 0.001;
  90920. return PhysicsEngine;
  90921. }());
  90922. BABYLON.PhysicsEngine = PhysicsEngine;
  90923. })(BABYLON || (BABYLON = {}));
  90924. //# sourceMappingURL=babylon.physicsEngine.js.map
  90925. var BABYLON;
  90926. (function (BABYLON) {
  90927. var PhysicsHelper = /** @class */ (function () {
  90928. function PhysicsHelper(scene) {
  90929. this._scene = scene;
  90930. this._physicsEngine = this._scene.getPhysicsEngine();
  90931. if (!this._physicsEngine) {
  90932. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  90933. }
  90934. }
  90935. /**
  90936. * @param {Vector3} origin the origin of the explosion
  90937. * @param {number} radius the explosion radius
  90938. * @param {number} strength the explosion strength
  90939. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  90940. */
  90941. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  90942. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  90943. if (!this._physicsEngine) {
  90944. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  90945. return null;
  90946. }
  90947. var impostors = this._physicsEngine.getImpostors();
  90948. if (impostors.length === 0) {
  90949. return null;
  90950. }
  90951. var event = new PhysicsRadialExplosionEvent(this._scene);
  90952. impostors.forEach(function (impostor) {
  90953. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  90954. if (!impostorForceAndContactPoint) {
  90955. return;
  90956. }
  90957. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  90958. });
  90959. event.dispose(false);
  90960. return event;
  90961. };
  90962. /**
  90963. * @param {Vector3} origin the origin of the explosion
  90964. * @param {number} radius the explosion radius
  90965. * @param {number} strength the explosion strength
  90966. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  90967. */
  90968. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  90969. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  90970. if (!this._physicsEngine) {
  90971. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  90972. return null;
  90973. }
  90974. var impostors = this._physicsEngine.getImpostors();
  90975. if (impostors.length === 0) {
  90976. return null;
  90977. }
  90978. var event = new PhysicsRadialExplosionEvent(this._scene);
  90979. impostors.forEach(function (impostor) {
  90980. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  90981. if (!impostorForceAndContactPoint) {
  90982. return;
  90983. }
  90984. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  90985. });
  90986. event.dispose(false);
  90987. return event;
  90988. };
  90989. /**
  90990. * @param {Vector3} origin the origin of the explosion
  90991. * @param {number} radius the explosion radius
  90992. * @param {number} strength the explosion strength
  90993. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  90994. */
  90995. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  90996. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  90997. if (!this._physicsEngine) {
  90998. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  90999. return null;
  91000. }
  91001. var impostors = this._physicsEngine.getImpostors();
  91002. if (impostors.length === 0) {
  91003. return null;
  91004. }
  91005. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  91006. event.dispose(false);
  91007. return event;
  91008. };
  91009. /**
  91010. * @param {Vector3} origin the origin of the updraft
  91011. * @param {number} radius the radius of the updraft
  91012. * @param {number} strength the strength of the updraft
  91013. * @param {number} height the height of the updraft
  91014. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  91015. */
  91016. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  91017. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  91018. if (!this._physicsEngine) {
  91019. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91020. return null;
  91021. }
  91022. if (this._physicsEngine.getImpostors().length === 0) {
  91023. return null;
  91024. }
  91025. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  91026. event.dispose(false);
  91027. return event;
  91028. };
  91029. /**
  91030. * @param {Vector3} origin the of the vortex
  91031. * @param {number} radius the radius of the vortex
  91032. * @param {number} strength the strength of the vortex
  91033. * @param {number} height the height of the vortex
  91034. */
  91035. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  91036. if (!this._physicsEngine) {
  91037. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  91038. return null;
  91039. }
  91040. if (this._physicsEngine.getImpostors().length === 0) {
  91041. return null;
  91042. }
  91043. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  91044. event.dispose(false);
  91045. return event;
  91046. };
  91047. return PhysicsHelper;
  91048. }());
  91049. BABYLON.PhysicsHelper = PhysicsHelper;
  91050. /***** Radial explosion *****/
  91051. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  91052. function PhysicsRadialExplosionEvent(scene) {
  91053. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  91054. this._rays = [];
  91055. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  91056. this._scene = scene;
  91057. }
  91058. /**
  91059. * Returns the data related to the radial explosion event (sphere & rays).
  91060. * @returns {PhysicsRadialExplosionEventData}
  91061. */
  91062. PhysicsRadialExplosionEvent.prototype.getData = function () {
  91063. this._dataFetched = true;
  91064. return {
  91065. sphere: this._sphere,
  91066. rays: this._rays,
  91067. };
  91068. };
  91069. /**
  91070. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  91071. * @param impostor
  91072. * @param {Vector3} origin the origin of the explosion
  91073. * @param {number} radius the explosion radius
  91074. * @param {number} strength the explosion strength
  91075. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  91076. * @returns {Nullable<PhysicsForceAndContactPoint>}
  91077. */
  91078. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  91079. if (impostor.mass === 0) {
  91080. return null;
  91081. }
  91082. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  91083. return null;
  91084. }
  91085. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91086. return null;
  91087. }
  91088. var impostorObjectCenter = impostor.getObjectCenter();
  91089. var direction = impostorObjectCenter.subtract(origin);
  91090. var ray = new BABYLON.Ray(origin, direction, radius);
  91091. this._rays.push(ray);
  91092. var hit = ray.intersectsMesh(impostor.object);
  91093. var contactPoint = hit.pickedPoint;
  91094. if (!contactPoint) {
  91095. return null;
  91096. }
  91097. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  91098. if (distanceFromOrigin > radius) {
  91099. return null;
  91100. }
  91101. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  91102. ? strength
  91103. : strength * (1 - (distanceFromOrigin / radius));
  91104. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91105. return { force: force, contactPoint: contactPoint };
  91106. };
  91107. /**
  91108. * Disposes the sphere.
  91109. * @param {bolean} force
  91110. */
  91111. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  91112. var _this = this;
  91113. if (force === void 0) { force = true; }
  91114. if (force) {
  91115. this._sphere.dispose();
  91116. }
  91117. else {
  91118. setTimeout(function () {
  91119. if (!_this._dataFetched) {
  91120. _this._sphere.dispose();
  91121. }
  91122. }, 0);
  91123. }
  91124. };
  91125. /*** Helpers ***/
  91126. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  91127. if (!this._sphere) {
  91128. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  91129. this._sphere.isVisible = false;
  91130. }
  91131. };
  91132. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  91133. var impostorObject = impostor.object;
  91134. this._prepareSphere();
  91135. this._sphere.position = origin;
  91136. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  91137. this._sphere._updateBoundingInfo();
  91138. this._sphere.computeWorldMatrix(true);
  91139. return this._sphere.intersectsMesh(impostorObject, true);
  91140. };
  91141. return PhysicsRadialExplosionEvent;
  91142. }());
  91143. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  91144. /***** Gravitational Field *****/
  91145. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  91146. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  91147. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  91148. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91149. this._physicsHelper = physicsHelper;
  91150. this._scene = scene;
  91151. this._origin = origin;
  91152. this._radius = radius;
  91153. this._strength = strength;
  91154. this._falloff = falloff;
  91155. this._tickCallback = this._tick.bind(this);
  91156. }
  91157. /**
  91158. * Returns the data related to the gravitational field event (sphere).
  91159. * @returns {PhysicsGravitationalFieldEventData}
  91160. */
  91161. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  91162. this._dataFetched = true;
  91163. return {
  91164. sphere: this._sphere,
  91165. };
  91166. };
  91167. /**
  91168. * Enables the gravitational field.
  91169. */
  91170. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  91171. this._tickCallback.call(this);
  91172. this._scene.registerBeforeRender(this._tickCallback);
  91173. };
  91174. /**
  91175. * Disables the gravitational field.
  91176. */
  91177. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  91178. this._scene.unregisterBeforeRender(this._tickCallback);
  91179. };
  91180. /**
  91181. * Disposes the sphere.
  91182. * @param {bolean} force
  91183. */
  91184. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  91185. var _this = this;
  91186. if (force === void 0) { force = true; }
  91187. if (force) {
  91188. this._sphere.dispose();
  91189. }
  91190. else {
  91191. setTimeout(function () {
  91192. if (!_this._dataFetched) {
  91193. _this._sphere.dispose();
  91194. }
  91195. }, 0);
  91196. }
  91197. };
  91198. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  91199. // Since the params won't change, we fetch the event only once
  91200. if (this._sphere) {
  91201. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91202. }
  91203. else {
  91204. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  91205. if (radialExplosionEvent) {
  91206. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  91207. }
  91208. }
  91209. };
  91210. return PhysicsGravitationalFieldEvent;
  91211. }());
  91212. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  91213. /***** Updraft *****/
  91214. var PhysicsUpdraftEvent = /** @class */ (function () {
  91215. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  91216. this._scene = _scene;
  91217. this._origin = _origin;
  91218. this._radius = _radius;
  91219. this._strength = _strength;
  91220. this._height = _height;
  91221. this._updraftMode = _updraftMode;
  91222. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91223. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  91224. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91225. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91226. this._physicsEngine = this._scene.getPhysicsEngine();
  91227. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91228. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91229. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91230. this._originDirection = this._origin.subtract(this._originTop).normalize();
  91231. }
  91232. this._tickCallback = this._tick.bind(this);
  91233. }
  91234. /**
  91235. * Returns the data related to the updraft event (cylinder).
  91236. * @returns {PhysicsUpdraftEventData}
  91237. */
  91238. PhysicsUpdraftEvent.prototype.getData = function () {
  91239. this._dataFetched = true;
  91240. return {
  91241. cylinder: this._cylinder,
  91242. };
  91243. };
  91244. /**
  91245. * Enables the updraft.
  91246. */
  91247. PhysicsUpdraftEvent.prototype.enable = function () {
  91248. this._tickCallback.call(this);
  91249. this._scene.registerBeforeRender(this._tickCallback);
  91250. };
  91251. /**
  91252. * Disables the cortex.
  91253. */
  91254. PhysicsUpdraftEvent.prototype.disable = function () {
  91255. this._scene.unregisterBeforeRender(this._tickCallback);
  91256. };
  91257. /**
  91258. * Disposes the sphere.
  91259. * @param {bolean} force
  91260. */
  91261. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  91262. var _this = this;
  91263. if (force === void 0) { force = true; }
  91264. if (force) {
  91265. this._cylinder.dispose();
  91266. }
  91267. else {
  91268. setTimeout(function () {
  91269. if (!_this._dataFetched) {
  91270. _this._cylinder.dispose();
  91271. }
  91272. }, 0);
  91273. }
  91274. };
  91275. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91276. if (impostor.mass === 0) {
  91277. return null;
  91278. }
  91279. if (!this._intersectsWithCylinder(impostor)) {
  91280. return null;
  91281. }
  91282. var impostorObjectCenter = impostor.getObjectCenter();
  91283. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  91284. var direction = this._originDirection;
  91285. }
  91286. else {
  91287. var direction = impostorObjectCenter.subtract(this._originTop);
  91288. }
  91289. var multiplier = this._strength * -1;
  91290. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  91291. return { force: force, contactPoint: impostorObjectCenter };
  91292. };
  91293. PhysicsUpdraftEvent.prototype._tick = function () {
  91294. var _this = this;
  91295. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91296. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91297. if (!impostorForceAndContactPoint) {
  91298. return;
  91299. }
  91300. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91301. });
  91302. };
  91303. /*** Helpers ***/
  91304. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  91305. if (!this._cylinder) {
  91306. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  91307. height: this._height,
  91308. diameter: this._radius * 2,
  91309. }, this._scene);
  91310. this._cylinder.isVisible = false;
  91311. }
  91312. };
  91313. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  91314. var impostorObject = impostor.object;
  91315. this._prepareCylinder();
  91316. this._cylinder.position = this._cylinderPosition;
  91317. return this._cylinder.intersectsMesh(impostorObject, true);
  91318. };
  91319. return PhysicsUpdraftEvent;
  91320. }());
  91321. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  91322. /***** Vortex *****/
  91323. var PhysicsVortexEvent = /** @class */ (function () {
  91324. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  91325. this._scene = _scene;
  91326. this._origin = _origin;
  91327. this._radius = _radius;
  91328. this._strength = _strength;
  91329. this._height = _height;
  91330. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  91331. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  91332. this._updraftMultiplier = 0.02;
  91333. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  91334. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  91335. this._physicsEngine = this._scene.getPhysicsEngine();
  91336. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  91337. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  91338. this._tickCallback = this._tick.bind(this);
  91339. }
  91340. /**
  91341. * Returns the data related to the vortex event (cylinder).
  91342. * @returns {PhysicsVortexEventData}
  91343. */
  91344. PhysicsVortexEvent.prototype.getData = function () {
  91345. this._dataFetched = true;
  91346. return {
  91347. cylinder: this._cylinder,
  91348. };
  91349. };
  91350. /**
  91351. * Enables the vortex.
  91352. */
  91353. PhysicsVortexEvent.prototype.enable = function () {
  91354. this._tickCallback.call(this);
  91355. this._scene.registerBeforeRender(this._tickCallback);
  91356. };
  91357. /**
  91358. * Disables the cortex.
  91359. */
  91360. PhysicsVortexEvent.prototype.disable = function () {
  91361. this._scene.unregisterBeforeRender(this._tickCallback);
  91362. };
  91363. /**
  91364. * Disposes the sphere.
  91365. * @param {bolean} force
  91366. */
  91367. PhysicsVortexEvent.prototype.dispose = function (force) {
  91368. var _this = this;
  91369. if (force === void 0) { force = true; }
  91370. if (force) {
  91371. this._cylinder.dispose();
  91372. }
  91373. else {
  91374. setTimeout(function () {
  91375. if (!_this._dataFetched) {
  91376. _this._cylinder.dispose();
  91377. }
  91378. }, 0);
  91379. }
  91380. };
  91381. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  91382. if (impostor.mass === 0) {
  91383. return null;
  91384. }
  91385. if (!this._intersectsWithCylinder(impostor)) {
  91386. return null;
  91387. }
  91388. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  91389. return null;
  91390. }
  91391. var impostorObjectCenter = impostor.getObjectCenter();
  91392. 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)
  91393. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  91394. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  91395. var hit = ray.intersectsMesh(impostor.object);
  91396. var contactPoint = hit.pickedPoint;
  91397. if (!contactPoint) {
  91398. return null;
  91399. }
  91400. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  91401. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  91402. var directionToOrigin = contactPoint.normalize();
  91403. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91404. directionToOrigin = directionToOrigin.negate();
  91405. }
  91406. // TODO: find a more physically based solution
  91407. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  91408. var forceX = directionToOrigin.x * this._strength / 8;
  91409. var forceY = directionToOrigin.y * this._updraftMultiplier;
  91410. var forceZ = directionToOrigin.z * this._strength / 8;
  91411. }
  91412. else {
  91413. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  91414. var forceY = this._originTop.y * this._updraftMultiplier;
  91415. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  91416. }
  91417. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  91418. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  91419. return { force: force, contactPoint: impostorObjectCenter };
  91420. };
  91421. PhysicsVortexEvent.prototype._tick = function () {
  91422. var _this = this;
  91423. this._physicsEngine.getImpostors().forEach(function (impostor) {
  91424. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  91425. if (!impostorForceAndContactPoint) {
  91426. return;
  91427. }
  91428. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  91429. });
  91430. };
  91431. /*** Helpers ***/
  91432. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  91433. if (!this._cylinder) {
  91434. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  91435. height: this._height,
  91436. diameter: this._radius * 2,
  91437. }, this._scene);
  91438. this._cylinder.isVisible = false;
  91439. }
  91440. };
  91441. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  91442. var impostorObject = impostor.object;
  91443. this._prepareCylinder();
  91444. this._cylinder.position = this._cylinderPosition;
  91445. return this._cylinder.intersectsMesh(impostorObject, true);
  91446. };
  91447. return PhysicsVortexEvent;
  91448. }());
  91449. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  91450. /***** Enums *****/
  91451. /**
  91452. * The strenght of the force in correspondence to the distance of the affected object
  91453. */
  91454. var PhysicsRadialImpulseFalloff;
  91455. (function (PhysicsRadialImpulseFalloff) {
  91456. /** Defines that impulse is constant in strength across it's whole radius */
  91457. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  91458. /** DEfines that impulse gets weaker if it's further from the origin */
  91459. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  91460. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  91461. /**
  91462. * The strenght of the force in correspondence to the distance of the affected object
  91463. */
  91464. var PhysicsUpdraftMode;
  91465. (function (PhysicsUpdraftMode) {
  91466. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  91467. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  91468. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  91469. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  91470. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  91471. })(BABYLON || (BABYLON = {}));
  91472. //# sourceMappingURL=babylon.physicsHelper.js.map
  91473. var BABYLON;
  91474. (function (BABYLON) {
  91475. var CannonJSPlugin = /** @class */ (function () {
  91476. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  91477. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  91478. if (iterations === void 0) { iterations = 10; }
  91479. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  91480. this.name = "CannonJSPlugin";
  91481. this._physicsMaterials = new Array();
  91482. this._fixedTimeStep = 1 / 60;
  91483. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  91484. this.BJSCANNON = CANNON;
  91485. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  91486. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  91487. this._tmpPosition = BABYLON.Vector3.Zero();
  91488. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  91489. this._tmpUnityRotation = new BABYLON.Quaternion();
  91490. if (!this.isSupported()) {
  91491. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  91492. return;
  91493. }
  91494. this._extendNamespace();
  91495. this.world = new this.BJSCANNON.World();
  91496. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  91497. this.world.solver.iterations = iterations;
  91498. }
  91499. CannonJSPlugin.prototype.setGravity = function (gravity) {
  91500. this.world.gravity.copy(gravity);
  91501. };
  91502. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  91503. this._fixedTimeStep = timeStep;
  91504. };
  91505. CannonJSPlugin.prototype.getTimeStep = function () {
  91506. return this._fixedTimeStep;
  91507. };
  91508. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  91509. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  91510. };
  91511. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  91512. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91513. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91514. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  91515. };
  91516. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  91517. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  91518. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  91519. impostor.physicsBody.applyForce(impulse, worldPoint);
  91520. };
  91521. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  91522. //parent-child relationship. Does this impostor has a parent impostor?
  91523. if (impostor.parent) {
  91524. if (impostor.physicsBody) {
  91525. this.removePhysicsBody(impostor);
  91526. //TODO is that needed?
  91527. impostor.forceUpdate();
  91528. }
  91529. return;
  91530. }
  91531. //should a new body be created for this impostor?
  91532. if (impostor.isBodyInitRequired()) {
  91533. var shape = this._createShape(impostor);
  91534. //unregister events, if body is being changed
  91535. var oldBody = impostor.physicsBody;
  91536. if (oldBody) {
  91537. this.removePhysicsBody(impostor);
  91538. }
  91539. //create the body and material
  91540. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  91541. var bodyCreationObject = {
  91542. mass: impostor.getParam("mass"),
  91543. material: material
  91544. };
  91545. // A simple extend, in case native options were used.
  91546. var nativeOptions = impostor.getParam("nativeOptions");
  91547. for (var key in nativeOptions) {
  91548. if (nativeOptions.hasOwnProperty(key)) {
  91549. bodyCreationObject[key] = nativeOptions[key];
  91550. }
  91551. }
  91552. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  91553. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  91554. this.world.addEventListener("preStep", impostor.beforeStep);
  91555. this.world.addEventListener("postStep", impostor.afterStep);
  91556. impostor.physicsBody.addShape(shape);
  91557. this.world.add(impostor.physicsBody);
  91558. //try to keep the body moving in the right direction by taking old properties.
  91559. //Should be tested!
  91560. if (oldBody) {
  91561. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  91562. impostor.physicsBody[param].copy(oldBody[param]);
  91563. });
  91564. }
  91565. this._processChildMeshes(impostor);
  91566. }
  91567. //now update the body's transformation
  91568. this._updatePhysicsBodyTransformation(impostor);
  91569. };
  91570. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  91571. var _this = this;
  91572. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  91573. var currentRotation = mainImpostor.object.rotationQuaternion;
  91574. if (meshChildren.length) {
  91575. var processMesh = function (localPosition, mesh) {
  91576. if (!currentRotation || !mesh.rotationQuaternion) {
  91577. return;
  91578. }
  91579. var childImpostor = mesh.getPhysicsImpostor();
  91580. if (childImpostor) {
  91581. var parent = childImpostor.parent;
  91582. if (parent !== mainImpostor) {
  91583. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  91584. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  91585. if (childImpostor.physicsBody) {
  91586. _this.removePhysicsBody(childImpostor);
  91587. childImpostor.physicsBody = null;
  91588. }
  91589. childImpostor.parent = mainImpostor;
  91590. childImpostor.resetUpdateFlags();
  91591. 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));
  91592. //Add the mass of the children.
  91593. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  91594. }
  91595. }
  91596. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  91597. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  91598. };
  91599. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  91600. }
  91601. };
  91602. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  91603. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  91604. this.world.removeEventListener("preStep", impostor.beforeStep);
  91605. this.world.removeEventListener("postStep", impostor.afterStep);
  91606. this.world.remove(impostor.physicsBody);
  91607. };
  91608. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  91609. var mainBody = impostorJoint.mainImpostor.physicsBody;
  91610. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  91611. if (!mainBody || !connectedBody) {
  91612. return;
  91613. }
  91614. var constraint;
  91615. var jointData = impostorJoint.joint.jointData;
  91616. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  91617. var constraintData = {
  91618. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  91619. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  91620. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  91621. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  91622. maxForce: jointData.nativeParams.maxForce,
  91623. collideConnected: !!jointData.collision
  91624. };
  91625. switch (impostorJoint.joint.type) {
  91626. case BABYLON.PhysicsJoint.HingeJoint:
  91627. case BABYLON.PhysicsJoint.Hinge2Joint:
  91628. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  91629. break;
  91630. case BABYLON.PhysicsJoint.DistanceJoint:
  91631. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  91632. break;
  91633. case BABYLON.PhysicsJoint.SpringJoint:
  91634. var springData = jointData;
  91635. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  91636. restLength: springData.length,
  91637. stiffness: springData.stiffness,
  91638. damping: springData.damping,
  91639. localAnchorA: constraintData.pivotA,
  91640. localAnchorB: constraintData.pivotB
  91641. });
  91642. break;
  91643. case BABYLON.PhysicsJoint.LockJoint:
  91644. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  91645. break;
  91646. case BABYLON.PhysicsJoint.PointToPointJoint:
  91647. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  91648. default:
  91649. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  91650. break;
  91651. }
  91652. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  91653. constraint.collideConnected = !!jointData.collision;
  91654. impostorJoint.joint.physicsJoint = constraint;
  91655. //don't add spring as constraint, as it is not one.
  91656. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  91657. this.world.addConstraint(constraint);
  91658. }
  91659. else {
  91660. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  91661. constraint.applyForce();
  91662. };
  91663. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  91664. }
  91665. };
  91666. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  91667. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  91668. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  91669. }
  91670. else {
  91671. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  91672. }
  91673. };
  91674. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  91675. var index;
  91676. var mat;
  91677. for (index = 0; index < this._physicsMaterials.length; index++) {
  91678. mat = this._physicsMaterials[index];
  91679. if (mat.friction === friction && mat.restitution === restitution) {
  91680. return mat;
  91681. }
  91682. }
  91683. var currentMat = new this.BJSCANNON.Material(name);
  91684. currentMat.friction = friction;
  91685. currentMat.restitution = restitution;
  91686. this._physicsMaterials.push(currentMat);
  91687. return currentMat;
  91688. };
  91689. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  91690. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  91691. };
  91692. CannonJSPlugin.prototype._createShape = function (impostor) {
  91693. var object = impostor.object;
  91694. var returnValue;
  91695. var extendSize = impostor.getObjectExtendSize();
  91696. switch (impostor.type) {
  91697. case BABYLON.PhysicsImpostor.SphereImpostor:
  91698. var radiusX = extendSize.x;
  91699. var radiusY = extendSize.y;
  91700. var radiusZ = extendSize.z;
  91701. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  91702. break;
  91703. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  91704. case BABYLON.PhysicsImpostor.CylinderImpostor:
  91705. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  91706. break;
  91707. case BABYLON.PhysicsImpostor.BoxImpostor:
  91708. var box = extendSize.scale(0.5);
  91709. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  91710. break;
  91711. case BABYLON.PhysicsImpostor.PlaneImpostor:
  91712. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  91713. returnValue = new this.BJSCANNON.Plane();
  91714. break;
  91715. case BABYLON.PhysicsImpostor.MeshImpostor:
  91716. // should transform the vertex data to world coordinates!!
  91717. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  91718. var rawFaces = object.getIndices ? object.getIndices() : [];
  91719. if (!rawVerts)
  91720. return;
  91721. // get only scale! so the object could transform correctly.
  91722. var oldPosition = object.position.clone();
  91723. var oldRotation = object.rotation && object.rotation.clone();
  91724. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  91725. object.position.copyFromFloats(0, 0, 0);
  91726. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  91727. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  91728. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  91729. var transform = object.computeWorldMatrix(true);
  91730. // convert rawVerts to object space
  91731. var temp = new Array();
  91732. var index;
  91733. for (index = 0; index < rawVerts.length; index += 3) {
  91734. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  91735. }
  91736. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  91737. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  91738. //now set back the transformation!
  91739. object.position.copyFrom(oldPosition);
  91740. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  91741. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  91742. break;
  91743. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  91744. var oldPosition2 = object.position.clone();
  91745. var oldRotation2 = object.rotation && object.rotation.clone();
  91746. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  91747. object.position.copyFromFloats(0, 0, 0);
  91748. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  91749. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  91750. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  91751. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  91752. returnValue = this._createHeightmap(object);
  91753. object.position.copyFrom(oldPosition2);
  91754. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  91755. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  91756. object.computeWorldMatrix(true);
  91757. break;
  91758. case BABYLON.PhysicsImpostor.ParticleImpostor:
  91759. returnValue = new this.BJSCANNON.Particle();
  91760. break;
  91761. }
  91762. return returnValue;
  91763. };
  91764. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  91765. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  91766. var transform = object.computeWorldMatrix(true);
  91767. // convert rawVerts to object space
  91768. var temp = new Array();
  91769. var index;
  91770. for (index = 0; index < pos.length; index += 3) {
  91771. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  91772. }
  91773. pos = temp;
  91774. var matrix = new Array();
  91775. //For now pointDepth will not be used and will be automatically calculated.
  91776. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  91777. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  91778. var boundingInfo = object.getBoundingInfo();
  91779. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  91780. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  91781. var elementSize = dim * 2 / arraySize;
  91782. for (var i = 0; i < pos.length; i = i + 3) {
  91783. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  91784. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  91785. var y = -pos[i + 2] + minY;
  91786. if (!matrix[x]) {
  91787. matrix[x] = [];
  91788. }
  91789. if (!matrix[x][z]) {
  91790. matrix[x][z] = y;
  91791. }
  91792. matrix[x][z] = Math.max(y, matrix[x][z]);
  91793. }
  91794. for (var x = 0; x <= arraySize; ++x) {
  91795. if (!matrix[x]) {
  91796. var loc = 1;
  91797. while (!matrix[(x + loc) % arraySize]) {
  91798. loc++;
  91799. }
  91800. matrix[x] = matrix[(x + loc) % arraySize].slice();
  91801. //console.log("missing x", x);
  91802. }
  91803. for (var z = 0; z <= arraySize; ++z) {
  91804. if (!matrix[x][z]) {
  91805. var loc = 1;
  91806. var newValue;
  91807. while (newValue === undefined) {
  91808. newValue = matrix[x][(z + loc++) % arraySize];
  91809. }
  91810. matrix[x][z] = newValue;
  91811. }
  91812. }
  91813. }
  91814. var shape = new this.BJSCANNON.Heightfield(matrix, {
  91815. elementSize: elementSize
  91816. });
  91817. //For future reference, needed for body transformation
  91818. shape.minY = minY;
  91819. return shape;
  91820. };
  91821. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  91822. var object = impostor.object;
  91823. //make sure it is updated...
  91824. object.computeWorldMatrix && object.computeWorldMatrix(true);
  91825. // The delta between the mesh position and the mesh bounding box center
  91826. var bInfo = object.getBoundingInfo();
  91827. if (!bInfo)
  91828. return;
  91829. var center = impostor.getObjectCenter();
  91830. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  91831. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  91832. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  91833. this._tmpPosition.copyFrom(center);
  91834. var quaternion = object.rotationQuaternion;
  91835. if (!quaternion) {
  91836. return;
  91837. }
  91838. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  91839. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  91840. //-90 DEG in X, precalculated
  91841. quaternion = quaternion.multiply(this._minus90X);
  91842. //Invert! (Precalculated, 90 deg in X)
  91843. //No need to clone. this will never change.
  91844. impostor.setDeltaRotation(this._plus90X);
  91845. }
  91846. //If it is a heightfield, if should be centered.
  91847. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  91848. var mesh = object;
  91849. var boundingInfo = mesh.getBoundingInfo();
  91850. //calculate the correct body position:
  91851. var rotationQuaternion = mesh.rotationQuaternion;
  91852. mesh.rotationQuaternion = this._tmpUnityRotation;
  91853. mesh.computeWorldMatrix(true);
  91854. //get original center with no rotation
  91855. var c = center.clone();
  91856. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  91857. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  91858. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  91859. mesh.setPreTransformMatrix(p);
  91860. mesh.computeWorldMatrix(true);
  91861. //calculate the translation
  91862. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  91863. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  91864. //add it inverted to the delta
  91865. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  91866. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  91867. //rotation is back
  91868. mesh.rotationQuaternion = rotationQuaternion;
  91869. mesh.setPreTransformMatrix(oldPivot);
  91870. mesh.computeWorldMatrix(true);
  91871. }
  91872. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  91873. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  91874. //this._tmpPosition.copyFrom(object.position);
  91875. }
  91876. impostor.setDeltaPosition(this._tmpDeltaPosition);
  91877. //Now update the impostor object
  91878. impostor.physicsBody.position.copy(this._tmpPosition);
  91879. impostor.physicsBody.quaternion.copy(quaternion);
  91880. };
  91881. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  91882. impostor.object.position.copyFrom(impostor.physicsBody.position);
  91883. if (impostor.object.rotationQuaternion) {
  91884. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  91885. }
  91886. };
  91887. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  91888. impostor.physicsBody.position.copy(newPosition);
  91889. impostor.physicsBody.quaternion.copy(newRotation);
  91890. };
  91891. CannonJSPlugin.prototype.isSupported = function () {
  91892. return this.BJSCANNON !== undefined;
  91893. };
  91894. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  91895. impostor.physicsBody.velocity.copy(velocity);
  91896. };
  91897. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  91898. impostor.physicsBody.angularVelocity.copy(velocity);
  91899. };
  91900. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  91901. var v = impostor.physicsBody.velocity;
  91902. if (!v) {
  91903. return null;
  91904. }
  91905. return new BABYLON.Vector3(v.x, v.y, v.z);
  91906. };
  91907. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  91908. var v = impostor.physicsBody.angularVelocity;
  91909. if (!v) {
  91910. return null;
  91911. }
  91912. return new BABYLON.Vector3(v.x, v.y, v.z);
  91913. };
  91914. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  91915. impostor.physicsBody.mass = mass;
  91916. impostor.physicsBody.updateMassProperties();
  91917. };
  91918. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  91919. return impostor.physicsBody.mass;
  91920. };
  91921. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  91922. return impostor.physicsBody.material.friction;
  91923. };
  91924. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  91925. impostor.physicsBody.material.friction = friction;
  91926. };
  91927. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  91928. return impostor.physicsBody.material.restitution;
  91929. };
  91930. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  91931. impostor.physicsBody.material.restitution = restitution;
  91932. };
  91933. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  91934. impostor.physicsBody.sleep();
  91935. };
  91936. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  91937. impostor.physicsBody.wakeUp();
  91938. };
  91939. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  91940. joint.physicsJoint.distance = maxDistance;
  91941. };
  91942. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  91943. // if (!motorIndex) {
  91944. // joint.physicsJoint.enableMotor();
  91945. // }
  91946. // }
  91947. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  91948. // if (!motorIndex) {
  91949. // joint.physicsJoint.disableMotor();
  91950. // }
  91951. // }
  91952. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  91953. if (!motorIndex) {
  91954. joint.physicsJoint.enableMotor();
  91955. joint.physicsJoint.setMotorSpeed(speed);
  91956. if (maxForce) {
  91957. this.setLimit(joint, maxForce);
  91958. }
  91959. }
  91960. };
  91961. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  91962. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  91963. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  91964. };
  91965. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  91966. var body = impostor.physicsBody;
  91967. mesh.position.x = body.position.x;
  91968. mesh.position.y = body.position.y;
  91969. mesh.position.z = body.position.z;
  91970. if (mesh.rotationQuaternion) {
  91971. mesh.rotationQuaternion.x = body.quaternion.x;
  91972. mesh.rotationQuaternion.y = body.quaternion.y;
  91973. mesh.rotationQuaternion.z = body.quaternion.z;
  91974. mesh.rotationQuaternion.w = body.quaternion.w;
  91975. }
  91976. };
  91977. CannonJSPlugin.prototype.getRadius = function (impostor) {
  91978. var shape = impostor.physicsBody.shapes[0];
  91979. return shape.boundingSphereRadius;
  91980. };
  91981. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  91982. var shape = impostor.physicsBody.shapes[0];
  91983. result.x = shape.halfExtents.x * 2;
  91984. result.y = shape.halfExtents.y * 2;
  91985. result.z = shape.halfExtents.z * 2;
  91986. };
  91987. CannonJSPlugin.prototype.dispose = function () {
  91988. };
  91989. CannonJSPlugin.prototype._extendNamespace = function () {
  91990. //this will force cannon to execute at least one step when using interpolation
  91991. var step_tmp1 = new this.BJSCANNON.Vec3();
  91992. var Engine = this.BJSCANNON;
  91993. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  91994. maxSubSteps = maxSubSteps || 10;
  91995. timeSinceLastCalled = timeSinceLastCalled || 0;
  91996. if (timeSinceLastCalled === 0) {
  91997. this.internalStep(dt);
  91998. this.time += dt;
  91999. }
  92000. else {
  92001. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  92002. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  92003. var t0 = performance.now();
  92004. for (var i = 0; i !== internalSteps; i++) {
  92005. this.internalStep(dt);
  92006. if (performance.now() - t0 > dt * 1000) {
  92007. break;
  92008. }
  92009. }
  92010. this.time += timeSinceLastCalled;
  92011. var h = this.time % dt;
  92012. var h_div_dt = h / dt;
  92013. var interpvelo = step_tmp1;
  92014. var bodies = this.bodies;
  92015. for (var j = 0; j !== bodies.length; j++) {
  92016. var b = bodies[j];
  92017. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  92018. b.position.vsub(b.previousPosition, interpvelo);
  92019. interpvelo.scale(h_div_dt, interpvelo);
  92020. b.position.vadd(interpvelo, b.interpolatedPosition);
  92021. }
  92022. else {
  92023. b.interpolatedPosition.copy(b.position);
  92024. b.interpolatedQuaternion.copy(b.quaternion);
  92025. }
  92026. }
  92027. }
  92028. };
  92029. };
  92030. return CannonJSPlugin;
  92031. }());
  92032. BABYLON.CannonJSPlugin = CannonJSPlugin;
  92033. })(BABYLON || (BABYLON = {}));
  92034. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  92035. var BABYLON;
  92036. (function (BABYLON) {
  92037. var OimoJSPlugin = /** @class */ (function () {
  92038. function OimoJSPlugin(iterations) {
  92039. this.name = "OimoJSPlugin";
  92040. this._tmpImpostorsArray = [];
  92041. this._tmpPositionVector = BABYLON.Vector3.Zero();
  92042. this.BJSOIMO = OIMO;
  92043. this.world = new this.BJSOIMO.World({
  92044. iterations: iterations
  92045. });
  92046. this.world.clear();
  92047. }
  92048. OimoJSPlugin.prototype.setGravity = function (gravity) {
  92049. this.world.gravity.copy(gravity);
  92050. };
  92051. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  92052. this.world.timeStep = timeStep;
  92053. };
  92054. OimoJSPlugin.prototype.getTimeStep = function () {
  92055. return this.world.timeStep;
  92056. };
  92057. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  92058. var _this = this;
  92059. impostors.forEach(function (impostor) {
  92060. impostor.beforeStep();
  92061. });
  92062. this.world.step();
  92063. impostors.forEach(function (impostor) {
  92064. impostor.afterStep();
  92065. //update the ordered impostors array
  92066. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  92067. });
  92068. //check for collisions
  92069. var contact = this.world.contacts;
  92070. while (contact !== null) {
  92071. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  92072. contact = contact.next;
  92073. continue;
  92074. }
  92075. //is this body colliding with any other? get the impostor
  92076. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  92077. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  92078. if (!mainImpostor || !collidingImpostor) {
  92079. contact = contact.next;
  92080. continue;
  92081. }
  92082. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  92083. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  92084. contact = contact.next;
  92085. }
  92086. };
  92087. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  92088. var mass = impostor.physicsBody.mass;
  92089. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  92090. };
  92091. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  92092. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  92093. this.applyImpulse(impostor, force, contactPoint);
  92094. };
  92095. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  92096. var _this = this;
  92097. //parent-child relationship. Does this impostor has a parent impostor?
  92098. if (impostor.parent) {
  92099. if (impostor.physicsBody) {
  92100. this.removePhysicsBody(impostor);
  92101. //TODO is that needed?
  92102. impostor.forceUpdate();
  92103. }
  92104. return;
  92105. }
  92106. if (impostor.isBodyInitRequired()) {
  92107. var bodyConfig = {
  92108. name: impostor.uniqueId,
  92109. //Oimo must have mass, also for static objects.
  92110. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  92111. size: [],
  92112. type: [],
  92113. pos: [],
  92114. posShape: [],
  92115. rot: [],
  92116. rotShape: [],
  92117. move: impostor.getParam("mass") !== 0,
  92118. density: impostor.getParam("mass"),
  92119. friction: impostor.getParam("friction"),
  92120. restitution: impostor.getParam("restitution"),
  92121. //Supporting older versions of Oimo
  92122. world: this.world
  92123. };
  92124. var impostors = [impostor];
  92125. var addToArray = function (parent) {
  92126. if (!parent.getChildMeshes)
  92127. return;
  92128. parent.getChildMeshes().forEach(function (m) {
  92129. if (m.physicsImpostor) {
  92130. impostors.push(m.physicsImpostor);
  92131. //m.physicsImpostor._init();
  92132. }
  92133. });
  92134. };
  92135. addToArray(impostor.object);
  92136. var checkWithEpsilon_1 = function (value) {
  92137. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  92138. };
  92139. var globalQuaternion_1 = new BABYLON.Quaternion();
  92140. impostors.forEach(function (i) {
  92141. if (!i.object.rotationQuaternion) {
  92142. return;
  92143. }
  92144. //get the correct bounding box
  92145. var oldQuaternion = i.object.rotationQuaternion;
  92146. globalQuaternion_1 = oldQuaternion.clone();
  92147. var rot = oldQuaternion.toEulerAngles();
  92148. var extendSize = i.getObjectExtendSize();
  92149. var radToDeg = 57.295779513082320876;
  92150. if (i === impostor) {
  92151. var center = impostor.getObjectCenter();
  92152. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  92153. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  92154. //Can also use Array.prototype.push.apply
  92155. bodyConfig.pos.push(center.x);
  92156. bodyConfig.pos.push(center.y);
  92157. bodyConfig.pos.push(center.z);
  92158. bodyConfig.posShape.push(0, 0, 0);
  92159. //tmp solution
  92160. bodyConfig.rot.push(0);
  92161. bodyConfig.rot.push(0);
  92162. bodyConfig.rot.push(0);
  92163. bodyConfig.rotShape.push(0, 0, 0);
  92164. }
  92165. else {
  92166. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  92167. bodyConfig.posShape.push(localPosition.x);
  92168. bodyConfig.posShape.push(localPosition.y);
  92169. bodyConfig.posShape.push(localPosition.z);
  92170. bodyConfig.pos.push(0, 0, 0);
  92171. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  92172. bodyConfig.rot.push(0);
  92173. bodyConfig.rot.push(0);
  92174. bodyConfig.rot.push(0);
  92175. bodyConfig.rotShape.push(rot.x * radToDeg);
  92176. bodyConfig.rotShape.push(rot.y * radToDeg);
  92177. bodyConfig.rotShape.push(rot.z * radToDeg);
  92178. }
  92179. // register mesh
  92180. switch (i.type) {
  92181. case BABYLON.PhysicsImpostor.ParticleImpostor:
  92182. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  92183. case BABYLON.PhysicsImpostor.SphereImpostor:
  92184. var radiusX = extendSize.x;
  92185. var radiusY = extendSize.y;
  92186. var radiusZ = extendSize.z;
  92187. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  92188. bodyConfig.type.push('sphere');
  92189. //due to the way oimo works with compounds, add 3 times
  92190. bodyConfig.size.push(size);
  92191. bodyConfig.size.push(size);
  92192. bodyConfig.size.push(size);
  92193. break;
  92194. case BABYLON.PhysicsImpostor.CylinderImpostor:
  92195. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  92196. var sizeY = checkWithEpsilon_1(extendSize.y);
  92197. bodyConfig.type.push('cylinder');
  92198. bodyConfig.size.push(sizeX);
  92199. bodyConfig.size.push(sizeY);
  92200. //due to the way oimo works with compounds, add one more value.
  92201. bodyConfig.size.push(sizeY);
  92202. break;
  92203. case BABYLON.PhysicsImpostor.PlaneImpostor:
  92204. case BABYLON.PhysicsImpostor.BoxImpostor:
  92205. default:
  92206. var sizeX = checkWithEpsilon_1(extendSize.x);
  92207. var sizeY = checkWithEpsilon_1(extendSize.y);
  92208. var sizeZ = checkWithEpsilon_1(extendSize.z);
  92209. bodyConfig.type.push('box');
  92210. //if (i === impostor) {
  92211. bodyConfig.size.push(sizeX);
  92212. bodyConfig.size.push(sizeY);
  92213. bodyConfig.size.push(sizeZ);
  92214. //} else {
  92215. // bodyConfig.size.push(0,0,0);
  92216. //}
  92217. break;
  92218. }
  92219. //actually not needed, but hey...
  92220. i.object.rotationQuaternion = oldQuaternion;
  92221. });
  92222. impostor.physicsBody = this.world.add(bodyConfig);
  92223. // set the quaternion, ignoring the previously defined (euler) rotation
  92224. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  92225. // update with delta 0, so the body will reveive the new rotation.
  92226. impostor.physicsBody.updatePosition(0);
  92227. }
  92228. else {
  92229. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  92230. }
  92231. impostor.setDeltaPosition(this._tmpPositionVector);
  92232. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  92233. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  92234. };
  92235. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  92236. //impostor.physicsBody.dispose();
  92237. //Same as : (older oimo versions)
  92238. this.world.removeRigidBody(impostor.physicsBody);
  92239. };
  92240. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  92241. var mainBody = impostorJoint.mainImpostor.physicsBody;
  92242. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  92243. if (!mainBody || !connectedBody) {
  92244. return;
  92245. }
  92246. var jointData = impostorJoint.joint.jointData;
  92247. var options = jointData.nativeParams || {};
  92248. var type;
  92249. var nativeJointData = {
  92250. body1: mainBody,
  92251. body2: connectedBody,
  92252. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  92253. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  92254. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  92255. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  92256. min: options.min,
  92257. max: options.max,
  92258. collision: options.collision || jointData.collision,
  92259. spring: options.spring,
  92260. //supporting older version of Oimo
  92261. world: this.world
  92262. };
  92263. switch (impostorJoint.joint.type) {
  92264. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  92265. type = "jointBall";
  92266. break;
  92267. case BABYLON.PhysicsJoint.SpringJoint:
  92268. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  92269. var springData = jointData;
  92270. nativeJointData.min = springData.length || nativeJointData.min;
  92271. //Max should also be set, just make sure it is at least min
  92272. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  92273. case BABYLON.PhysicsJoint.DistanceJoint:
  92274. type = "jointDistance";
  92275. nativeJointData.max = jointData.maxDistance;
  92276. break;
  92277. case BABYLON.PhysicsJoint.PrismaticJoint:
  92278. type = "jointPrisme";
  92279. break;
  92280. case BABYLON.PhysicsJoint.SliderJoint:
  92281. type = "jointSlide";
  92282. break;
  92283. case BABYLON.PhysicsJoint.WheelJoint:
  92284. type = "jointWheel";
  92285. break;
  92286. case BABYLON.PhysicsJoint.HingeJoint:
  92287. default:
  92288. type = "jointHinge";
  92289. break;
  92290. }
  92291. nativeJointData.type = type;
  92292. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  92293. };
  92294. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  92295. //Bug in Oimo prevents us from disposing a joint in the playground
  92296. //joint.joint.physicsJoint.dispose();
  92297. //So we will bruteforce it!
  92298. try {
  92299. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  92300. }
  92301. catch (e) {
  92302. BABYLON.Tools.Warn(e);
  92303. }
  92304. };
  92305. OimoJSPlugin.prototype.isSupported = function () {
  92306. return this.BJSOIMO !== undefined;
  92307. };
  92308. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  92309. if (!impostor.physicsBody.sleeping) {
  92310. //TODO check that
  92311. /*if (impostor.physicsBody.shapes.next) {
  92312. var parentShape = this._getLastShape(impostor.physicsBody);
  92313. impostor.object.position.copyFrom(parentShape.position);
  92314. console.log(parentShape.position);
  92315. } else {*/
  92316. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  92317. //}
  92318. if (impostor.object.rotationQuaternion) {
  92319. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  92320. }
  92321. }
  92322. };
  92323. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  92324. var body = impostor.physicsBody;
  92325. body.position.copy(newPosition);
  92326. body.orientation.copy(newRotation);
  92327. body.syncShapes();
  92328. body.awake();
  92329. };
  92330. /*private _getLastShape(body: any): any {
  92331. var lastShape = body.shapes;
  92332. while (lastShape.next) {
  92333. lastShape = lastShape.next;
  92334. }
  92335. return lastShape;
  92336. }*/
  92337. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  92338. impostor.physicsBody.linearVelocity.copy(velocity);
  92339. };
  92340. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  92341. impostor.physicsBody.angularVelocity.copy(velocity);
  92342. };
  92343. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  92344. var v = impostor.physicsBody.linearVelocity;
  92345. if (!v) {
  92346. return null;
  92347. }
  92348. return new BABYLON.Vector3(v.x, v.y, v.z);
  92349. };
  92350. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  92351. var v = impostor.physicsBody.angularVelocity;
  92352. if (!v) {
  92353. return null;
  92354. }
  92355. return new BABYLON.Vector3(v.x, v.y, v.z);
  92356. };
  92357. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  92358. var staticBody = mass === 0;
  92359. //this will actually set the body's density and not its mass.
  92360. //But this is how oimo treats the mass variable.
  92361. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  92362. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  92363. };
  92364. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  92365. return impostor.physicsBody.shapes.density;
  92366. };
  92367. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  92368. return impostor.physicsBody.shapes.friction;
  92369. };
  92370. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  92371. impostor.physicsBody.shapes.friction = friction;
  92372. };
  92373. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  92374. return impostor.physicsBody.shapes.restitution;
  92375. };
  92376. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  92377. impostor.physicsBody.shapes.restitution = restitution;
  92378. };
  92379. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  92380. impostor.physicsBody.sleep();
  92381. };
  92382. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  92383. impostor.physicsBody.awake();
  92384. };
  92385. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  92386. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  92387. if (minDistance !== void 0) {
  92388. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  92389. }
  92390. };
  92391. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  92392. //TODO separate rotational and transational motors.
  92393. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92394. if (motor) {
  92395. motor.setMotor(speed, maxForce);
  92396. }
  92397. };
  92398. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  92399. //TODO separate rotational and transational motors.
  92400. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  92401. if (motor) {
  92402. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  92403. }
  92404. };
  92405. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  92406. var body = impostor.physicsBody;
  92407. mesh.position.x = body.position.x;
  92408. mesh.position.y = body.position.y;
  92409. mesh.position.z = body.position.z;
  92410. if (mesh.rotationQuaternion) {
  92411. mesh.rotationQuaternion.x = body.orientation.x;
  92412. mesh.rotationQuaternion.y = body.orientation.y;
  92413. mesh.rotationQuaternion.z = body.orientation.z;
  92414. mesh.rotationQuaternion.w = body.orientation.s;
  92415. }
  92416. };
  92417. OimoJSPlugin.prototype.getRadius = function (impostor) {
  92418. return impostor.physicsBody.shapes.radius;
  92419. };
  92420. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  92421. var shape = impostor.physicsBody.shapes;
  92422. result.x = shape.halfWidth * 2;
  92423. result.y = shape.halfHeight * 2;
  92424. result.z = shape.halfDepth * 2;
  92425. };
  92426. OimoJSPlugin.prototype.dispose = function () {
  92427. this.world.clear();
  92428. };
  92429. return OimoJSPlugin;
  92430. }());
  92431. BABYLON.OimoJSPlugin = OimoJSPlugin;
  92432. })(BABYLON || (BABYLON = {}));
  92433. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  92434. var BABYLON;
  92435. (function (BABYLON) {
  92436. /**
  92437. * Gets the current physics engine
  92438. * @returns a IPhysicsEngine or null if none attached
  92439. */
  92440. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  92441. return this._physicsEngine;
  92442. };
  92443. /**
  92444. * Enables physics to the current scene
  92445. * @param gravity defines the scene's gravity for the physics engine
  92446. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  92447. * @return a boolean indicating if the physics engine was initialized
  92448. */
  92449. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  92450. if (gravity === void 0) { gravity = null; }
  92451. if (this._physicsEngine) {
  92452. return true;
  92453. }
  92454. // Register the component to the scene
  92455. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  92456. if (!component) {
  92457. component = new PhysicsEngineSceneComponent(this);
  92458. this._addComponent(component);
  92459. }
  92460. try {
  92461. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  92462. return true;
  92463. }
  92464. catch (e) {
  92465. BABYLON.Tools.Error(e.message);
  92466. return false;
  92467. }
  92468. };
  92469. /**
  92470. * Disables and disposes the physics engine associated with the scene
  92471. */
  92472. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  92473. if (!this._physicsEngine) {
  92474. return;
  92475. }
  92476. this._physicsEngine.dispose();
  92477. this._physicsEngine = null;
  92478. };
  92479. /**
  92480. * Gets a boolean indicating if there is an active physics engine
  92481. * @returns a boolean indicating if there is an active physics engine
  92482. */
  92483. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  92484. return this._physicsEngine !== undefined;
  92485. };
  92486. /**
  92487. * Deletes a physics compound impostor
  92488. * @param compound defines the compound to delete
  92489. */
  92490. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  92491. var mesh = compound.parts[0].mesh;
  92492. if (mesh.physicsImpostor) {
  92493. mesh.physicsImpostor.dispose( /*true*/);
  92494. mesh.physicsImpostor = null;
  92495. }
  92496. };
  92497. /** @hidden */
  92498. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  92499. if (this._physicsEngine) {
  92500. this.onBeforePhysicsObservable.notifyObservers(this);
  92501. this._physicsEngine._step(step / 1000);
  92502. this.onAfterPhysicsObservable.notifyObservers(this);
  92503. }
  92504. };
  92505. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  92506. get: function () {
  92507. return this._physicsImpostor;
  92508. },
  92509. set: function (value) {
  92510. var _this = this;
  92511. if (this._physicsImpostor === value) {
  92512. return;
  92513. }
  92514. if (this._disposePhysicsObserver) {
  92515. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  92516. }
  92517. this._physicsImpostor = value;
  92518. if (value) {
  92519. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  92520. // Physics
  92521. if (_this.physicsImpostor) {
  92522. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  92523. _this.physicsImpostor = null;
  92524. }
  92525. });
  92526. }
  92527. },
  92528. enumerable: true,
  92529. configurable: true
  92530. });
  92531. /**
  92532. * Gets the current physics impostor
  92533. * @see http://doc.babylonjs.com/features/physics_engine
  92534. * @returns a physics impostor or null
  92535. */
  92536. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  92537. return this.physicsImpostor;
  92538. };
  92539. /**
  92540. * Apply a physic impulse to the mesh
  92541. * @param force defines the force to apply
  92542. * @param contactPoint defines where to apply the force
  92543. * @returns the current mesh
  92544. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  92545. */
  92546. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  92547. if (!this.physicsImpostor) {
  92548. return this;
  92549. }
  92550. this.physicsImpostor.applyImpulse(force, contactPoint);
  92551. return this;
  92552. };
  92553. /**
  92554. * Creates a physic joint between two meshes
  92555. * @param otherMesh defines the other mesh to use
  92556. * @param pivot1 defines the pivot to use on this mesh
  92557. * @param pivot2 defines the pivot to use on the other mesh
  92558. * @param options defines additional options (can be plugin dependent)
  92559. * @returns the current mesh
  92560. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  92561. */
  92562. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  92563. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  92564. return this;
  92565. }
  92566. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  92567. mainPivot: pivot1,
  92568. connectedPivot: pivot2,
  92569. nativeParams: options
  92570. });
  92571. return this;
  92572. };
  92573. /**
  92574. * Defines the physics engine scene component responsible to manage a physics engine
  92575. */
  92576. var PhysicsEngineSceneComponent = /** @class */ (function () {
  92577. /**
  92578. * Creates a new instance of the component for the given scene
  92579. * @param scene Defines the scene to register the component in
  92580. */
  92581. function PhysicsEngineSceneComponent(scene) {
  92582. var _this = this;
  92583. /**
  92584. * The component name helpful to identify the component in the list of scene components.
  92585. */
  92586. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  92587. this.scene = scene;
  92588. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  92589. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  92590. // Replace the function used to get the deterministic frame time
  92591. this.scene.getDeterministicFrameTime = function () {
  92592. if (_this.scene._physicsEngine) {
  92593. return _this.scene._physicsEngine.getTimeStep() * 1000;
  92594. }
  92595. return 1000.0 / 60.0;
  92596. };
  92597. }
  92598. /**
  92599. * Registers the component in a given scene
  92600. */
  92601. PhysicsEngineSceneComponent.prototype.register = function () {
  92602. };
  92603. /**
  92604. * Rebuilds the elements related to this component in case of
  92605. * context lost for instance.
  92606. */
  92607. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  92608. // Nothing to do for this component
  92609. };
  92610. /**
  92611. * Disposes the component and the associated ressources
  92612. */
  92613. PhysicsEngineSceneComponent.prototype.dispose = function () {
  92614. this.scene.onBeforePhysicsObservable.clear();
  92615. this.scene.onAfterPhysicsObservable.clear();
  92616. if (this.scene._physicsEngine) {
  92617. this.scene.disablePhysicsEngine();
  92618. }
  92619. };
  92620. return PhysicsEngineSceneComponent;
  92621. }());
  92622. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  92623. })(BABYLON || (BABYLON = {}));
  92624. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  92625. var BABYLON;
  92626. (function (BABYLON) {
  92627. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  92628. // All values and structures referenced from:
  92629. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  92630. var DDS_MAGIC = 0x20534444;
  92631. var
  92632. //DDSD_CAPS = 0x1,
  92633. //DDSD_HEIGHT = 0x2,
  92634. //DDSD_WIDTH = 0x4,
  92635. //DDSD_PITCH = 0x8,
  92636. //DDSD_PIXELFORMAT = 0x1000,
  92637. DDSD_MIPMAPCOUNT = 0x20000;
  92638. //DDSD_LINEARSIZE = 0x80000,
  92639. //DDSD_DEPTH = 0x800000;
  92640. // var DDSCAPS_COMPLEX = 0x8,
  92641. // DDSCAPS_MIPMAP = 0x400000,
  92642. // DDSCAPS_TEXTURE = 0x1000;
  92643. var DDSCAPS2_CUBEMAP = 0x200;
  92644. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  92645. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  92646. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  92647. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  92648. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  92649. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  92650. // DDSCAPS2_VOLUME = 0x200000;
  92651. var
  92652. //DDPF_ALPHAPIXELS = 0x1,
  92653. //DDPF_ALPHA = 0x2,
  92654. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  92655. //DDPF_YUV = 0x200,
  92656. DDPF_LUMINANCE = 0x20000;
  92657. function FourCCToInt32(value) {
  92658. return value.charCodeAt(0) +
  92659. (value.charCodeAt(1) << 8) +
  92660. (value.charCodeAt(2) << 16) +
  92661. (value.charCodeAt(3) << 24);
  92662. }
  92663. function Int32ToFourCC(value) {
  92664. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  92665. }
  92666. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  92667. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  92668. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  92669. var FOURCC_DX10 = FourCCToInt32("DX10");
  92670. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  92671. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  92672. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  92673. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  92674. var headerLengthInt = 31; // The header length in 32 bit ints
  92675. // Offsets into the header array
  92676. var off_magic = 0;
  92677. var off_size = 1;
  92678. var off_flags = 2;
  92679. var off_height = 3;
  92680. var off_width = 4;
  92681. var off_mipmapCount = 7;
  92682. var off_pfFlags = 20;
  92683. var off_pfFourCC = 21;
  92684. var off_RGBbpp = 22;
  92685. var off_RMask = 23;
  92686. var off_GMask = 24;
  92687. var off_BMask = 25;
  92688. var off_AMask = 26;
  92689. // var off_caps1 = 27;
  92690. var off_caps2 = 28;
  92691. // var off_caps3 = 29;
  92692. // var off_caps4 = 30;
  92693. var off_dxgiFormat = 32;
  92694. ;
  92695. var DDSTools = /** @class */ (function () {
  92696. function DDSTools() {
  92697. }
  92698. DDSTools.GetDDSInfo = function (arrayBuffer) {
  92699. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  92700. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  92701. var mipmapCount = 1;
  92702. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  92703. mipmapCount = Math.max(1, header[off_mipmapCount]);
  92704. }
  92705. var fourCC = header[off_pfFourCC];
  92706. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  92707. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92708. switch (fourCC) {
  92709. case FOURCC_D3DFMT_R16G16B16A16F:
  92710. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92711. break;
  92712. case FOURCC_D3DFMT_R32G32B32A32F:
  92713. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  92714. break;
  92715. case FOURCC_DX10:
  92716. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  92717. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92718. break;
  92719. }
  92720. }
  92721. return {
  92722. width: header[off_width],
  92723. height: header[off_height],
  92724. mipmapCount: mipmapCount,
  92725. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  92726. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  92727. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  92728. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  92729. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  92730. dxgiFormat: dxgiFormat,
  92731. textureType: textureType
  92732. };
  92733. };
  92734. DDSTools._ToHalfFloat = function (value) {
  92735. if (!DDSTools._FloatView) {
  92736. DDSTools._FloatView = new Float32Array(1);
  92737. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  92738. }
  92739. DDSTools._FloatView[0] = value;
  92740. var x = DDSTools._Int32View[0];
  92741. var bits = (x >> 16) & 0x8000; /* Get the sign */
  92742. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  92743. var e = (x >> 23) & 0xff; /* Using int is faster here */
  92744. /* If zero, or denormal, or exponent underflows too much for a denormal
  92745. * half, return signed zero. */
  92746. if (e < 103) {
  92747. return bits;
  92748. }
  92749. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  92750. if (e > 142) {
  92751. bits |= 0x7c00;
  92752. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  92753. * not Inf, so make sure we set one mantissa bit too. */
  92754. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  92755. return bits;
  92756. }
  92757. /* If exponent underflows but not too much, return a denormal */
  92758. if (e < 113) {
  92759. m |= 0x0800;
  92760. /* Extra rounding may overflow and set mantissa to 0 and exponent
  92761. * to 1, which is OK. */
  92762. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  92763. return bits;
  92764. }
  92765. bits |= ((e - 112) << 10) | (m >> 1);
  92766. bits += m & 1;
  92767. return bits;
  92768. };
  92769. DDSTools._FromHalfFloat = function (value) {
  92770. var s = (value & 0x8000) >> 15;
  92771. var e = (value & 0x7C00) >> 10;
  92772. var f = value & 0x03FF;
  92773. if (e === 0) {
  92774. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  92775. }
  92776. else if (e == 0x1F) {
  92777. return f ? NaN : ((s ? -1 : 1) * Infinity);
  92778. }
  92779. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  92780. };
  92781. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92782. var destArray = new Float32Array(dataLength);
  92783. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  92784. var index = 0;
  92785. for (var y = 0; y < height; y++) {
  92786. for (var x = 0; x < width; x++) {
  92787. var srcPos = (x + y * width) * 4;
  92788. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  92789. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  92790. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  92791. if (DDSTools.StoreLODInAlphaChannel) {
  92792. destArray[index + 3] = lod;
  92793. }
  92794. else {
  92795. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  92796. }
  92797. index += 4;
  92798. }
  92799. }
  92800. return destArray;
  92801. };
  92802. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92803. if (DDSTools.StoreLODInAlphaChannel) {
  92804. var destArray = new Uint16Array(dataLength);
  92805. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  92806. var index = 0;
  92807. for (var y = 0; y < height; y++) {
  92808. for (var x = 0; x < width; x++) {
  92809. var srcPos = (x + y * width) * 4;
  92810. destArray[index] = srcData[srcPos];
  92811. destArray[index + 1] = srcData[srcPos + 1];
  92812. destArray[index + 2] = srcData[srcPos + 2];
  92813. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  92814. index += 4;
  92815. }
  92816. }
  92817. return destArray;
  92818. }
  92819. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  92820. };
  92821. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92822. if (DDSTools.StoreLODInAlphaChannel) {
  92823. var destArray = new Float32Array(dataLength);
  92824. var srcData = new Float32Array(arrayBuffer, dataOffset);
  92825. var index = 0;
  92826. for (var y = 0; y < height; y++) {
  92827. for (var x = 0; x < width; x++) {
  92828. var srcPos = (x + y * width) * 4;
  92829. destArray[index] = srcData[srcPos];
  92830. destArray[index + 1] = srcData[srcPos + 1];
  92831. destArray[index + 2] = srcData[srcPos + 2];
  92832. destArray[index + 3] = lod;
  92833. index += 4;
  92834. }
  92835. }
  92836. return destArray;
  92837. }
  92838. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  92839. };
  92840. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92841. var destArray = new Uint8Array(dataLength);
  92842. var srcData = new Float32Array(arrayBuffer, dataOffset);
  92843. var index = 0;
  92844. for (var y = 0; y < height; y++) {
  92845. for (var x = 0; x < width; x++) {
  92846. var srcPos = (x + y * width) * 4;
  92847. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  92848. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  92849. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  92850. if (DDSTools.StoreLODInAlphaChannel) {
  92851. destArray[index + 3] = lod;
  92852. }
  92853. else {
  92854. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  92855. }
  92856. index += 4;
  92857. }
  92858. }
  92859. return destArray;
  92860. };
  92861. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  92862. var destArray = new Uint8Array(dataLength);
  92863. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  92864. var index = 0;
  92865. for (var y = 0; y < height; y++) {
  92866. for (var x = 0; x < width; x++) {
  92867. var srcPos = (x + y * width) * 4;
  92868. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  92869. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  92870. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  92871. if (DDSTools.StoreLODInAlphaChannel) {
  92872. destArray[index + 3] = lod;
  92873. }
  92874. else {
  92875. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  92876. }
  92877. index += 4;
  92878. }
  92879. }
  92880. return destArray;
  92881. };
  92882. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  92883. var byteArray = new Uint8Array(dataLength);
  92884. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  92885. var index = 0;
  92886. for (var y = 0; y < height; y++) {
  92887. for (var x = 0; x < width; x++) {
  92888. var srcPos = (x + y * width) * 4;
  92889. byteArray[index] = srcData[srcPos + rOffset];
  92890. byteArray[index + 1] = srcData[srcPos + gOffset];
  92891. byteArray[index + 2] = srcData[srcPos + bOffset];
  92892. byteArray[index + 3] = srcData[srcPos + aOffset];
  92893. index += 4;
  92894. }
  92895. }
  92896. return byteArray;
  92897. };
  92898. DDSTools._ExtractLongWordOrder = function (value) {
  92899. if (value === 0 || value === 255 || value === -16777216) {
  92900. return 0;
  92901. }
  92902. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  92903. };
  92904. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  92905. var byteArray = new Uint8Array(dataLength);
  92906. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  92907. var index = 0;
  92908. for (var y = 0; y < height; y++) {
  92909. for (var x = 0; x < width; x++) {
  92910. var srcPos = (x + y * width) * 3;
  92911. byteArray[index] = srcData[srcPos + rOffset];
  92912. byteArray[index + 1] = srcData[srcPos + gOffset];
  92913. byteArray[index + 2] = srcData[srcPos + bOffset];
  92914. index += 3;
  92915. }
  92916. }
  92917. return byteArray;
  92918. };
  92919. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  92920. var byteArray = new Uint8Array(dataLength);
  92921. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  92922. var index = 0;
  92923. for (var y = 0; y < height; y++) {
  92924. for (var x = 0; x < width; x++) {
  92925. var srcPos = (x + y * width);
  92926. byteArray[index] = srcData[srcPos];
  92927. index++;
  92928. }
  92929. }
  92930. return byteArray;
  92931. };
  92932. /**
  92933. * Uploads DDS Levels to a Babylon Texture
  92934. * @hidden
  92935. */
  92936. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  92937. if (lodIndex === void 0) { lodIndex = -1; }
  92938. var sphericalPolynomialFaces = null;
  92939. if (info.sphericalPolynomial) {
  92940. sphericalPolynomialFaces = new Array();
  92941. }
  92942. var ext = engine.getCaps().s3tc;
  92943. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  92944. var fourCC, width, height, dataLength = 0, dataOffset;
  92945. var byteArray, mipmapCount, mip;
  92946. var internalCompressedFormat = 0;
  92947. var blockBytes = 1;
  92948. if (header[off_magic] !== DDS_MAGIC) {
  92949. BABYLON.Tools.Error("Invalid magic number in DDS header");
  92950. return;
  92951. }
  92952. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  92953. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  92954. return;
  92955. }
  92956. if (info.isCompressed && !ext) {
  92957. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  92958. return;
  92959. }
  92960. var bpp = header[off_RGBbpp];
  92961. dataOffset = header[off_size] + 4;
  92962. var computeFormats = false;
  92963. if (info.isFourCC) {
  92964. fourCC = header[off_pfFourCC];
  92965. switch (fourCC) {
  92966. case FOURCC_DXT1:
  92967. blockBytes = 8;
  92968. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  92969. break;
  92970. case FOURCC_DXT3:
  92971. blockBytes = 16;
  92972. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  92973. break;
  92974. case FOURCC_DXT5:
  92975. blockBytes = 16;
  92976. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  92977. break;
  92978. case FOURCC_D3DFMT_R16G16B16A16F:
  92979. computeFormats = true;
  92980. break;
  92981. case FOURCC_D3DFMT_R32G32B32A32F:
  92982. computeFormats = true;
  92983. break;
  92984. case FOURCC_DX10:
  92985. // There is an additionnal header so dataOffset need to be changed
  92986. dataOffset += 5 * 4; // 5 uints
  92987. var supported = false;
  92988. switch (info.dxgiFormat) {
  92989. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  92990. computeFormats = true;
  92991. supported = true;
  92992. break;
  92993. case DXGI_FORMAT_B8G8R8X8_UNORM:
  92994. info.isRGB = true;
  92995. info.isFourCC = false;
  92996. bpp = 32;
  92997. supported = true;
  92998. break;
  92999. }
  93000. if (supported) {
  93001. break;
  93002. }
  93003. default:
  93004. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  93005. return;
  93006. }
  93007. }
  93008. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  93009. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  93010. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  93011. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  93012. if (computeFormats) {
  93013. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  93014. }
  93015. mipmapCount = 1;
  93016. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  93017. mipmapCount = Math.max(1, header[off_mipmapCount]);
  93018. }
  93019. for (var face = 0; face < faces; face++) {
  93020. width = header[off_width];
  93021. height = header[off_height];
  93022. for (mip = 0; mip < mipmapCount; ++mip) {
  93023. if (lodIndex === -1 || lodIndex === mip) {
  93024. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  93025. var i = (lodIndex === -1) ? mip : 0;
  93026. if (!info.isCompressed && info.isFourCC) {
  93027. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93028. dataLength = width * height * 4;
  93029. var floatArray = null;
  93030. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  93031. if (bpp === 128) {
  93032. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93033. if (sphericalPolynomialFaces && i == 0) {
  93034. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93035. }
  93036. }
  93037. else if (bpp === 64) {
  93038. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93039. if (sphericalPolynomialFaces && i == 0) {
  93040. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93041. }
  93042. }
  93043. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93044. }
  93045. else {
  93046. if (bpp === 128) {
  93047. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93048. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93049. if (sphericalPolynomialFaces && i == 0) {
  93050. sphericalPolynomialFaces.push(floatArray);
  93051. }
  93052. }
  93053. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  93054. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93055. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93056. if (sphericalPolynomialFaces && i == 0) {
  93057. sphericalPolynomialFaces.push(floatArray);
  93058. }
  93059. }
  93060. else { // 64
  93061. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93062. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  93063. if (sphericalPolynomialFaces && i == 0) {
  93064. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  93065. }
  93066. }
  93067. }
  93068. if (floatArray) {
  93069. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  93070. }
  93071. }
  93072. else if (info.isRGB) {
  93073. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93074. if (bpp === 24) {
  93075. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  93076. dataLength = width * height * 3;
  93077. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  93078. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93079. }
  93080. else { // 32
  93081. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  93082. dataLength = width * height * 4;
  93083. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  93084. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93085. }
  93086. }
  93087. else if (info.isLuminance) {
  93088. var unpackAlignment = engine._getUnpackAlignement();
  93089. var unpaddedRowSize = width;
  93090. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  93091. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  93092. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  93093. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  93094. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93095. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  93096. }
  93097. else {
  93098. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  93099. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  93100. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  93101. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  93102. }
  93103. }
  93104. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  93105. width *= 0.5;
  93106. height *= 0.5;
  93107. width = Math.max(1.0, width);
  93108. height = Math.max(1.0, height);
  93109. }
  93110. if (currentFace !== undefined) {
  93111. // Loading a single face
  93112. break;
  93113. }
  93114. }
  93115. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  93116. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  93117. size: header[off_width],
  93118. right: sphericalPolynomialFaces[0],
  93119. left: sphericalPolynomialFaces[1],
  93120. up: sphericalPolynomialFaces[2],
  93121. down: sphericalPolynomialFaces[3],
  93122. front: sphericalPolynomialFaces[4],
  93123. back: sphericalPolynomialFaces[5],
  93124. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  93125. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  93126. gammaSpace: false,
  93127. });
  93128. }
  93129. else {
  93130. info.sphericalPolynomial = undefined;
  93131. }
  93132. };
  93133. DDSTools.StoreLODInAlphaChannel = false;
  93134. return DDSTools;
  93135. }());
  93136. BABYLON.DDSTools = DDSTools;
  93137. })(BABYLON || (BABYLON = {}));
  93138. //# sourceMappingURL=babylon.dds.js.map
  93139. var BABYLON;
  93140. (function (BABYLON) {
  93141. /**
  93142. * Implementation of the DDS Texture Loader.
  93143. */
  93144. var DDSTextureLoader = /** @class */ (function () {
  93145. function DDSTextureLoader() {
  93146. /**
  93147. * Defines wether the loader supports cascade loading the different faces.
  93148. */
  93149. this.supportCascades = true;
  93150. }
  93151. /**
  93152. * This returns if the loader support the current file information.
  93153. * @param extension defines the file extension of the file being loaded
  93154. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93155. * @param fallback defines the fallback internal texture if any
  93156. * @param isBase64 defines whether the texture is encoded as a base64
  93157. * @param isBuffer defines whether the texture data are stored as a buffer
  93158. * @returns true if the loader can load the specified file
  93159. */
  93160. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93161. return extension.indexOf(".dds") === 0;
  93162. };
  93163. /**
  93164. * Transform the url before loading if required.
  93165. * @param rootUrl the url of the texture
  93166. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93167. * @returns the transformed texture
  93168. */
  93169. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93170. return rootUrl;
  93171. };
  93172. /**
  93173. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93174. * @param rootUrl the url of the texture
  93175. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93176. * @returns the fallback texture
  93177. */
  93178. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93179. return null;
  93180. };
  93181. /**
  93182. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93183. * @param data contains the texture data
  93184. * @param texture defines the BabylonJS internal texture
  93185. * @param createPolynomials will be true if polynomials have been requested
  93186. * @param onLoad defines the callback to trigger once the texture is ready
  93187. * @param onError defines the callback to trigger in case of error
  93188. */
  93189. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  93190. var engine = texture.getEngine();
  93191. var info;
  93192. var loadMipmap = false;
  93193. if (Array.isArray(imgs)) {
  93194. for (var index = 0; index < imgs.length; index++) {
  93195. var data_1 = imgs[index];
  93196. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  93197. texture.width = info.width;
  93198. texture.height = info.height;
  93199. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93200. engine._unpackFlipY(info.isCompressed);
  93201. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  93202. if (!info.isFourCC && info.mipmapCount === 1) {
  93203. engine.generateMipMapsForCubemap(texture);
  93204. }
  93205. }
  93206. }
  93207. else {
  93208. var data = imgs;
  93209. info = BABYLON.DDSTools.GetDDSInfo(data);
  93210. texture.width = info.width;
  93211. texture.height = info.height;
  93212. if (createPolynomials) {
  93213. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  93214. }
  93215. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  93216. engine._unpackFlipY(info.isCompressed);
  93217. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  93218. if (!info.isFourCC && info.mipmapCount === 1) {
  93219. engine.generateMipMapsForCubemap(texture);
  93220. }
  93221. }
  93222. engine._setCubeMapTextureParams(loadMipmap);
  93223. texture.isReady = true;
  93224. if (onLoad) {
  93225. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  93226. }
  93227. };
  93228. /**
  93229. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93230. * @param data contains the texture data
  93231. * @param texture defines the BabylonJS internal texture
  93232. * @param callback defines the method to call once ready to upload
  93233. */
  93234. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  93235. var info = BABYLON.DDSTools.GetDDSInfo(data);
  93236. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  93237. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  93238. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  93239. });
  93240. };
  93241. return DDSTextureLoader;
  93242. }());
  93243. // Register the loader.
  93244. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  93245. })(BABYLON || (BABYLON = {}));
  93246. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  93247. var BABYLON;
  93248. (function (BABYLON) {
  93249. /*
  93250. * Based on jsTGALoader - Javascript loader for TGA file
  93251. * By Vincent Thibault
  93252. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  93253. */
  93254. var TGATools = /** @class */ (function () {
  93255. function TGATools() {
  93256. }
  93257. TGATools.GetTGAHeader = function (data) {
  93258. var offset = 0;
  93259. var header = {
  93260. id_length: data[offset++],
  93261. colormap_type: data[offset++],
  93262. image_type: data[offset++],
  93263. colormap_index: data[offset++] | data[offset++] << 8,
  93264. colormap_length: data[offset++] | data[offset++] << 8,
  93265. colormap_size: data[offset++],
  93266. origin: [
  93267. data[offset++] | data[offset++] << 8,
  93268. data[offset++] | data[offset++] << 8
  93269. ],
  93270. width: data[offset++] | data[offset++] << 8,
  93271. height: data[offset++] | data[offset++] << 8,
  93272. pixel_size: data[offset++],
  93273. flags: data[offset++]
  93274. };
  93275. return header;
  93276. };
  93277. /**
  93278. * Uploads TGA content to a Babylon Texture
  93279. * @hidden
  93280. */
  93281. TGATools.UploadContent = function (texture, data) {
  93282. // Not enough data to contain header ?
  93283. if (data.length < 19) {
  93284. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  93285. return;
  93286. }
  93287. // Read Header
  93288. var offset = 18;
  93289. var header = TGATools.GetTGAHeader(data);
  93290. // Assume it's a valid Targa file.
  93291. if (header.id_length + offset > data.length) {
  93292. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  93293. return;
  93294. }
  93295. // Skip not needed data
  93296. offset += header.id_length;
  93297. var use_rle = false;
  93298. var use_pal = false;
  93299. var use_grey = false;
  93300. // Get some informations.
  93301. switch (header.image_type) {
  93302. case TGATools._TYPE_RLE_INDEXED:
  93303. use_rle = true;
  93304. case TGATools._TYPE_INDEXED:
  93305. use_pal = true;
  93306. break;
  93307. case TGATools._TYPE_RLE_RGB:
  93308. use_rle = true;
  93309. case TGATools._TYPE_RGB:
  93310. // use_rgb = true;
  93311. break;
  93312. case TGATools._TYPE_RLE_GREY:
  93313. use_rle = true;
  93314. case TGATools._TYPE_GREY:
  93315. use_grey = true;
  93316. break;
  93317. }
  93318. var pixel_data;
  93319. // var numAlphaBits = header.flags & 0xf;
  93320. var pixel_size = header.pixel_size >> 3;
  93321. var pixel_total = header.width * header.height * pixel_size;
  93322. // Read palettes
  93323. var palettes;
  93324. if (use_pal) {
  93325. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  93326. }
  93327. // Read LRE
  93328. if (use_rle) {
  93329. pixel_data = new Uint8Array(pixel_total);
  93330. var c, count, i;
  93331. var localOffset = 0;
  93332. var pixels = new Uint8Array(pixel_size);
  93333. while (offset < pixel_total && localOffset < pixel_total) {
  93334. c = data[offset++];
  93335. count = (c & 0x7f) + 1;
  93336. // RLE pixels
  93337. if (c & 0x80) {
  93338. // Bind pixel tmp array
  93339. for (i = 0; i < pixel_size; ++i) {
  93340. pixels[i] = data[offset++];
  93341. }
  93342. // Copy pixel array
  93343. for (i = 0; i < count; ++i) {
  93344. pixel_data.set(pixels, localOffset + i * pixel_size);
  93345. }
  93346. localOffset += pixel_size * count;
  93347. }
  93348. // Raw pixels
  93349. else {
  93350. count *= pixel_size;
  93351. for (i = 0; i < count; ++i) {
  93352. pixel_data[localOffset + i] = data[offset++];
  93353. }
  93354. localOffset += count;
  93355. }
  93356. }
  93357. }
  93358. // RAW Pixels
  93359. else {
  93360. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  93361. }
  93362. // Load to texture
  93363. var x_start, y_start, x_step, y_step, y_end, x_end;
  93364. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  93365. default:
  93366. case TGATools._ORIGIN_UL:
  93367. x_start = 0;
  93368. x_step = 1;
  93369. x_end = header.width;
  93370. y_start = 0;
  93371. y_step = 1;
  93372. y_end = header.height;
  93373. break;
  93374. case TGATools._ORIGIN_BL:
  93375. x_start = 0;
  93376. x_step = 1;
  93377. x_end = header.width;
  93378. y_start = header.height - 1;
  93379. y_step = -1;
  93380. y_end = -1;
  93381. break;
  93382. case TGATools._ORIGIN_UR:
  93383. x_start = header.width - 1;
  93384. x_step = -1;
  93385. x_end = -1;
  93386. y_start = 0;
  93387. y_step = 1;
  93388. y_end = header.height;
  93389. break;
  93390. case TGATools._ORIGIN_BR:
  93391. x_start = header.width - 1;
  93392. x_step = -1;
  93393. x_end = -1;
  93394. y_start = header.height - 1;
  93395. y_step = -1;
  93396. y_end = -1;
  93397. break;
  93398. }
  93399. // Load the specify method
  93400. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  93401. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  93402. var engine = texture.getEngine();
  93403. engine._uploadDataToTextureDirectly(texture, imageData);
  93404. };
  93405. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93406. var image = pixel_data, colormap = palettes;
  93407. var width = header.width, height = header.height;
  93408. var color, i = 0, x, y;
  93409. var imageData = new Uint8Array(width * height * 4);
  93410. for (y = y_start; y !== y_end; y += y_step) {
  93411. for (x = x_start; x !== x_end; x += x_step, i++) {
  93412. color = image[i];
  93413. imageData[(x + width * y) * 4 + 3] = 255;
  93414. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  93415. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  93416. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  93417. }
  93418. }
  93419. return imageData;
  93420. };
  93421. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93422. var image = pixel_data;
  93423. var width = header.width, height = header.height;
  93424. var color, i = 0, x, y;
  93425. var imageData = new Uint8Array(width * height * 4);
  93426. for (y = y_start; y !== y_end; y += y_step) {
  93427. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93428. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  93429. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  93430. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  93431. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  93432. imageData[(x + width * y) * 4 + 0] = r;
  93433. imageData[(x + width * y) * 4 + 1] = g;
  93434. imageData[(x + width * y) * 4 + 2] = b;
  93435. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  93436. }
  93437. }
  93438. return imageData;
  93439. };
  93440. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93441. var image = pixel_data;
  93442. var width = header.width, height = header.height;
  93443. var i = 0, x, y;
  93444. var imageData = new Uint8Array(width * height * 4);
  93445. for (y = y_start; y !== y_end; y += y_step) {
  93446. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  93447. imageData[(x + width * y) * 4 + 3] = 255;
  93448. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93449. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93450. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93451. }
  93452. }
  93453. return imageData;
  93454. };
  93455. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93456. var image = pixel_data;
  93457. var width = header.width, height = header.height;
  93458. var i = 0, x, y;
  93459. var imageData = new Uint8Array(width * height * 4);
  93460. for (y = y_start; y !== y_end; y += y_step) {
  93461. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  93462. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93463. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  93464. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  93465. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  93466. }
  93467. }
  93468. return imageData;
  93469. };
  93470. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93471. var image = pixel_data;
  93472. var width = header.width, height = header.height;
  93473. var color, i = 0, x, y;
  93474. var imageData = new Uint8Array(width * height * 4);
  93475. for (y = y_start; y !== y_end; y += y_step) {
  93476. for (x = x_start; x !== x_end; x += x_step, i++) {
  93477. color = image[i];
  93478. imageData[(x + width * y) * 4 + 0] = color;
  93479. imageData[(x + width * y) * 4 + 1] = color;
  93480. imageData[(x + width * y) * 4 + 2] = color;
  93481. imageData[(x + width * y) * 4 + 3] = 255;
  93482. }
  93483. }
  93484. return imageData;
  93485. };
  93486. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  93487. var image = pixel_data;
  93488. var width = header.width, height = header.height;
  93489. var i = 0, x, y;
  93490. var imageData = new Uint8Array(width * height * 4);
  93491. for (y = y_start; y !== y_end; y += y_step) {
  93492. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  93493. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  93494. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  93495. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  93496. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  93497. }
  93498. }
  93499. return imageData;
  93500. };
  93501. //private static _TYPE_NO_DATA = 0;
  93502. TGATools._TYPE_INDEXED = 1;
  93503. TGATools._TYPE_RGB = 2;
  93504. TGATools._TYPE_GREY = 3;
  93505. TGATools._TYPE_RLE_INDEXED = 9;
  93506. TGATools._TYPE_RLE_RGB = 10;
  93507. TGATools._TYPE_RLE_GREY = 11;
  93508. TGATools._ORIGIN_MASK = 0x30;
  93509. TGATools._ORIGIN_SHIFT = 0x04;
  93510. TGATools._ORIGIN_BL = 0x00;
  93511. TGATools._ORIGIN_BR = 0x01;
  93512. TGATools._ORIGIN_UL = 0x02;
  93513. TGATools._ORIGIN_UR = 0x03;
  93514. return TGATools;
  93515. }());
  93516. BABYLON.TGATools = TGATools;
  93517. })(BABYLON || (BABYLON = {}));
  93518. //# sourceMappingURL=babylon.tga.js.map
  93519. var BABYLON;
  93520. (function (BABYLON) {
  93521. /**
  93522. * Implementation of the TGA Texture Loader.
  93523. */
  93524. var TGATextureLoader = /** @class */ (function () {
  93525. function TGATextureLoader() {
  93526. /**
  93527. * Defines wether the loader supports cascade loading the different faces.
  93528. */
  93529. this.supportCascades = false;
  93530. }
  93531. /**
  93532. * This returns if the loader support the current file information.
  93533. * @param extension defines the file extension of the file being loaded
  93534. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93535. * @param fallback defines the fallback internal texture if any
  93536. * @param isBase64 defines whether the texture is encoded as a base64
  93537. * @param isBuffer defines whether the texture data are stored as a buffer
  93538. * @returns true if the loader can load the specified file
  93539. */
  93540. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93541. return extension.indexOf(".tga") === 0;
  93542. };
  93543. /**
  93544. * Transform the url before loading if required.
  93545. * @param rootUrl the url of the texture
  93546. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93547. * @returns the transformed texture
  93548. */
  93549. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93550. return rootUrl;
  93551. };
  93552. /**
  93553. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93554. * @param rootUrl the url of the texture
  93555. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93556. * @returns the fallback texture
  93557. */
  93558. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93559. return null;
  93560. };
  93561. /**
  93562. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93563. * @param data contains the texture data
  93564. * @param texture defines the BabylonJS internal texture
  93565. * @param createPolynomials will be true if polynomials have been requested
  93566. * @param onLoad defines the callback to trigger once the texture is ready
  93567. * @param onError defines the callback to trigger in case of error
  93568. */
  93569. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93570. throw ".env not supported in Cube.";
  93571. };
  93572. /**
  93573. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93574. * @param data contains the texture data
  93575. * @param texture defines the BabylonJS internal texture
  93576. * @param callback defines the method to call once ready to upload
  93577. */
  93578. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  93579. var uintData = new Uint8Array(data);
  93580. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  93581. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  93582. BABYLON.TGATools.UploadContent(texture, uintData);
  93583. });
  93584. };
  93585. return TGATextureLoader;
  93586. }());
  93587. // Register the loader.
  93588. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  93589. })(BABYLON || (BABYLON = {}));
  93590. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  93591. var BABYLON;
  93592. (function (BABYLON) {
  93593. /**
  93594. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  93595. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  93596. */
  93597. var KhronosTextureContainer = /** @class */ (function () {
  93598. /**
  93599. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  93600. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  93601. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  93602. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  93603. */
  93604. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  93605. this.arrayBuffer = arrayBuffer;
  93606. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  93607. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  93608. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  93609. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  93610. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  93611. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  93612. BABYLON.Tools.Error("texture missing KTX identifier");
  93613. return;
  93614. }
  93615. // load the reset of the header in native 32 bit int
  93616. var header = new Int32Array(this.arrayBuffer, 12, 13);
  93617. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  93618. var oppositeEndianess = header[0] === 0x01020304;
  93619. // read all the header elements in order they exist in the file, without modification (sans endainness)
  93620. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  93621. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  93622. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  93623. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  93624. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  93625. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  93626. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  93627. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  93628. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  93629. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  93630. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  93631. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  93632. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  93633. if (this.glType !== 0) {
  93634. BABYLON.Tools.Error("only compressed formats currently supported");
  93635. return;
  93636. }
  93637. else {
  93638. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  93639. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  93640. }
  93641. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  93642. BABYLON.Tools.Error("only 2D textures currently supported");
  93643. return;
  93644. }
  93645. if (this.numberOfArrayElements !== 0) {
  93646. BABYLON.Tools.Error("texture arrays not currently supported");
  93647. return;
  93648. }
  93649. if (this.numberOfFaces !== facesExpected) {
  93650. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  93651. return;
  93652. }
  93653. // we now have a completely validated file, so could use existence of loadType as success
  93654. // would need to make this more elaborate & adjust checks above to support more than one load type
  93655. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  93656. }
  93657. // not as fast hardware based, but will probably never need to use
  93658. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  93659. return ((val & 0xFF) << 24)
  93660. | ((val & 0xFF00) << 8)
  93661. | ((val >> 8) & 0xFF00)
  93662. | ((val >> 24) & 0xFF);
  93663. };
  93664. /**
  93665. * Uploads KTX content to a Babylon Texture.
  93666. * It is assumed that the texture has already been created & is currently bound
  93667. * @hidden
  93668. */
  93669. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  93670. switch (this.loadType) {
  93671. case KhronosTextureContainer.COMPRESSED_2D:
  93672. this._upload2DCompressedLevels(texture, loadMipmaps);
  93673. break;
  93674. case KhronosTextureContainer.TEX_2D:
  93675. case KhronosTextureContainer.COMPRESSED_3D:
  93676. case KhronosTextureContainer.TEX_3D:
  93677. }
  93678. };
  93679. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  93680. // initialize width & height for level 1
  93681. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  93682. var width = this.pixelWidth;
  93683. var height = this.pixelHeight;
  93684. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  93685. for (var level = 0; level < mipmapCount; level++) {
  93686. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  93687. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  93688. for (var face = 0; face < this.numberOfFaces; face++) {
  93689. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  93690. var engine = texture.getEngine();
  93691. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  93692. dataOffset += imageSize; // add size of the image for the next face/mipmap
  93693. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  93694. }
  93695. width = Math.max(1.0, width * 0.5);
  93696. height = Math.max(1.0, height * 0.5);
  93697. }
  93698. };
  93699. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  93700. // load types
  93701. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  93702. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  93703. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  93704. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  93705. return KhronosTextureContainer;
  93706. }());
  93707. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  93708. })(BABYLON || (BABYLON = {}));
  93709. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  93710. var BABYLON;
  93711. (function (BABYLON) {
  93712. /**
  93713. * Implementation of the KTX Texture Loader.
  93714. */
  93715. var KTXTextureLoader = /** @class */ (function () {
  93716. function KTXTextureLoader() {
  93717. /**
  93718. * Defines wether the loader supports cascade loading the different faces.
  93719. */
  93720. this.supportCascades = false;
  93721. }
  93722. /**
  93723. * This returns if the loader support the current file information.
  93724. * @param extension defines the file extension of the file being loaded
  93725. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93726. * @param fallback defines the fallback internal texture if any
  93727. * @param isBase64 defines whether the texture is encoded as a base64
  93728. * @param isBuffer defines whether the texture data are stored as a buffer
  93729. * @returns true if the loader can load the specified file
  93730. */
  93731. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  93732. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  93733. return true;
  93734. }
  93735. return false;
  93736. };
  93737. /**
  93738. * Transform the url before loading if required.
  93739. * @param rootUrl the url of the texture
  93740. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93741. * @returns the transformed texture
  93742. */
  93743. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  93744. var lastDot = rootUrl.lastIndexOf('.');
  93745. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  93746. };
  93747. /**
  93748. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  93749. * @param rootUrl the url of the texture
  93750. * @param textureFormatInUse defines the current compressed format in use iun the engine
  93751. * @returns the fallback texture
  93752. */
  93753. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  93754. // remove the format appended to the rootUrl in the original createCubeTexture call.
  93755. var exp = new RegExp("" + textureFormatInUse + "$");
  93756. return rootUrl.replace(exp, "");
  93757. };
  93758. /**
  93759. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  93760. * @param data contains the texture data
  93761. * @param texture defines the BabylonJS internal texture
  93762. * @param createPolynomials will be true if polynomials have been requested
  93763. * @param onLoad defines the callback to trigger once the texture is ready
  93764. * @param onError defines the callback to trigger in case of error
  93765. */
  93766. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  93767. if (Array.isArray(data)) {
  93768. return;
  93769. }
  93770. var engine = texture.getEngine();
  93771. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  93772. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  93773. engine._unpackFlipY(true);
  93774. ktx.uploadLevels(texture, texture.generateMipMaps);
  93775. texture.width = ktx.pixelWidth;
  93776. texture.height = ktx.pixelHeight;
  93777. engine._setCubeMapTextureParams(loadMipmap);
  93778. texture.isReady = true;
  93779. };
  93780. /**
  93781. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  93782. * @param data contains the texture data
  93783. * @param texture defines the BabylonJS internal texture
  93784. * @param callback defines the method to call once ready to upload
  93785. */
  93786. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  93787. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  93788. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  93789. ktx.uploadLevels(texture, texture.generateMipMaps);
  93790. });
  93791. };
  93792. return KTXTextureLoader;
  93793. }());
  93794. // Register the loader.
  93795. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  93796. })(BABYLON || (BABYLON = {}));
  93797. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  93798. var BABYLON;
  93799. (function (BABYLON) {
  93800. /**
  93801. * Sets of helpers addressing the serialization and deserialization of environment texture
  93802. * stored in a BabylonJS env file.
  93803. * Those files are usually stored as .env files.
  93804. */
  93805. var EnvironmentTextureTools = /** @class */ (function () {
  93806. function EnvironmentTextureTools() {
  93807. }
  93808. /**
  93809. * Gets the environment info from an env file.
  93810. * @param data The array buffer containing the .env bytes.
  93811. * @returns the environment file info (the json header) if successfully parsed.
  93812. */
  93813. EnvironmentTextureTools.GetEnvInfo = function (data) {
  93814. var dataView = new DataView(data);
  93815. var pos = 0;
  93816. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  93817. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  93818. BABYLON.Tools.Error('Not a babylon environment map');
  93819. return null;
  93820. }
  93821. }
  93822. // Read json manifest - collect characters up to null terminator
  93823. var manifestString = '';
  93824. var charCode = 0x00;
  93825. while ((charCode = dataView.getUint8(pos++))) {
  93826. manifestString += String.fromCharCode(charCode);
  93827. }
  93828. var manifest = JSON.parse(manifestString);
  93829. if (manifest.specular) {
  93830. // Extend the header with the position of the payload.
  93831. manifest.specular.specularDataPosition = pos;
  93832. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  93833. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  93834. }
  93835. return manifest;
  93836. };
  93837. /**
  93838. * Creates an environment texture from a loaded cube texture.
  93839. * @param texture defines the cube texture to convert in env file
  93840. * @return a promise containing the environment data if succesfull.
  93841. */
  93842. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  93843. var _this = this;
  93844. var internalTexture = texture.getInternalTexture();
  93845. if (!internalTexture) {
  93846. return Promise.reject("The cube texture is invalid.");
  93847. }
  93848. if (!texture._prefiltered) {
  93849. return Promise.reject("The cube texture is invalid (not prefiltered).");
  93850. }
  93851. var engine = internalTexture.getEngine();
  93852. if (engine && engine.premultipliedAlpha) {
  93853. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  93854. }
  93855. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  93856. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  93857. }
  93858. var canvas = engine.getRenderingCanvas();
  93859. if (!canvas) {
  93860. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  93861. }
  93862. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  93863. if (!engine.getCaps().textureFloatRender) {
  93864. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  93865. if (!engine.getCaps().textureHalfFloatRender) {
  93866. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  93867. }
  93868. }
  93869. var cubeWidth = internalTexture.width;
  93870. var hostingScene = new BABYLON.Scene(engine);
  93871. var specularTextures = {};
  93872. var promises = [];
  93873. // Read and collect all mipmaps data from the cube.
  93874. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  93875. mipmapsCount = Math.round(mipmapsCount);
  93876. var _loop_1 = function (i) {
  93877. var faceWidth = Math.pow(2, mipmapsCount - i);
  93878. var _loop_2 = function (face) {
  93879. var data = texture.readPixels(face, i);
  93880. // Creates a temp texture with the face data.
  93881. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  93882. // And rgbdEncode them.
  93883. var promise = new Promise(function (resolve, reject) {
  93884. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  93885. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  93886. rgbdPostProcess.onApply = function (effect) {
  93887. effect._bindTexture("textureSampler", tempTexture);
  93888. };
  93889. // As the process needs to happen on the main canvas, keep track of the current size
  93890. var currentW = engine.getRenderWidth();
  93891. var currentH = engine.getRenderHeight();
  93892. // Set the desired size for the texture
  93893. engine.setSize(faceWidth, faceWidth);
  93894. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  93895. // Reading datas from WebGL
  93896. BABYLON.Tools.ToBlob(canvas, function (blob) {
  93897. var fileReader = new FileReader();
  93898. fileReader.onload = function (event) {
  93899. var arrayBuffer = event.target.result;
  93900. specularTextures[i * 6 + face] = arrayBuffer;
  93901. resolve();
  93902. };
  93903. fileReader.readAsArrayBuffer(blob);
  93904. });
  93905. // Reapply the previous canvas size
  93906. engine.setSize(currentW, currentH);
  93907. });
  93908. });
  93909. promises.push(promise);
  93910. };
  93911. // All faces of the cube.
  93912. for (var face = 0; face < 6; face++) {
  93913. _loop_2(face);
  93914. }
  93915. };
  93916. for (var i = 0; i <= mipmapsCount; i++) {
  93917. _loop_1(i);
  93918. }
  93919. // Once all the textures haves been collected as RGBD stored in PNGs
  93920. return Promise.all(promises).then(function () {
  93921. // We can delete the hosting scene keeping track of all the creation objects
  93922. hostingScene.dispose();
  93923. // Creates the json header for the env texture
  93924. var info = {
  93925. version: 1,
  93926. width: cubeWidth,
  93927. irradiance: _this._CreateEnvTextureIrradiance(texture),
  93928. specular: {
  93929. mipmaps: [],
  93930. lodGenerationScale: texture.lodGenerationScale
  93931. }
  93932. };
  93933. // Sets the specular image data information
  93934. var position = 0;
  93935. for (var i = 0; i <= mipmapsCount; i++) {
  93936. for (var face = 0; face < 6; face++) {
  93937. var byteLength = specularTextures[i * 6 + face].byteLength;
  93938. info.specular.mipmaps.push({
  93939. length: byteLength,
  93940. position: position
  93941. });
  93942. position += byteLength;
  93943. }
  93944. }
  93945. // Encode the JSON as an array buffer
  93946. var infoString = JSON.stringify(info);
  93947. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  93948. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  93949. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  93950. infoView[i] = infoString.charCodeAt(i);
  93951. }
  93952. // Ends up with a null terminator for easier parsing
  93953. infoView[infoString.length] = 0x00;
  93954. // Computes the final required size and creates the storage
  93955. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  93956. var finalBuffer = new ArrayBuffer(totalSize);
  93957. var finalBufferView = new Uint8Array(finalBuffer);
  93958. var dataView = new DataView(finalBuffer);
  93959. // Copy the magic bytes identifying the file in
  93960. var pos = 0;
  93961. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  93962. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  93963. }
  93964. // Add the json info
  93965. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  93966. pos += infoBuffer.byteLength;
  93967. // Finally inserts the texture data
  93968. for (var i = 0; i <= mipmapsCount; i++) {
  93969. for (var face = 0; face < 6; face++) {
  93970. var dataBuffer = specularTextures[i * 6 + face];
  93971. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  93972. pos += dataBuffer.byteLength;
  93973. }
  93974. }
  93975. // Voila
  93976. return finalBuffer;
  93977. });
  93978. };
  93979. /**
  93980. * Creates a JSON representation of the spherical data.
  93981. * @param texture defines the texture containing the polynomials
  93982. * @return the JSON representation of the spherical info
  93983. */
  93984. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  93985. var polynmials = texture.sphericalPolynomial;
  93986. if (polynmials == null) {
  93987. return null;
  93988. }
  93989. return {
  93990. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  93991. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  93992. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  93993. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  93994. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  93995. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  93996. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  93997. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  93998. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  93999. };
  94000. };
  94001. /**
  94002. * Uploads the texture info contained in the env file to the GPU.
  94003. * @param texture defines the internal texture to upload to
  94004. * @param arrayBuffer defines the buffer cotaining the data to load
  94005. * @param info defines the texture info retrieved through the GetEnvInfo method
  94006. * @returns a promise
  94007. */
  94008. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  94009. if (info.version !== 1) {
  94010. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  94011. }
  94012. var specularInfo = info.specular;
  94013. if (!specularInfo) {
  94014. // Nothing else parsed so far
  94015. return Promise.resolve();
  94016. }
  94017. // Double checks the enclosed info
  94018. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  94019. mipmapsCount = Math.round(mipmapsCount) + 1;
  94020. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  94021. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  94022. }
  94023. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  94024. var imageData = new Array(mipmapsCount);
  94025. for (var i = 0; i < mipmapsCount; i++) {
  94026. imageData[i] = new Array(6);
  94027. for (var face = 0; face < 6; face++) {
  94028. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  94029. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  94030. }
  94031. }
  94032. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  94033. };
  94034. /**
  94035. * Uploads the levels of image data to the GPU.
  94036. * @param texture defines the internal texture to upload to
  94037. * @param imageData defines the array buffer views of image data [mipmap][face]
  94038. * @returns a promise
  94039. */
  94040. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  94041. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  94042. throw new Error("Texture size must be a power of two");
  94043. }
  94044. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  94045. // Gets everything ready.
  94046. var engine = texture.getEngine();
  94047. var expandTexture = false;
  94048. var generateNonLODTextures = false;
  94049. var rgbdPostProcess = null;
  94050. var cubeRtt = null;
  94051. var lodTextures = null;
  94052. var caps = engine.getCaps();
  94053. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  94054. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94055. texture.generateMipMaps = true;
  94056. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  94057. // Add extra process if texture lod is not supported
  94058. if (!caps.textureLOD) {
  94059. expandTexture = false;
  94060. generateNonLODTextures = true;
  94061. lodTextures = {};
  94062. }
  94063. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  94064. else if (engine.webGLVersion < 2) {
  94065. expandTexture = false;
  94066. }
  94067. // If half float available we can uncompress the texture
  94068. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  94069. expandTexture = true;
  94070. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  94071. }
  94072. // If full float available we can uncompress the texture
  94073. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  94074. expandTexture = true;
  94075. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  94076. }
  94077. // Expand the texture if possible
  94078. if (expandTexture) {
  94079. // Simply run through the decode PP
  94080. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  94081. texture._isRGBD = false;
  94082. texture.invertY = false;
  94083. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  94084. generateDepthBuffer: false,
  94085. generateMipMaps: true,
  94086. generateStencilBuffer: false,
  94087. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  94088. type: texture.type,
  94089. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  94090. });
  94091. }
  94092. else {
  94093. texture._isRGBD = true;
  94094. texture.invertY = true;
  94095. // In case of missing support, applies the same patch than DDS files.
  94096. if (generateNonLODTextures) {
  94097. var mipSlices = 3;
  94098. var scale = texture._lodGenerationScale;
  94099. var offset = texture._lodGenerationOffset;
  94100. for (var i = 0; i < mipSlices; i++) {
  94101. //compute LOD from even spacing in smoothness (matching shader calculation)
  94102. var smoothness = i / (mipSlices - 1);
  94103. var roughness = 1 - smoothness;
  94104. var minLODIndex = offset; // roughness = 0
  94105. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  94106. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  94107. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  94108. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  94109. glTextureFromLod.isCube = true;
  94110. glTextureFromLod.invertY = true;
  94111. glTextureFromLod.generateMipMaps = false;
  94112. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  94113. // Wrap in a base texture for easy binding.
  94114. var lodTexture = new BABYLON.BaseTexture(null);
  94115. lodTexture.isCube = true;
  94116. lodTexture._texture = glTextureFromLod;
  94117. lodTextures[mipmapIndex] = lodTexture;
  94118. switch (i) {
  94119. case 0:
  94120. texture._lodTextureLow = lodTexture;
  94121. break;
  94122. case 1:
  94123. texture._lodTextureMid = lodTexture;
  94124. break;
  94125. case 2:
  94126. texture._lodTextureHigh = lodTexture;
  94127. break;
  94128. }
  94129. }
  94130. }
  94131. }
  94132. var promises = [];
  94133. var _loop_3 = function (i) {
  94134. var _loop_4 = function (face) {
  94135. // Constructs an image element from image data
  94136. var bytes = imageData[i][face];
  94137. var blob = new Blob([bytes], { type: 'image/png' });
  94138. var url = URL.createObjectURL(blob);
  94139. var image = new Image();
  94140. image.src = url;
  94141. // Enqueue promise to upload to the texture.
  94142. var promise = new Promise(function (resolve, reject) {
  94143. image.onload = function () {
  94144. if (expandTexture) {
  94145. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  94146. reject(message);
  94147. }, image);
  94148. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  94149. // Uncompress the data to a RTT
  94150. rgbdPostProcess.onApply = function (effect) {
  94151. effect._bindTexture("textureSampler", tempTexture_1);
  94152. effect.setFloat2("scale", 1, 1);
  94153. };
  94154. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  94155. // Cleanup
  94156. engine.restoreDefaultFramebuffer();
  94157. tempTexture_1.dispose();
  94158. window.URL.revokeObjectURL(url);
  94159. resolve();
  94160. });
  94161. }
  94162. else {
  94163. engine._uploadImageToTexture(texture, image, face, i);
  94164. // Upload the face to the non lod texture support
  94165. if (generateNonLODTextures) {
  94166. var lodTexture = lodTextures[i];
  94167. if (lodTexture) {
  94168. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  94169. }
  94170. }
  94171. resolve();
  94172. }
  94173. };
  94174. image.onerror = function (error) {
  94175. reject(error);
  94176. };
  94177. });
  94178. promises.push(promise);
  94179. };
  94180. // All faces
  94181. for (var face = 0; face < 6; face++) {
  94182. _loop_4(face);
  94183. }
  94184. };
  94185. // All mipmaps up to provided number of images
  94186. for (var i = 0; i < imageData.length; i++) {
  94187. _loop_3(i);
  94188. }
  94189. // Fill remaining mipmaps with black textures.
  94190. if (imageData.length < mipmapsCount) {
  94191. var data = void 0;
  94192. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  94193. var dataLength = size * size * 4;
  94194. switch (texture.type) {
  94195. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  94196. data = new Uint8Array(dataLength);
  94197. break;
  94198. }
  94199. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  94200. data = new Uint16Array(dataLength);
  94201. break;
  94202. }
  94203. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  94204. data = new Float32Array(dataLength);
  94205. break;
  94206. }
  94207. }
  94208. for (var i = imageData.length; i < mipmapsCount; i++) {
  94209. for (var face = 0; face < 6; face++) {
  94210. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  94211. }
  94212. }
  94213. }
  94214. // Once all done, finishes the cleanup and return
  94215. return Promise.all(promises).then(function () {
  94216. // Release temp RTT.
  94217. if (cubeRtt) {
  94218. engine._releaseFramebufferObjects(cubeRtt);
  94219. cubeRtt._swapAndDie(texture);
  94220. }
  94221. // Release temp Post Process.
  94222. if (rgbdPostProcess) {
  94223. rgbdPostProcess.dispose();
  94224. }
  94225. // Flag internal texture as ready in case they are in use.
  94226. if (generateNonLODTextures) {
  94227. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  94228. texture._lodTextureHigh._texture.isReady = true;
  94229. }
  94230. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  94231. texture._lodTextureMid._texture.isReady = true;
  94232. }
  94233. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  94234. texture._lodTextureLow._texture.isReady = true;
  94235. }
  94236. }
  94237. });
  94238. };
  94239. /**
  94240. * Uploads spherical polynomials information to the texture.
  94241. * @param texture defines the texture we are trying to upload the information to
  94242. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  94243. */
  94244. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  94245. if (info.version !== 1) {
  94246. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  94247. }
  94248. var irradianceInfo = info.irradiance;
  94249. if (!irradianceInfo) {
  94250. return;
  94251. }
  94252. var sp = new BABYLON.SphericalPolynomial();
  94253. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  94254. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  94255. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  94256. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  94257. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  94258. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  94259. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  94260. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  94261. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  94262. texture._sphericalPolynomial = sp;
  94263. };
  94264. /**
  94265. * Magic number identifying the env file.
  94266. */
  94267. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  94268. return EnvironmentTextureTools;
  94269. }());
  94270. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  94271. })(BABYLON || (BABYLON = {}));
  94272. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  94273. var BABYLON;
  94274. (function (BABYLON) {
  94275. /**
  94276. * Implementation of the ENV Texture Loader.
  94277. */
  94278. var ENVTextureLoader = /** @class */ (function () {
  94279. function ENVTextureLoader() {
  94280. /**
  94281. * Defines wether the loader supports cascade loading the different faces.
  94282. */
  94283. this.supportCascades = false;
  94284. }
  94285. /**
  94286. * This returns if the loader support the current file information.
  94287. * @param extension defines the file extension of the file being loaded
  94288. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94289. * @param fallback defines the fallback internal texture if any
  94290. * @param isBase64 defines whether the texture is encoded as a base64
  94291. * @param isBuffer defines whether the texture data are stored as a buffer
  94292. * @returns true if the loader can load the specified file
  94293. */
  94294. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  94295. return extension.indexOf(".env") === 0;
  94296. };
  94297. /**
  94298. * Transform the url before loading if required.
  94299. * @param rootUrl the url of the texture
  94300. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94301. * @returns the transformed texture
  94302. */
  94303. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  94304. return rootUrl;
  94305. };
  94306. /**
  94307. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  94308. * @param rootUrl the url of the texture
  94309. * @param textureFormatInUse defines the current compressed format in use iun the engine
  94310. * @returns the fallback texture
  94311. */
  94312. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  94313. return null;
  94314. };
  94315. /**
  94316. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  94317. * @param data contains the texture data
  94318. * @param texture defines the BabylonJS internal texture
  94319. * @param createPolynomials will be true if polynomials have been requested
  94320. * @param onLoad defines the callback to trigger once the texture is ready
  94321. * @param onError defines the callback to trigger in case of error
  94322. */
  94323. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  94324. if (Array.isArray(data)) {
  94325. return;
  94326. }
  94327. data = data;
  94328. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  94329. if (info) {
  94330. texture.width = info.width;
  94331. texture.height = info.width;
  94332. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  94333. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  94334. texture.isReady = true;
  94335. if (onLoad) {
  94336. onLoad();
  94337. }
  94338. });
  94339. }
  94340. else if (onError) {
  94341. onError("Can not parse the environment file", null);
  94342. }
  94343. };
  94344. /**
  94345. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  94346. * @param data contains the texture data
  94347. * @param texture defines the BabylonJS internal texture
  94348. * @param callback defines the method to call once ready to upload
  94349. */
  94350. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  94351. throw ".env not supported in 2d.";
  94352. };
  94353. return ENVTextureLoader;
  94354. }());
  94355. // Register the loader.
  94356. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  94357. })(BABYLON || (BABYLON = {}));
  94358. //# sourceMappingURL=babylon.envTextureLoader.js.map
  94359. var BABYLON;
  94360. (function (BABYLON) {
  94361. /**
  94362. * Renders a layer on top of an existing scene
  94363. */
  94364. var UtilityLayerRenderer = /** @class */ (function () {
  94365. /**
  94366. * Instantiates a UtilityLayerRenderer
  94367. * @param originalScene the original scene that will be rendered on top of
  94368. */
  94369. function UtilityLayerRenderer(
  94370. /** the original scene that will be rendered on top of */
  94371. originalScene) {
  94372. var _this = this;
  94373. this.originalScene = originalScene;
  94374. this._pointerCaptures = {};
  94375. this._lastPointerEvents = {};
  94376. /**
  94377. * If the utility layer should automatically be rendered on top of existing scene
  94378. */
  94379. this.shouldRender = true;
  94380. /**
  94381. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  94382. */
  94383. this.onlyCheckPointerDownEvents = true;
  94384. /**
  94385. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  94386. */
  94387. this.processAllEvents = false;
  94388. /**
  94389. * Observable raised when the pointer move from the utility layer scene to the main scene
  94390. */
  94391. this.onPointerOutObservable = new BABYLON.Observable();
  94392. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  94393. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  94394. this.utilityLayerScene._allowPostProcessClearColor = false;
  94395. originalScene.getEngine().scenes.pop();
  94396. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  94397. this.utilityLayerScene.detachControl();
  94398. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  94399. if (!_this.processAllEvents) {
  94400. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  94401. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  94402. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  94403. return;
  94404. }
  94405. }
  94406. var pointerEvent = (prePointerInfo.event);
  94407. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  94408. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94409. return;
  94410. }
  94411. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  94412. if (!prePointerInfo.ray && utilityScenePick) {
  94413. prePointerInfo.ray = utilityScenePick.ray;
  94414. }
  94415. // always fire the prepointer oversvable
  94416. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  94417. // allow every non pointer down event to flow to the utility layer
  94418. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  94419. if (!prePointerInfo.skipOnPointerObservable) {
  94420. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94421. }
  94422. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  94423. _this._pointerCaptures[pointerEvent.pointerId] = false;
  94424. }
  94425. return;
  94426. }
  94427. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  94428. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  94429. if (utilityScenePick && utilityScenePick.hit) {
  94430. if (!prePointerInfo.skipOnPointerObservable) {
  94431. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  94432. }
  94433. prePointerInfo.skipOnPointerObservable = true;
  94434. }
  94435. }
  94436. else {
  94437. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  94438. var pointerEvent_1 = (prePointerInfo.event);
  94439. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  94440. if (originalScenePick && utilityScenePick) {
  94441. // No pick in utility scene
  94442. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  94443. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94444. // We touched an utility mesh present in the main scene
  94445. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94446. prePointerInfo.skipOnPointerObservable = true;
  94447. }
  94448. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94449. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  94450. }
  94451. }
  94452. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  94453. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  94454. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  94455. // If a previous utility layer set this, do not unset this
  94456. if (!prePointerInfo.skipOnPointerObservable) {
  94457. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  94458. }
  94459. }
  94460. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  94461. // We have a pick in both scenes but main is closer than utility
  94462. // We touched an utility mesh present in the main scene
  94463. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  94464. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  94465. prePointerInfo.skipOnPointerObservable = true;
  94466. }
  94467. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  94468. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  94469. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  94470. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  94471. }
  94472. }
  94473. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  94474. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  94475. }
  94476. }
  94477. }
  94478. });
  94479. // Render directly on top of existing scene without clearing
  94480. this.utilityLayerScene.autoClear = false;
  94481. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  94482. if (_this.shouldRender) {
  94483. _this.render();
  94484. }
  94485. });
  94486. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  94487. _this.dispose();
  94488. });
  94489. this._updateCamera();
  94490. }
  94491. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  94492. /**
  94493. * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
  94494. */
  94495. get: function () {
  94496. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  94497. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94498. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94499. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94500. });
  94501. }
  94502. return UtilityLayerRenderer._DefaultUtilityLayer;
  94503. },
  94504. enumerable: true,
  94505. configurable: true
  94506. });
  94507. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  94508. /**
  94509. * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
  94510. */
  94511. get: function () {
  94512. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  94513. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  94514. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  94515. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  94516. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94517. });
  94518. }
  94519. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  94520. },
  94521. enumerable: true,
  94522. configurable: true
  94523. });
  94524. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  94525. if (!prePointerInfo.skipOnPointerObservable) {
  94526. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  94527. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  94528. }
  94529. };
  94530. /**
  94531. * Renders the utility layers scene on top of the original scene
  94532. */
  94533. UtilityLayerRenderer.prototype.render = function () {
  94534. this._updateCamera();
  94535. if (this.utilityLayerScene.activeCamera) {
  94536. // Set the camera's scene to utility layers scene
  94537. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  94538. var camera = this.utilityLayerScene.activeCamera;
  94539. camera._scene = this.utilityLayerScene;
  94540. if (camera.leftCamera) {
  94541. camera.leftCamera._scene = this.utilityLayerScene;
  94542. }
  94543. if (camera.rightCamera) {
  94544. camera.rightCamera._scene = this.utilityLayerScene;
  94545. }
  94546. this.utilityLayerScene.render(false);
  94547. // Reset camera's scene back to original
  94548. camera._scene = oldScene;
  94549. if (camera.leftCamera) {
  94550. camera.leftCamera._scene = oldScene;
  94551. }
  94552. if (camera.rightCamera) {
  94553. camera.rightCamera._scene = oldScene;
  94554. }
  94555. }
  94556. };
  94557. /**
  94558. * Disposes of the renderer
  94559. */
  94560. UtilityLayerRenderer.prototype.dispose = function () {
  94561. this.onPointerOutObservable.clear();
  94562. if (this._afterRenderObserver) {
  94563. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  94564. }
  94565. if (this._sceneDisposeObserver) {
  94566. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94567. }
  94568. if (this._originalPointerObserver) {
  94569. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  94570. }
  94571. this.utilityLayerScene.dispose();
  94572. };
  94573. UtilityLayerRenderer.prototype._updateCamera = function () {
  94574. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  94575. };
  94576. UtilityLayerRenderer._DefaultUtilityLayer = null;
  94577. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  94578. return UtilityLayerRenderer;
  94579. }());
  94580. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  94581. })(BABYLON || (BABYLON = {}));
  94582. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  94583. //# sourceMappingURL=babylon.behavior.js.map
  94584. var BABYLON;
  94585. (function (BABYLON) {
  94586. /**
  94587. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  94588. */
  94589. var PointerDragBehavior = /** @class */ (function () {
  94590. /**
  94591. * Creates a pointer drag behavior that can be attached to a mesh
  94592. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  94593. */
  94594. function PointerDragBehavior(options) {
  94595. /**
  94596. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  94597. */
  94598. this.maxDragAngle = 0;
  94599. /**
  94600. * @hidden
  94601. */
  94602. this._useAlternatePickedPointAboveMaxDragAngle = false;
  94603. /**
  94604. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  94605. */
  94606. this.currentDraggingPointerID = -1;
  94607. /**
  94608. * If the behavior is currently in a dragging state
  94609. */
  94610. this.dragging = false;
  94611. /**
  94612. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  94613. */
  94614. this.dragDeltaRatio = 0.2;
  94615. /**
  94616. * If the drag plane orientation should be updated during the dragging (Default: true)
  94617. */
  94618. this.updateDragPlane = true;
  94619. // Debug mode will display drag planes to help visualize behavior
  94620. this._debugMode = false;
  94621. this._moving = false;
  94622. /**
  94623. * Fires each time the attached mesh is dragged with the pointer
  94624. * * delta between last drag position and current drag position in world space
  94625. * * dragDistance along the drag axis
  94626. * * dragPlaneNormal normal of the current drag plane used during the drag
  94627. * * dragPlanePoint in world space where the drag intersects the drag plane
  94628. */
  94629. this.onDragObservable = new BABYLON.Observable();
  94630. /**
  94631. * Fires each time a drag begins (eg. mouse down on mesh)
  94632. */
  94633. this.onDragStartObservable = new BABYLON.Observable();
  94634. /**
  94635. * Fires each time a drag ends (eg. mouse release after drag)
  94636. */
  94637. this.onDragEndObservable = new BABYLON.Observable();
  94638. /**
  94639. * If the attached mesh should be moved when dragged
  94640. */
  94641. this.moveAttached = true;
  94642. /**
  94643. * If the drag behavior will react to drag events (Default: true)
  94644. */
  94645. this.enabled = true;
  94646. /**
  94647. * If camera controls should be detached during the drag
  94648. */
  94649. this.detachCameraControls = true;
  94650. /**
  94651. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  94652. */
  94653. this.useObjectOrienationForDragging = true;
  94654. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  94655. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  94656. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  94657. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  94658. this._attachedElement = null;
  94659. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  94660. this._lastPointerRay = {};
  94661. this._dragDelta = new BABYLON.Vector3();
  94662. // Variables to avoid instantiation in the below method
  94663. this._pointA = new BABYLON.Vector3(0, 0, 0);
  94664. this._pointB = new BABYLON.Vector3(0, 0, 0);
  94665. this._pointC = new BABYLON.Vector3(0, 0, 0);
  94666. this._lineA = new BABYLON.Vector3(0, 0, 0);
  94667. this._lineB = new BABYLON.Vector3(0, 0, 0);
  94668. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  94669. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  94670. this._options = options ? options : {};
  94671. var optionCount = 0;
  94672. if (this._options.dragAxis) {
  94673. optionCount++;
  94674. }
  94675. if (this._options.dragPlaneNormal) {
  94676. optionCount++;
  94677. }
  94678. if (optionCount > 1) {
  94679. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  94680. }
  94681. }
  94682. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  94683. /**
  94684. * The name of the behavior
  94685. */
  94686. get: function () {
  94687. return "PointerDrag";
  94688. },
  94689. enumerable: true,
  94690. configurable: true
  94691. });
  94692. /**
  94693. * Initializes the behavior
  94694. */
  94695. PointerDragBehavior.prototype.init = function () { };
  94696. /**
  94697. * Attaches the drag behavior the passed in mesh
  94698. * @param ownerNode The mesh that will be dragged around once attached
  94699. */
  94700. PointerDragBehavior.prototype.attach = function (ownerNode) {
  94701. var _this = this;
  94702. this._scene = ownerNode.getScene();
  94703. this._attachedNode = ownerNode;
  94704. // Initialize drag plane to not interfere with existing scene
  94705. if (!PointerDragBehavior._planeScene) {
  94706. if (this._debugMode) {
  94707. PointerDragBehavior._planeScene = this._scene;
  94708. }
  94709. else {
  94710. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  94711. PointerDragBehavior._planeScene.detachControl();
  94712. this._scene.getEngine().scenes.pop();
  94713. this._scene.onDisposeObservable.addOnce(function () {
  94714. PointerDragBehavior._planeScene.dispose();
  94715. PointerDragBehavior._planeScene = null;
  94716. });
  94717. }
  94718. }
  94719. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  94720. // State of the drag
  94721. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  94722. var pickPredicate = function (m) {
  94723. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  94724. };
  94725. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  94726. if (!_this.enabled) {
  94727. return;
  94728. }
  94729. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  94730. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  94731. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  94732. }
  94733. }
  94734. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  94735. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  94736. _this.releaseDrag();
  94737. }
  94738. }
  94739. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  94740. var pointerId = pointerInfo.event.pointerId;
  94741. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  94742. if (!_this._lastPointerRay[pointerId]) {
  94743. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  94744. }
  94745. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  94746. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  94747. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  94748. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  94749. _this._moveDrag(pointerInfo.pickInfo.ray);
  94750. }
  94751. }
  94752. }
  94753. });
  94754. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  94755. if (_this._moving && _this.moveAttached) {
  94756. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  94757. // Slowly move mesh to avoid jitter
  94758. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  94759. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  94760. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  94761. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  94762. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  94763. }
  94764. });
  94765. };
  94766. PointerDragBehavior.prototype.releaseDrag = function () {
  94767. this.dragging = false;
  94768. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  94769. this.currentDraggingPointerID = -1;
  94770. this._moving = false;
  94771. // Reattach camera controls
  94772. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  94773. this._scene.activeCamera.attachControl(this._attachedElement, true);
  94774. }
  94775. };
  94776. /**
  94777. * Simulates the start of a pointer drag event on the behavior
  94778. * @param pointerId pointerID of the pointer that should be simulated (Default: 1 for mouse pointer)
  94779. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  94780. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  94781. */
  94782. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  94783. if (pointerId === void 0) { pointerId = 1; }
  94784. this._startDrag(pointerId, fromRay, startPickedPoint);
  94785. if (this._lastPointerRay[pointerId]) {
  94786. // if there was a last pointer ray drag the object there
  94787. this._moveDrag(this._lastPointerRay[pointerId]);
  94788. }
  94789. };
  94790. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  94791. if (pointerId === void 0) { pointerId = 1; }
  94792. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  94793. return;
  94794. }
  94795. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  94796. // Create start ray from the camera to the object
  94797. if (fromRay) {
  94798. this._startDragRay.direction.copyFrom(fromRay.direction);
  94799. this._startDragRay.origin.copyFrom(fromRay.origin);
  94800. }
  94801. else {
  94802. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  94803. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  94804. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  94805. }
  94806. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  94807. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  94808. if (pickedPoint) {
  94809. this.dragging = true;
  94810. this.currentDraggingPointerID = pointerId;
  94811. this.lastDragPosition.copyFrom(pickedPoint);
  94812. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  94813. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  94814. // Detatch camera controls
  94815. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  94816. if (this._scene.activeCamera.inputs.attachedElement) {
  94817. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  94818. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  94819. }
  94820. else {
  94821. this._attachedElement = null;
  94822. }
  94823. }
  94824. }
  94825. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  94826. };
  94827. PointerDragBehavior.prototype._moveDrag = function (ray) {
  94828. this._moving = true;
  94829. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  94830. if (pickedPoint) {
  94831. if (this.updateDragPlane) {
  94832. this._updateDragPlanePosition(ray, pickedPoint);
  94833. }
  94834. var dragLength = 0;
  94835. // depending on the drag mode option drag accordingly
  94836. if (this._options.dragAxis) {
  94837. // Convert local drag axis to world
  94838. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  94839. // Project delta drag from the drag plane onto the drag axis
  94840. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  94841. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  94842. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  94843. }
  94844. else {
  94845. dragLength = this._dragDelta.length();
  94846. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  94847. }
  94848. this._targetPosition.addInPlace(this._dragDelta);
  94849. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  94850. this.lastDragPosition.copyFrom(pickedPoint);
  94851. }
  94852. };
  94853. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  94854. var _this = this;
  94855. if (!ray) {
  94856. return null;
  94857. }
  94858. // Calculate angle between plane normal and ray
  94859. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  94860. // Correct if ray is casted from oposite side
  94861. if (angle > Math.PI / 2) {
  94862. angle = Math.PI - angle;
  94863. }
  94864. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  94865. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  94866. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  94867. // Invert ray direction along the towards object axis
  94868. this._tmpVector.copyFrom(ray.direction);
  94869. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  94870. this._alternatePickedPoint.normalize();
  94871. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  94872. this._tmpVector.addInPlace(this._alternatePickedPoint);
  94873. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  94874. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  94875. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  94876. this._alternatePickedPoint.addInPlace(this._tmpVector);
  94877. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  94878. return this._alternatePickedPoint;
  94879. }
  94880. else {
  94881. return null;
  94882. }
  94883. }
  94884. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  94885. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  94886. return pickResult.pickedPoint;
  94887. }
  94888. else {
  94889. return null;
  94890. }
  94891. };
  94892. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  94893. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  94894. this._pointA.copyFrom(dragPlanePosition);
  94895. if (this._options.dragAxis) {
  94896. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  94897. // Calculate plane normal in direction of camera but perpendicular to drag axis
  94898. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  94899. ray.origin.subtractToRef(this._pointA, this._pointC);
  94900. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  94901. // Get perpendicular line from direction to camera and drag axis
  94902. this._pointB.subtractToRef(this._pointA, this._lineA);
  94903. this._pointC.subtractToRef(this._pointA, this._lineB);
  94904. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  94905. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  94906. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  94907. this._lookAt.normalize();
  94908. this._dragPlane.position.copyFrom(this._pointA);
  94909. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  94910. this._dragPlane.lookAt(this._lookAt);
  94911. }
  94912. else if (this._options.dragPlaneNormal) {
  94913. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  94914. this._dragPlane.position.copyFrom(this._pointA);
  94915. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  94916. this._dragPlane.lookAt(this._lookAt);
  94917. }
  94918. else {
  94919. this._dragPlane.position.copyFrom(this._pointA);
  94920. this._dragPlane.lookAt(ray.origin);
  94921. }
  94922. this._dragPlane.computeWorldMatrix(true);
  94923. };
  94924. /**
  94925. * Detaches the behavior from the mesh
  94926. */
  94927. PointerDragBehavior.prototype.detach = function () {
  94928. if (this._pointerObserver) {
  94929. this._scene.onPointerObservable.remove(this._pointerObserver);
  94930. }
  94931. if (this._beforeRenderObserver) {
  94932. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  94933. }
  94934. };
  94935. return PointerDragBehavior;
  94936. }());
  94937. BABYLON.PointerDragBehavior = PointerDragBehavior;
  94938. })(BABYLON || (BABYLON = {}));
  94939. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  94940. var BABYLON;
  94941. (function (BABYLON) {
  94942. /**
  94943. * A behavior that when attached to a mesh will allow the mesh to be scaled
  94944. */
  94945. var MultiPointerScaleBehavior = /** @class */ (function () {
  94946. function MultiPointerScaleBehavior() {
  94947. this._startDistance = 0;
  94948. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  94949. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  94950. this._sceneRenderObserver = null;
  94951. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  94952. this._dragBehaviorA.moveAttached = false;
  94953. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  94954. this._dragBehaviorB.moveAttached = false;
  94955. }
  94956. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  94957. /**
  94958. * The name of the behavior
  94959. */
  94960. get: function () {
  94961. return "MultiPointerScale";
  94962. },
  94963. enumerable: true,
  94964. configurable: true
  94965. });
  94966. /**
  94967. * Initializes the behavior
  94968. */
  94969. MultiPointerScaleBehavior.prototype.init = function () { };
  94970. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  94971. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  94972. };
  94973. /**
  94974. * Attaches the scale behavior the passed in mesh
  94975. * @param ownerNode The mesh that will be scaled around once attached
  94976. */
  94977. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  94978. var _this = this;
  94979. this._ownerNode = ownerNode;
  94980. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  94981. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  94982. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  94983. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  94984. _this._dragBehaviorA.releaseDrag();
  94985. }
  94986. else {
  94987. _this._initialScale.copyFrom(ownerNode.scaling);
  94988. _this._startDistance = _this._getCurrentDistance();
  94989. }
  94990. }
  94991. });
  94992. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  94993. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  94994. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  94995. _this._dragBehaviorB.releaseDrag();
  94996. }
  94997. else {
  94998. _this._initialScale.copyFrom(ownerNode.scaling);
  94999. _this._startDistance = _this._getCurrentDistance();
  95000. }
  95001. }
  95002. });
  95003. // Once both drag behaviors are active scale based on the distance between the two pointers
  95004. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95005. behavior.onDragObservable.add(function () {
  95006. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95007. var ratio = _this._getCurrentDistance() / _this._startDistance;
  95008. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  95009. }
  95010. });
  95011. });
  95012. ownerNode.addBehavior(this._dragBehaviorA);
  95013. ownerNode.addBehavior(this._dragBehaviorB);
  95014. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95015. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95016. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  95017. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  95018. if (change.length() > 0.01) {
  95019. ownerNode.scaling.addInPlace(change);
  95020. }
  95021. }
  95022. });
  95023. };
  95024. /**
  95025. * Detaches the behavior from the mesh
  95026. */
  95027. MultiPointerScaleBehavior.prototype.detach = function () {
  95028. var _this = this;
  95029. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95030. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  95031. behavior.onDragStartObservable.clear();
  95032. behavior.onDragObservable.clear();
  95033. _this._ownerNode.removeBehavior(behavior);
  95034. });
  95035. };
  95036. return MultiPointerScaleBehavior;
  95037. }());
  95038. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  95039. })(BABYLON || (BABYLON = {}));
  95040. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  95041. var BABYLON;
  95042. (function (BABYLON) {
  95043. /**
  95044. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  95045. */
  95046. var SixDofDragBehavior = /** @class */ (function () {
  95047. function SixDofDragBehavior() {
  95048. this._sceneRenderObserver = null;
  95049. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  95050. this._moving = false;
  95051. this._startingOrientation = new BABYLON.Quaternion();
  95052. /**
  95053. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
  95054. */
  95055. this.zDragFactor = 3;
  95056. /**
  95057. * If the behavior is currently in a dragging state
  95058. */
  95059. this.dragging = false;
  95060. /**
  95061. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  95062. */
  95063. this.dragDeltaRatio = 0.2;
  95064. /**
  95065. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  95066. */
  95067. this.currentDraggingPointerID = -1;
  95068. /**
  95069. * If camera controls should be detached during the drag
  95070. */
  95071. this.detachCameraControls = true;
  95072. /**
  95073. * Fires each time a drag starts
  95074. */
  95075. this.onDragStartObservable = new BABYLON.Observable();
  95076. /**
  95077. * Fires each time a drag ends (eg. mouse release after drag)
  95078. */
  95079. this.onDragEndObservable = new BABYLON.Observable();
  95080. }
  95081. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  95082. /**
  95083. * The name of the behavior
  95084. */
  95085. get: function () {
  95086. return "SixDofDrag";
  95087. },
  95088. enumerable: true,
  95089. configurable: true
  95090. });
  95091. /**
  95092. * Initializes the behavior
  95093. */
  95094. SixDofDragBehavior.prototype.init = function () { };
  95095. /**
  95096. * Attaches the scale behavior the passed in mesh
  95097. * @param ownerNode The mesh that will be scaled around once attached
  95098. */
  95099. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  95100. var _this = this;
  95101. this._ownerNode = ownerNode;
  95102. this._scene = this._ownerNode.getScene();
  95103. if (!SixDofDragBehavior._virtualScene) {
  95104. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  95105. this._scene.getEngine().scenes.pop();
  95106. }
  95107. var pickedMesh = null;
  95108. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  95109. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  95110. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95111. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  95112. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  95113. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  95114. var pickPredicate = function (m) {
  95115. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  95116. };
  95117. var attachedElement = null;
  95118. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  95119. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  95120. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  95121. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95122. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95123. }
  95124. pickedMesh = _this._ownerNode;
  95125. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95126. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95127. // Set position and orientation of the controller
  95128. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95129. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95130. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  95131. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95132. pickedMesh.computeWorldMatrix();
  95133. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  95134. if (!pickedMesh.rotationQuaternion) {
  95135. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  95136. }
  95137. var oldParent = pickedMesh.parent;
  95138. pickedMesh.setParent(null);
  95139. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  95140. pickedMesh.setParent(oldParent);
  95141. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95142. // Update state
  95143. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95144. _this.dragging = true;
  95145. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  95146. // Detatch camera controls
  95147. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95148. if (_this._scene.activeCamera.inputs.attachedElement) {
  95149. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  95150. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  95151. }
  95152. else {
  95153. attachedElement = null;
  95154. }
  95155. }
  95156. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95157. _this.onDragStartObservable.notifyObservers({});
  95158. }
  95159. }
  95160. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  95161. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  95162. _this.dragging = false;
  95163. _this._moving = false;
  95164. _this.currentDraggingPointerID = -1;
  95165. pickedMesh = null;
  95166. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95167. // Reattach camera controls
  95168. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  95169. _this._scene.activeCamera.attachControl(attachedElement, true);
  95170. }
  95171. _this.onDragEndObservable.notifyObservers({});
  95172. }
  95173. }
  95174. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  95175. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  95176. var zDragFactor = _this.zDragFactor;
  95177. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  95178. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  95179. zDragFactor = 0;
  95180. }
  95181. // Calculate controller drag distance in controller space
  95182. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  95183. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  95184. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  95185. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  95186. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  95187. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  95188. if (_this._virtualDragMesh.position.z < 0) {
  95189. _this._virtualDragMesh.position.z = 0;
  95190. }
  95191. // Update the controller position
  95192. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  95193. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  95194. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  95195. // Move the virtualObjectsPosition into the picked mesh's space if needed
  95196. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  95197. if (pickedMesh.parent) {
  95198. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  95199. }
  95200. if (!_this._moving) {
  95201. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  95202. }
  95203. _this._moving = true;
  95204. }
  95205. }
  95206. });
  95207. var tmpQuaternion = new BABYLON.Quaternion();
  95208. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  95209. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  95210. if (_this.dragging && _this._moving && pickedMesh) {
  95211. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  95212. // Slowly move mesh to avoid jitter
  95213. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  95214. // Get change in rotation
  95215. tmpQuaternion.copyFrom(_this._startingOrientation);
  95216. tmpQuaternion.x = -tmpQuaternion.x;
  95217. tmpQuaternion.y = -tmpQuaternion.y;
  95218. tmpQuaternion.z = -tmpQuaternion.z;
  95219. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  95220. // Convert change in rotation to only y axis rotation
  95221. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  95222. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  95223. // Slowly move mesh to avoid jitter
  95224. var oldParent = pickedMesh.parent;
  95225. pickedMesh.setParent(null);
  95226. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  95227. pickedMesh.setParent(oldParent);
  95228. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  95229. }
  95230. });
  95231. };
  95232. /**
  95233. * Detaches the behavior from the mesh
  95234. */
  95235. SixDofDragBehavior.prototype.detach = function () {
  95236. if (this._scene) {
  95237. this._scene.onPointerObservable.remove(this._pointerObserver);
  95238. }
  95239. if (this._ownerNode) {
  95240. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  95241. }
  95242. if (this._virtualOriginMesh) {
  95243. this._virtualOriginMesh.dispose();
  95244. }
  95245. if (this._virtualDragMesh) {
  95246. this._virtualDragMesh.dispose();
  95247. }
  95248. this.onDragEndObservable.clear();
  95249. this.onDragStartObservable.clear();
  95250. };
  95251. return SixDofDragBehavior;
  95252. }());
  95253. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  95254. })(BABYLON || (BABYLON = {}));
  95255. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  95256. var BABYLON;
  95257. (function (BABYLON) {
  95258. /**
  95259. * @hidden
  95260. */
  95261. var FaceDirectionInfo = /** @class */ (function () {
  95262. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  95263. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  95264. if (diff === void 0) { diff = 0; }
  95265. if (ignore === void 0) { ignore = false; }
  95266. this.direction = direction;
  95267. this.rotatedDirection = rotatedDirection;
  95268. this.diff = diff;
  95269. this.ignore = ignore;
  95270. }
  95271. return FaceDirectionInfo;
  95272. }());
  95273. /**
  95274. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  95275. */
  95276. var AttachToBoxBehavior = /** @class */ (function () {
  95277. /**
  95278. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  95279. * @param ui The transform node that should be attched to the mesh
  95280. */
  95281. function AttachToBoxBehavior(ui) {
  95282. this.ui = ui;
  95283. /**
  95284. * The name of the behavior
  95285. */
  95286. this.name = "AttachToBoxBehavior";
  95287. /**
  95288. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  95289. */
  95290. this.distanceAwayFromFace = 0.15;
  95291. /**
  95292. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  95293. */
  95294. this.distanceAwayFromBottomOfFace = 0.15;
  95295. this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
  95296. this._tmpMatrix = new BABYLON.Matrix();
  95297. this._tmpVector = new BABYLON.Vector3();
  95298. this._zeroVector = BABYLON.Vector3.Zero();
  95299. this._lookAtTmpMatrix = new BABYLON.Matrix();
  95300. /* Does nothing */
  95301. }
  95302. /**
  95303. * Initializes the behavior
  95304. */
  95305. AttachToBoxBehavior.prototype.init = function () {
  95306. /* Does nothing */
  95307. };
  95308. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  95309. var _this = this;
  95310. // Go over each face and calculate the angle between the face's normal and targetDirection
  95311. this._faceVectors.forEach(function (v) {
  95312. if (!_this._target.rotationQuaternion) {
  95313. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  95314. }
  95315. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  95316. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  95317. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  95318. });
  95319. // Return the face information of the one with the normal closeset to target direction
  95320. return this._faceVectors.reduce(function (min, p) {
  95321. if (min.ignore) {
  95322. return p;
  95323. }
  95324. else if (p.ignore) {
  95325. return min;
  95326. }
  95327. else {
  95328. return min.diff < p.diff ? min : p;
  95329. }
  95330. }, this._faceVectors[0]);
  95331. };
  95332. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  95333. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  95334. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  95335. this._lookAtTmpMatrix.invert();
  95336. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  95337. };
  95338. /**
  95339. * Attaches the AttachToBoxBehavior to the passed in mesh
  95340. * @param target The mesh that the specified node will be attached to
  95341. */
  95342. AttachToBoxBehavior.prototype.attach = function (target) {
  95343. var _this = this;
  95344. this._target = target;
  95345. this._scene = this._target.getScene();
  95346. // Every frame, update the app bars position
  95347. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  95348. if (!_this._scene.activeCamera) {
  95349. return;
  95350. }
  95351. // Find the face closest to the cameras position
  95352. var cameraPos = _this._scene.activeCamera.position;
  95353. if (_this._scene.activeCamera.devicePosition) {
  95354. cameraPos = _this._scene.activeCamera.devicePosition;
  95355. }
  95356. var facing = _this._closestFace(cameraPos.subtract(target.position));
  95357. if (_this._scene.activeCamera.leftCamera) {
  95358. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95359. }
  95360. else {
  95361. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  95362. }
  95363. // Get camera up direction
  95364. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  95365. // Ignore faces to not select a parrelel face for the up vector of the UI
  95366. _this._faceVectors.forEach(function (v) {
  95367. if (facing.direction.x && v.direction.x) {
  95368. v.ignore = true;
  95369. }
  95370. if (facing.direction.y && v.direction.y) {
  95371. v.ignore = true;
  95372. }
  95373. if (facing.direction.z && v.direction.z) {
  95374. v.ignore = true;
  95375. }
  95376. });
  95377. var facingUp = _this._closestFace(_this._tmpVector);
  95378. // Unignore faces
  95379. _this._faceVectors.forEach(function (v) {
  95380. v.ignore = false;
  95381. });
  95382. // Position the app bar on that face
  95383. _this.ui.position.copyFrom(target.position);
  95384. if (facing.direction.x) {
  95385. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95386. _this.ui.position.addInPlace(_this._tmpVector);
  95387. }
  95388. if (facing.direction.y) {
  95389. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95390. _this.ui.position.addInPlace(_this._tmpVector);
  95391. }
  95392. if (facing.direction.z) {
  95393. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  95394. _this.ui.position.addInPlace(_this._tmpVector);
  95395. }
  95396. // Rotate to be oriented properly to the camera
  95397. if (!_this.ui.rotationQuaternion) {
  95398. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  95399. }
  95400. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  95401. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  95402. // Place ui the correct distance from the bottom of the mesh
  95403. if (facingUp.direction.x) {
  95404. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  95405. }
  95406. if (facingUp.direction.y) {
  95407. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  95408. }
  95409. if (facingUp.direction.z) {
  95410. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  95411. }
  95412. _this.ui.position.addInPlace(_this._tmpVector);
  95413. });
  95414. };
  95415. /**
  95416. * Detaches the behavior from the mesh
  95417. */
  95418. AttachToBoxBehavior.prototype.detach = function () {
  95419. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  95420. };
  95421. return AttachToBoxBehavior;
  95422. }());
  95423. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  95424. })(BABYLON || (BABYLON = {}));
  95425. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  95426. var BABYLON;
  95427. (function (BABYLON) {
  95428. /**
  95429. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  95430. */
  95431. var FadeInOutBehavior = /** @class */ (function () {
  95432. /**
  95433. * Instatiates the FadeInOutBehavior
  95434. */
  95435. function FadeInOutBehavior() {
  95436. var _this = this;
  95437. /**
  95438. * Time in milliseconds to delay before fading in (Default: 0)
  95439. */
  95440. this.delay = 0;
  95441. /**
  95442. * Time in milliseconds for the mesh to fade in (Default: 300)
  95443. */
  95444. this.fadeInTime = 300;
  95445. this._millisecondsPerFrame = 1000 / 60;
  95446. this._hovered = false;
  95447. this._hoverValue = 0;
  95448. this._ownerNode = null;
  95449. this._update = function () {
  95450. if (_this._ownerNode) {
  95451. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  95452. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  95453. if (_this._ownerNode.visibility > 1) {
  95454. _this._setAllVisibility(_this._ownerNode, 1);
  95455. _this._hoverValue = _this.fadeInTime + _this.delay;
  95456. return;
  95457. }
  95458. else if (_this._ownerNode.visibility < 0) {
  95459. _this._setAllVisibility(_this._ownerNode, 0);
  95460. if (_this._hoverValue < 0) {
  95461. _this._hoverValue = 0;
  95462. return;
  95463. }
  95464. }
  95465. setTimeout(_this._update, _this._millisecondsPerFrame);
  95466. }
  95467. };
  95468. }
  95469. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  95470. /**
  95471. * The name of the behavior
  95472. */
  95473. get: function () {
  95474. return "FadeInOut";
  95475. },
  95476. enumerable: true,
  95477. configurable: true
  95478. });
  95479. /**
  95480. * Initializes the behavior
  95481. */
  95482. FadeInOutBehavior.prototype.init = function () {
  95483. };
  95484. /**
  95485. * Attaches the fade behavior on the passed in mesh
  95486. * @param ownerNode The mesh that will be faded in/out once attached
  95487. */
  95488. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  95489. this._ownerNode = ownerNode;
  95490. this._setAllVisibility(this._ownerNode, 0);
  95491. };
  95492. /**
  95493. * Detaches the behavior from the mesh
  95494. */
  95495. FadeInOutBehavior.prototype.detach = function () {
  95496. this._ownerNode = null;
  95497. };
  95498. /**
  95499. * Triggers the mesh to begin fading in or out
  95500. * @param value if the object should fade in or out (true to fade in)
  95501. */
  95502. FadeInOutBehavior.prototype.fadeIn = function (value) {
  95503. this._hovered = value;
  95504. this._update();
  95505. };
  95506. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  95507. var _this = this;
  95508. mesh.visibility = value;
  95509. mesh.getChildMeshes().forEach(function (c) {
  95510. _this._setAllVisibility(c, value);
  95511. });
  95512. };
  95513. return FadeInOutBehavior;
  95514. }());
  95515. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  95516. })(BABYLON || (BABYLON = {}));
  95517. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  95518. var BABYLON;
  95519. (function (BABYLON) {
  95520. /**
  95521. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  95522. */
  95523. var Gizmo = /** @class */ (function () {
  95524. /**
  95525. * Creates a gizmo
  95526. * @param gizmoLayer The utility layer the gizmo will be added to
  95527. */
  95528. function Gizmo(
  95529. /** The utility layer the gizmo will be added to */
  95530. gizmoLayer) {
  95531. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95532. var _this = this;
  95533. this.gizmoLayer = gizmoLayer;
  95534. /**
  95535. * Ratio for the scale of the gizmo (Default: 1)
  95536. */
  95537. this.scaleRatio = 1;
  95538. this._tmpMatrix = new BABYLON.Matrix();
  95539. /**
  95540. * If a custom mesh has been set (Default: false)
  95541. */
  95542. this._customMeshSet = false;
  95543. /**
  95544. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  95545. */
  95546. this.updateGizmoRotationToMatchAttachedMesh = true;
  95547. /**
  95548. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  95549. */
  95550. this.updateGizmoPositionToMatchAttachedMesh = true;
  95551. /**
  95552. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  95553. */
  95554. this._updateScale = true;
  95555. this._interactionsEnabled = true;
  95556. this._tempVector = new BABYLON.Vector3();
  95557. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  95558. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  95559. _this._update();
  95560. });
  95561. this.attachedMesh = null;
  95562. }
  95563. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  95564. /**
  95565. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  95566. * * When set, interactions will be enabled
  95567. */
  95568. get: function () {
  95569. return this._attachedMesh;
  95570. },
  95571. set: function (value) {
  95572. this._attachedMesh = value;
  95573. this._rootMesh.setEnabled(value ? true : false);
  95574. this._attachedMeshChanged(value);
  95575. },
  95576. enumerable: true,
  95577. configurable: true
  95578. });
  95579. /**
  95580. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  95581. * @param mesh The mesh to replace the default mesh of the gizmo
  95582. */
  95583. Gizmo.prototype.setCustomMesh = function (mesh) {
  95584. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  95585. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  95586. }
  95587. this._rootMesh.getChildMeshes().forEach(function (c) {
  95588. c.dispose();
  95589. });
  95590. mesh.parent = this._rootMesh;
  95591. this._customMeshSet = true;
  95592. };
  95593. Gizmo.prototype._attachedMeshChanged = function (value) {
  95594. };
  95595. /**
  95596. * @hidden
  95597. * Updates the gizmo to match the attached mesh's position/rotation
  95598. */
  95599. Gizmo.prototype._update = function () {
  95600. if (this.attachedMesh) {
  95601. if (this.updateGizmoRotationToMatchAttachedMesh) {
  95602. if (!this._rootMesh.rotationQuaternion) {
  95603. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  95604. }
  95605. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  95606. this._tempVector.copyFrom(this.attachedMesh.scaling);
  95607. if (this.attachedMesh.scaling.x < 0) {
  95608. this.attachedMesh.scaling.x *= -1;
  95609. }
  95610. if (this.attachedMesh.scaling.y < 0) {
  95611. this.attachedMesh.scaling.y *= -1;
  95612. }
  95613. if (this.attachedMesh.scaling.z < 0) {
  95614. this.attachedMesh.scaling.z *= -1;
  95615. }
  95616. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  95617. this.attachedMesh.scaling.copyFrom(this._tempVector);
  95618. this.attachedMesh.computeWorldMatrix();
  95619. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  95620. }
  95621. else if (this._rootMesh.rotationQuaternion) {
  95622. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  95623. }
  95624. if (this.updateGizmoPositionToMatchAttachedMesh) {
  95625. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  95626. }
  95627. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  95628. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  95629. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  95630. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  95631. }
  95632. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  95633. var dist = this._tempVector.length() * this.scaleRatio;
  95634. this._rootMesh.scaling.set(dist, dist, dist);
  95635. }
  95636. }
  95637. };
  95638. /**
  95639. * Disposes of the gizmo
  95640. */
  95641. Gizmo.prototype.dispose = function () {
  95642. this._rootMesh.dispose();
  95643. if (this._beforeRenderObserver) {
  95644. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  95645. }
  95646. };
  95647. return Gizmo;
  95648. }());
  95649. BABYLON.Gizmo = Gizmo;
  95650. })(BABYLON || (BABYLON = {}));
  95651. //# sourceMappingURL=babylon.gizmo.js.map
  95652. var BABYLON;
  95653. (function (BABYLON) {
  95654. /**
  95655. * Single axis drag gizmo
  95656. */
  95657. var AxisDragGizmo = /** @class */ (function (_super) {
  95658. __extends(AxisDragGizmo, _super);
  95659. /**
  95660. * Creates an AxisDragGizmo
  95661. * @param gizmoLayer The utility layer the gizmo will be added to
  95662. * @param dragAxis The axis which the gizmo will be able to drag on
  95663. * @param color The color of the gizmo
  95664. */
  95665. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  95666. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95667. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95668. var _this = _super.call(this, gizmoLayer) || this;
  95669. _this._pointerObserver = null;
  95670. /**
  95671. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95672. */
  95673. _this.snapDistance = 0;
  95674. /**
  95675. * Event that fires each time the gizmo snaps to a new location.
  95676. * * snapDistance is the the change in distance
  95677. */
  95678. _this.onSnapObservable = new BABYLON.Observable();
  95679. // Create Material
  95680. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95681. coloredMaterial.disableLighting = true;
  95682. coloredMaterial.emissiveColor = color;
  95683. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95684. hoverMaterial.disableLighting = true;
  95685. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95686. // Build mesh on root node
  95687. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95688. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  95689. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  95690. arrowTail.color = coloredMaterial.emissiveColor;
  95691. arrow.addChild(arrowMesh);
  95692. arrow.addChild(arrowTail);
  95693. // Position arrow pointing in its drag axis
  95694. arrowMesh.scaling.scaleInPlace(0.05);
  95695. arrowMesh.material = coloredMaterial;
  95696. arrowMesh.rotation.x = Math.PI / 2;
  95697. arrowMesh.position.z += 0.3;
  95698. arrowTail.scaling.scaleInPlace(0.26);
  95699. arrowTail.rotation.x = Math.PI / 2;
  95700. arrowTail.material = coloredMaterial;
  95701. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  95702. arrow.scaling.scaleInPlace(1 / 3);
  95703. _this._rootMesh.addChild(arrow);
  95704. var currentSnapDragDistance = 0;
  95705. var tmpVector = new BABYLON.Vector3();
  95706. var tmpSnapEvent = { snapDistance: 0 };
  95707. // Add drag behavior to handle events when the gizmo is dragged
  95708. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95709. _this.dragBehavior.moveAttached = false;
  95710. _this._rootMesh.addBehavior(_this.dragBehavior);
  95711. var localDelta = new BABYLON.Vector3();
  95712. var tmpMatrix = new BABYLON.Matrix();
  95713. _this.dragBehavior.onDragObservable.add(function (event) {
  95714. if (_this.attachedMesh) {
  95715. // Convert delta to local translation if it has a parent
  95716. if (_this.attachedMesh.parent) {
  95717. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  95718. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  95719. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  95720. }
  95721. else {
  95722. localDelta.copyFrom(event.delta);
  95723. }
  95724. // Snapping logic
  95725. if (_this.snapDistance == 0) {
  95726. _this.attachedMesh.position.addInPlace(localDelta);
  95727. }
  95728. else {
  95729. currentSnapDragDistance += event.dragDistance;
  95730. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  95731. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  95732. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  95733. localDelta.normalizeToRef(tmpVector);
  95734. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  95735. _this.attachedMesh.position.addInPlace(tmpVector);
  95736. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  95737. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  95738. }
  95739. }
  95740. }
  95741. });
  95742. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95743. if (_this._customMeshSet) {
  95744. return;
  95745. }
  95746. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  95747. var material = isHovered ? hoverMaterial : coloredMaterial;
  95748. _this._rootMesh.getChildMeshes().forEach(function (m) {
  95749. m.material = material;
  95750. if (m.color) {
  95751. m.color = material.emissiveColor;
  95752. }
  95753. });
  95754. });
  95755. return _this;
  95756. }
  95757. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  95758. if (this.dragBehavior) {
  95759. this.dragBehavior.enabled = value ? true : false;
  95760. }
  95761. };
  95762. /**
  95763. * Disposes of the gizmo
  95764. */
  95765. AxisDragGizmo.prototype.dispose = function () {
  95766. this.onSnapObservable.clear();
  95767. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95768. this.dragBehavior.detach();
  95769. _super.prototype.dispose.call(this);
  95770. };
  95771. return AxisDragGizmo;
  95772. }(BABYLON.Gizmo));
  95773. BABYLON.AxisDragGizmo = AxisDragGizmo;
  95774. })(BABYLON || (BABYLON = {}));
  95775. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  95776. var BABYLON;
  95777. (function (BABYLON) {
  95778. /**
  95779. * Single axis scale gizmo
  95780. */
  95781. var AxisScaleGizmo = /** @class */ (function (_super) {
  95782. __extends(AxisScaleGizmo, _super);
  95783. /**
  95784. * Creates an AxisScaleGizmo
  95785. * @param gizmoLayer The utility layer the gizmo will be added to
  95786. * @param dragAxis The axis which the gizmo will be able to scale on
  95787. * @param color The color of the gizmo
  95788. */
  95789. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  95790. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95791. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95792. var _this = _super.call(this, gizmoLayer) || this;
  95793. _this._pointerObserver = null;
  95794. /**
  95795. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  95796. */
  95797. _this.snapDistance = 0;
  95798. /**
  95799. * Event that fires each time the gizmo snaps to a new location.
  95800. * * snapDistance is the the change in distance
  95801. */
  95802. _this.onSnapObservable = new BABYLON.Observable();
  95803. /**
  95804. * If the scaling operation should be done on all axis (default: false)
  95805. */
  95806. _this.uniformScaling = false;
  95807. // Create Material
  95808. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95809. _this._coloredMaterial.disableLighting = true;
  95810. _this._coloredMaterial.emissiveColor = color;
  95811. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95812. hoverMaterial.disableLighting = true;
  95813. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95814. // Build mesh on root node
  95815. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95816. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  95817. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  95818. arrowTail.color = _this._coloredMaterial.emissiveColor;
  95819. arrow.addChild(arrowMesh);
  95820. arrow.addChild(arrowTail);
  95821. // Position arrow pointing in its drag axis
  95822. arrowMesh.scaling.scaleInPlace(0.1);
  95823. arrowMesh.material = _this._coloredMaterial;
  95824. arrowMesh.rotation.x = Math.PI / 2;
  95825. arrowMesh.position.z += 0.3;
  95826. arrowTail.scaling.scaleInPlace(0.26);
  95827. arrowTail.rotation.x = Math.PI / 2;
  95828. arrowTail.material = _this._coloredMaterial;
  95829. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  95830. _this._rootMesh.addChild(arrow);
  95831. arrow.scaling.scaleInPlace(1 / 3);
  95832. // Add drag behavior to handle events when the gizmo is dragged
  95833. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  95834. _this.dragBehavior.moveAttached = false;
  95835. _this._rootMesh.addBehavior(_this.dragBehavior);
  95836. var currentSnapDragDistance = 0;
  95837. var tmpVector = new BABYLON.Vector3();
  95838. var tmpSnapEvent = { snapDistance: 0 };
  95839. _this.dragBehavior.onDragObservable.add(function (event) {
  95840. if (_this.attachedMesh) {
  95841. // Snapping logic
  95842. var snapped = false;
  95843. var dragSteps = 0;
  95844. if (_this.uniformScaling) {
  95845. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  95846. if (tmpVector.y < 0) {
  95847. tmpVector.scaleInPlace(-1);
  95848. }
  95849. }
  95850. else {
  95851. tmpVector.copyFrom(dragAxis);
  95852. }
  95853. if (_this.snapDistance == 0) {
  95854. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  95855. }
  95856. else {
  95857. currentSnapDragDistance += event.dragDistance;
  95858. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  95859. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  95860. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  95861. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  95862. snapped = true;
  95863. }
  95864. else {
  95865. tmpVector.scaleInPlace(0);
  95866. }
  95867. }
  95868. _this.attachedMesh.scaling.addInPlace(tmpVector);
  95869. if (snapped) {
  95870. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  95871. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  95872. }
  95873. }
  95874. });
  95875. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  95876. if (_this._customMeshSet) {
  95877. return;
  95878. }
  95879. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  95880. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  95881. _this._rootMesh.getChildMeshes().forEach(function (m) {
  95882. m.material = material;
  95883. if (m.color) {
  95884. m.color = material.emissiveColor;
  95885. }
  95886. });
  95887. });
  95888. return _this;
  95889. }
  95890. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  95891. if (this.dragBehavior) {
  95892. this.dragBehavior.enabled = value ? true : false;
  95893. }
  95894. };
  95895. /**
  95896. * Disposes of the gizmo
  95897. */
  95898. AxisScaleGizmo.prototype.dispose = function () {
  95899. this.onSnapObservable.clear();
  95900. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  95901. this.dragBehavior.detach();
  95902. _super.prototype.dispose.call(this);
  95903. };
  95904. /**
  95905. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  95906. * @param mesh The mesh to replace the default mesh of the gizmo
  95907. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  95908. */
  95909. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  95910. var _this = this;
  95911. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  95912. _super.prototype.setCustomMesh.call(this, mesh);
  95913. if (useGizmoMaterial) {
  95914. this._rootMesh.getChildMeshes().forEach(function (m) {
  95915. m.material = _this._coloredMaterial;
  95916. if (m.color) {
  95917. m.color = _this._coloredMaterial.emissiveColor;
  95918. }
  95919. });
  95920. this._customMeshSet = false;
  95921. }
  95922. };
  95923. return AxisScaleGizmo;
  95924. }(BABYLON.Gizmo));
  95925. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  95926. })(BABYLON || (BABYLON = {}));
  95927. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  95928. var BABYLON;
  95929. (function (BABYLON) {
  95930. /**
  95931. * Single plane rotation gizmo
  95932. */
  95933. var PlaneRotationGizmo = /** @class */ (function (_super) {
  95934. __extends(PlaneRotationGizmo, _super);
  95935. /**
  95936. * Creates a PlaneRotationGizmo
  95937. * @param gizmoLayer The utility layer the gizmo will be added to
  95938. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  95939. * @param color The color of the gizmo
  95940. */
  95941. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  95942. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  95943. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  95944. var _this = _super.call(this, gizmoLayer) || this;
  95945. _this._pointerObserver = null;
  95946. /**
  95947. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  95948. */
  95949. _this.snapDistance = 0;
  95950. /**
  95951. * Event that fires each time the gizmo snaps to a new location.
  95952. * * snapDistance is the the change in distance
  95953. */
  95954. _this.onSnapObservable = new BABYLON.Observable();
  95955. // Create Material
  95956. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95957. coloredMaterial.disableLighting = true;
  95958. coloredMaterial.emissiveColor = color;
  95959. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  95960. hoverMaterial.disableLighting = true;
  95961. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  95962. // Build mesh on root node
  95963. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  95964. // Create circle out of lines
  95965. var tessellation = 20;
  95966. var radius = 0.8;
  95967. var points = new Array();
  95968. for (var i = 0; i < tessellation; i++) {
  95969. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  95970. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  95971. }
  95972. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  95973. rotationMesh.color = coloredMaterial.emissiveColor;
  95974. // Position arrow pointing in its drag axis
  95975. rotationMesh.scaling.scaleInPlace(0.26);
  95976. rotationMesh.material = coloredMaterial;
  95977. rotationMesh.rotation.x = Math.PI / 2;
  95978. parentMesh.addChild(rotationMesh);
  95979. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  95980. _this._rootMesh.addChild(parentMesh);
  95981. parentMesh.scaling.scaleInPlace(1 / 3);
  95982. // Add drag behavior to handle events when the gizmo is dragged
  95983. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  95984. _this.dragBehavior.moveAttached = false;
  95985. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  95986. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  95987. _this._rootMesh.addBehavior(_this.dragBehavior);
  95988. var lastDragPosition = new BABYLON.Vector3();
  95989. _this.dragBehavior.onDragStartObservable.add(function (e) {
  95990. if (_this.attachedMesh) {
  95991. lastDragPosition.copyFrom(e.dragPlanePoint);
  95992. }
  95993. });
  95994. var rotationMatrix = new BABYLON.Matrix();
  95995. var planeNormalTowardsCamera = new BABYLON.Vector3();
  95996. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  95997. var tmpSnapEvent = { snapDistance: 0 };
  95998. var currentSnapDragDistance = 0;
  95999. var tmpMatrix = new BABYLON.Matrix();
  96000. var tmpVector = new BABYLON.Vector3();
  96001. var amountToRotate = new BABYLON.Quaternion();
  96002. _this.dragBehavior.onDragObservable.add(function (event) {
  96003. if (_this.attachedMesh) {
  96004. if (!_this.attachedMesh.rotationQuaternion) {
  96005. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96006. }
  96007. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  96008. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  96009. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  96010. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  96011. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  96012. var angle = Math.atan2(cross.length(), dot);
  96013. planeNormalTowardsCamera.copyFrom(planeNormal);
  96014. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  96015. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96016. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  96017. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  96018. }
  96019. // Flip up vector depending on which side the camera is on
  96020. if (gizmoLayer.utilityLayerScene.activeCamera) {
  96021. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  96022. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  96023. planeNormalTowardsCamera.scaleInPlace(-1);
  96024. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  96025. }
  96026. }
  96027. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  96028. if (halfCircleSide)
  96029. angle = -angle;
  96030. // Snapping logic
  96031. var snapped = false;
  96032. if (_this.snapDistance != 0) {
  96033. currentSnapDragDistance += angle;
  96034. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  96035. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  96036. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  96037. angle = _this.snapDistance * dragSteps;
  96038. snapped = true;
  96039. }
  96040. else {
  96041. angle = 0;
  96042. }
  96043. }
  96044. // If the mesh has a parent, convert needed world rotation to local rotation
  96045. tmpMatrix.reset();
  96046. if (_this.attachedMesh.parent) {
  96047. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  96048. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  96049. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  96050. }
  96051. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  96052. var quaternionCoefficient = Math.sin(angle / 2);
  96053. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  96054. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  96055. if (tmpMatrix.determinant() > 0) {
  96056. amountToRotate.toEulerAnglesToRef(tmpVector);
  96057. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  96058. }
  96059. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  96060. // Rotate selected mesh quaternion over fixed axis
  96061. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  96062. }
  96063. else {
  96064. // Rotate selected mesh quaternion over rotated axis
  96065. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  96066. }
  96067. lastDragPosition.copyFrom(event.dragPlanePoint);
  96068. if (snapped) {
  96069. tmpSnapEvent.snapDistance = angle;
  96070. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  96071. }
  96072. }
  96073. });
  96074. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96075. if (_this._customMeshSet) {
  96076. return;
  96077. }
  96078. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  96079. var material = isHovered ? hoverMaterial : coloredMaterial;
  96080. _this._rootMesh.getChildMeshes().forEach(function (m) {
  96081. m.material = material;
  96082. if (m.color) {
  96083. m.color = material.emissiveColor;
  96084. }
  96085. });
  96086. });
  96087. return _this;
  96088. }
  96089. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  96090. if (this.dragBehavior) {
  96091. this.dragBehavior.enabled = value ? true : false;
  96092. }
  96093. };
  96094. /**
  96095. * Disposes of the gizmo
  96096. */
  96097. PlaneRotationGizmo.prototype.dispose = function () {
  96098. this.onSnapObservable.clear();
  96099. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96100. this.dragBehavior.detach();
  96101. _super.prototype.dispose.call(this);
  96102. };
  96103. return PlaneRotationGizmo;
  96104. }(BABYLON.Gizmo));
  96105. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  96106. })(BABYLON || (BABYLON = {}));
  96107. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  96108. var BABYLON;
  96109. (function (BABYLON) {
  96110. /**
  96111. * Gizmo that enables dragging a mesh along 3 axis
  96112. */
  96113. var PositionGizmo = /** @class */ (function (_super) {
  96114. __extends(PositionGizmo, _super);
  96115. /**
  96116. * Creates a PositionGizmo
  96117. * @param gizmoLayer The utility layer the gizmo will be added to
  96118. */
  96119. function PositionGizmo(gizmoLayer) {
  96120. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96121. var _this = _super.call(this, gizmoLayer) || this;
  96122. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96123. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96124. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96125. _this.attachedMesh = null;
  96126. return _this;
  96127. }
  96128. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  96129. set: function (mesh) {
  96130. if (this.xGizmo) {
  96131. this.xGizmo.attachedMesh = mesh;
  96132. this.yGizmo.attachedMesh = mesh;
  96133. this.zGizmo.attachedMesh = mesh;
  96134. }
  96135. },
  96136. enumerable: true,
  96137. configurable: true
  96138. });
  96139. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96140. get: function () {
  96141. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96142. },
  96143. set: function (value) {
  96144. if (this.xGizmo) {
  96145. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96146. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96147. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96148. }
  96149. },
  96150. enumerable: true,
  96151. configurable: true
  96152. });
  96153. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  96154. get: function () {
  96155. return this.xGizmo.snapDistance;
  96156. },
  96157. /**
  96158. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96159. */
  96160. set: function (value) {
  96161. if (this.xGizmo) {
  96162. this.xGizmo.snapDistance = value;
  96163. this.yGizmo.snapDistance = value;
  96164. this.zGizmo.snapDistance = value;
  96165. }
  96166. },
  96167. enumerable: true,
  96168. configurable: true
  96169. });
  96170. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  96171. get: function () {
  96172. return this.xGizmo.scaleRatio;
  96173. },
  96174. /**
  96175. * Ratio for the scale of the gizmo (Default: 1)
  96176. */
  96177. set: function (value) {
  96178. if (this.xGizmo) {
  96179. this.xGizmo.scaleRatio = value;
  96180. this.yGizmo.scaleRatio = value;
  96181. this.zGizmo.scaleRatio = value;
  96182. }
  96183. },
  96184. enumerable: true,
  96185. configurable: true
  96186. });
  96187. /**
  96188. * Disposes of the gizmo
  96189. */
  96190. PositionGizmo.prototype.dispose = function () {
  96191. this.xGizmo.dispose();
  96192. this.yGizmo.dispose();
  96193. this.zGizmo.dispose();
  96194. };
  96195. /**
  96196. * CustomMeshes are not supported by this gizmo
  96197. * @param mesh The mesh to replace the default mesh of the gizmo
  96198. */
  96199. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  96200. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  96201. };
  96202. return PositionGizmo;
  96203. }(BABYLON.Gizmo));
  96204. BABYLON.PositionGizmo = PositionGizmo;
  96205. })(BABYLON || (BABYLON = {}));
  96206. //# sourceMappingURL=babylon.positionGizmo.js.map
  96207. var BABYLON;
  96208. (function (BABYLON) {
  96209. /**
  96210. * Gizmo that enables rotating a mesh along 3 axis
  96211. */
  96212. var RotationGizmo = /** @class */ (function (_super) {
  96213. __extends(RotationGizmo, _super);
  96214. /**
  96215. * Creates a RotationGizmo
  96216. * @param gizmoLayer The utility layer the gizmo will be added to
  96217. */
  96218. function RotationGizmo(gizmoLayer) {
  96219. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96220. var _this = _super.call(this, gizmoLayer) || this;
  96221. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96222. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96223. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96224. _this.attachedMesh = null;
  96225. return _this;
  96226. }
  96227. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  96228. set: function (mesh) {
  96229. if (this.xGizmo) {
  96230. this.xGizmo.attachedMesh = mesh;
  96231. this.yGizmo.attachedMesh = mesh;
  96232. this.zGizmo.attachedMesh = mesh;
  96233. }
  96234. },
  96235. enumerable: true,
  96236. configurable: true
  96237. });
  96238. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96239. get: function () {
  96240. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96241. },
  96242. set: function (value) {
  96243. if (this.xGizmo) {
  96244. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96245. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96246. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96247. }
  96248. },
  96249. enumerable: true,
  96250. configurable: true
  96251. });
  96252. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  96253. get: function () {
  96254. return this.xGizmo.snapDistance;
  96255. },
  96256. /**
  96257. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96258. */
  96259. set: function (value) {
  96260. if (this.xGizmo) {
  96261. this.xGizmo.snapDistance = value;
  96262. this.yGizmo.snapDistance = value;
  96263. this.zGizmo.snapDistance = value;
  96264. }
  96265. },
  96266. enumerable: true,
  96267. configurable: true
  96268. });
  96269. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  96270. get: function () {
  96271. return this.xGizmo.scaleRatio;
  96272. },
  96273. /**
  96274. * Ratio for the scale of the gizmo (Default: 1)
  96275. */
  96276. set: function (value) {
  96277. if (this.xGizmo) {
  96278. this.xGizmo.scaleRatio = value;
  96279. this.yGizmo.scaleRatio = value;
  96280. this.zGizmo.scaleRatio = value;
  96281. }
  96282. },
  96283. enumerable: true,
  96284. configurable: true
  96285. });
  96286. /**
  96287. * Disposes of the gizmo
  96288. */
  96289. RotationGizmo.prototype.dispose = function () {
  96290. this.xGizmo.dispose();
  96291. this.yGizmo.dispose();
  96292. this.zGizmo.dispose();
  96293. };
  96294. /**
  96295. * CustomMeshes are not supported by this gizmo
  96296. * @param mesh The mesh to replace the default mesh of the gizmo
  96297. */
  96298. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  96299. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
  96300. };
  96301. return RotationGizmo;
  96302. }(BABYLON.Gizmo));
  96303. BABYLON.RotationGizmo = RotationGizmo;
  96304. })(BABYLON || (BABYLON = {}));
  96305. //# sourceMappingURL=babylon.rotationGizmo.js.map
  96306. var BABYLON;
  96307. (function (BABYLON) {
  96308. /**
  96309. * Gizmo that enables scaling a mesh along 3 axis
  96310. */
  96311. var ScaleGizmo = /** @class */ (function (_super) {
  96312. __extends(ScaleGizmo, _super);
  96313. /**
  96314. * Creates a ScaleGizmo
  96315. * @param gizmoLayer The utility layer the gizmo will be added to
  96316. */
  96317. function ScaleGizmo(gizmoLayer) {
  96318. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  96319. var _this = _super.call(this, gizmoLayer) || this;
  96320. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  96321. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  96322. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  96323. // Create uniform scale gizmo
  96324. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  96325. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  96326. _this.uniformScaleGizmo.uniformScaling = true;
  96327. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  96328. octahedron.scaling.scaleInPlace(0.007);
  96329. _this.uniformScaleGizmo.setCustomMesh(octahedron, true);
  96330. _this.attachedMesh = null;
  96331. return _this;
  96332. }
  96333. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  96334. set: function (mesh) {
  96335. if (this.xGizmo) {
  96336. this.xGizmo.attachedMesh = mesh;
  96337. this.yGizmo.attachedMesh = mesh;
  96338. this.zGizmo.attachedMesh = mesh;
  96339. this.uniformScaleGizmo.attachedMesh = mesh;
  96340. }
  96341. },
  96342. enumerable: true,
  96343. configurable: true
  96344. });
  96345. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  96346. get: function () {
  96347. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  96348. },
  96349. set: function (value) {
  96350. if (this.xGizmo) {
  96351. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96352. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96353. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  96354. }
  96355. },
  96356. enumerable: true,
  96357. configurable: true
  96358. });
  96359. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  96360. get: function () {
  96361. return this.xGizmo.snapDistance;
  96362. },
  96363. /**
  96364. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  96365. */
  96366. set: function (value) {
  96367. if (this.xGizmo) {
  96368. this.xGizmo.snapDistance = value;
  96369. this.yGizmo.snapDistance = value;
  96370. this.zGizmo.snapDistance = value;
  96371. this.uniformScaleGizmo.snapDistance = value;
  96372. }
  96373. },
  96374. enumerable: true,
  96375. configurable: true
  96376. });
  96377. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  96378. get: function () {
  96379. return this.xGizmo.scaleRatio;
  96380. },
  96381. /**
  96382. * Ratio for the scale of the gizmo (Default: 1)
  96383. */
  96384. set: function (value) {
  96385. if (this.xGizmo) {
  96386. this.xGizmo.scaleRatio = value;
  96387. this.yGizmo.scaleRatio = value;
  96388. this.zGizmo.scaleRatio = value;
  96389. this.uniformScaleGizmo.scaleRatio = value;
  96390. }
  96391. },
  96392. enumerable: true,
  96393. configurable: true
  96394. });
  96395. /**
  96396. * Disposes of the gizmo
  96397. */
  96398. ScaleGizmo.prototype.dispose = function () {
  96399. this.xGizmo.dispose();
  96400. this.yGizmo.dispose();
  96401. this.zGizmo.dispose();
  96402. this.uniformScaleGizmo.dispose();
  96403. };
  96404. return ScaleGizmo;
  96405. }(BABYLON.Gizmo));
  96406. BABYLON.ScaleGizmo = ScaleGizmo;
  96407. })(BABYLON || (BABYLON = {}));
  96408. //# sourceMappingURL=babylon.scaleGizmo.js.map
  96409. var BABYLON;
  96410. (function (BABYLON) {
  96411. /**
  96412. * Bounding box gizmo
  96413. */
  96414. var BoundingBoxGizmo = /** @class */ (function (_super) {
  96415. __extends(BoundingBoxGizmo, _super);
  96416. /**
  96417. * Creates an BoundingBoxGizmo
  96418. * @param gizmoLayer The utility layer the gizmo will be added to
  96419. * @param color The color of the gizmo
  96420. */
  96421. function BoundingBoxGizmo(color, gizmoLayer) {
  96422. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  96423. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  96424. var _this = _super.call(this, gizmoLayer) || this;
  96425. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  96426. _this._renderObserver = null;
  96427. _this._pointerObserver = null;
  96428. _this._scaleDragSpeed = 0.2;
  96429. _this._tmpQuaternion = new BABYLON.Quaternion();
  96430. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  96431. _this._tmpRotationMatrix = new BABYLON.Matrix();
  96432. /**
  96433. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  96434. */
  96435. _this.ignoreChildren = false;
  96436. /**
  96437. * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
  96438. */
  96439. _this.includeChildPredicate = null;
  96440. /**
  96441. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  96442. */
  96443. _this.rotationSphereSize = 0.1;
  96444. /**
  96445. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  96446. */
  96447. _this.scaleBoxSize = 0.1;
  96448. /**
  96449. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  96450. */
  96451. _this.fixedDragMeshScreenSize = false;
  96452. /**
  96453. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  96454. */
  96455. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  96456. /**
  96457. * Fired when a rotation sphere or scale box is dragged
  96458. */
  96459. _this.onDragStartObservable = new BABYLON.Observable();
  96460. /**
  96461. * Fired when a scale box is dragged
  96462. */
  96463. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  96464. /**
  96465. * Fired when a scale box drag is ended
  96466. */
  96467. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  96468. /**
  96469. * Fired when a rotation sphere is dragged
  96470. */
  96471. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  96472. /**
  96473. * Fired when a rotation sphere drag is ended
  96474. */
  96475. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  96476. /**
  96477. * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
  96478. */
  96479. _this.scalePivot = null;
  96480. _this._existingMeshScale = new BABYLON.Vector3();
  96481. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  96482. _this._updateScale = false;
  96483. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  96484. // Create Materials
  96485. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96486. coloredMaterial.disableLighting = true;
  96487. coloredMaterial.emissiveColor = color;
  96488. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  96489. hoverColoredMaterial.disableLighting = true;
  96490. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  96491. // Build bounding box out of lines
  96492. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96493. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  96494. var lines = [];
  96495. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  96496. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96497. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96498. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96499. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96500. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96501. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96502. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96503. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96504. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96505. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  96506. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  96507. lines.forEach(function (l) {
  96508. l.color = color;
  96509. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  96510. l.isPickable = false;
  96511. _this._lineBoundingBox.addChild(l);
  96512. });
  96513. _this._rootMesh.addChild(_this._lineBoundingBox);
  96514. // Create rotation spheres
  96515. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96516. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  96517. var _loop_1 = function (i_1) {
  96518. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  96519. sphere.rotationQuaternion = new BABYLON.Quaternion();
  96520. sphere.material = coloredMaterial;
  96521. // Drag behavior
  96522. _dragBehavior = new BABYLON.PointerDragBehavior({});
  96523. _dragBehavior.moveAttached = false;
  96524. _dragBehavior.updateDragPlane = false;
  96525. sphere.addBehavior(_dragBehavior);
  96526. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  96527. var totalTurnAmountOfDrag = 0;
  96528. _dragBehavior.onDragStartObservable.add(function (event) {
  96529. startingTurnDirection.copyFrom(sphere.forward);
  96530. totalTurnAmountOfDrag = 0;
  96531. });
  96532. _dragBehavior.onDragObservable.add(function (event) {
  96533. _this.onRotationSphereDragObservable.notifyObservers({});
  96534. if (_this.attachedMesh) {
  96535. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  96536. var worldDragDirection = startingTurnDirection;
  96537. // Project the world right on to the drag plane
  96538. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  96539. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  96540. // project drag delta on to the resulting drag axis and rotate based on that
  96541. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  96542. // Make rotation relative to size of mesh.
  96543. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  96544. // Rotate based on axis
  96545. if (!_this.attachedMesh.rotationQuaternion) {
  96546. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  96547. }
  96548. if (!_this._anchorMesh.rotationQuaternion) {
  96549. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  96550. }
  96551. // Do not allow the object to turn more than a full circle
  96552. totalTurnAmountOfDrag += projectDist;
  96553. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  96554. if (i_1 >= 8) {
  96555. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  96556. }
  96557. else if (i_1 >= 4) {
  96558. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  96559. }
  96560. else {
  96561. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  96562. }
  96563. // Rotate around center of bounding box
  96564. _this._anchorMesh.addChild(_this.attachedMesh);
  96565. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  96566. _this._anchorMesh.removeChild(_this.attachedMesh);
  96567. }
  96568. _this.updateBoundingBox();
  96569. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  96570. }
  96571. });
  96572. // Selection/deselection
  96573. _dragBehavior.onDragStartObservable.add(function () {
  96574. _this.onDragStartObservable.notifyObservers({});
  96575. _this._selectNode(sphere);
  96576. });
  96577. _dragBehavior.onDragEndObservable.add(function () {
  96578. _this.onRotationSphereDragEndObservable.notifyObservers({});
  96579. _this._selectNode(null);
  96580. });
  96581. this_1._rotateSpheresParent.addChild(sphere);
  96582. };
  96583. var this_1 = this, _dragBehavior;
  96584. for (var i_1 = 0; i_1 < 12; i_1++) {
  96585. _loop_1(i_1);
  96586. }
  96587. _this._rootMesh.addChild(_this._rotateSpheresParent);
  96588. // Create scale cubes
  96589. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  96590. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  96591. for (var i = 0; i < 2; i++) {
  96592. for (var j = 0; j < 2; j++) {
  96593. var _loop_2 = function () {
  96594. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  96595. box.material = coloredMaterial;
  96596. // Dragging logic
  96597. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  96598. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  96599. _dragBehavior.moveAttached = false;
  96600. box.addBehavior(_dragBehavior);
  96601. _dragBehavior.onDragObservable.add(function (event) {
  96602. _this.onScaleBoxDragObservable.notifyObservers({});
  96603. if (_this.attachedMesh) {
  96604. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  96605. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  96606. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  96607. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  96608. _this.updateBoundingBox();
  96609. if (_this.scalePivot) {
  96610. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  96611. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  96612. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  96613. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  96614. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  96615. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  96616. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  96617. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  96618. }
  96619. else {
  96620. // Scale from the position of the opposite corner
  96621. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  96622. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  96623. }
  96624. _this._anchorMesh.addChild(_this.attachedMesh);
  96625. _this._anchorMesh.scaling.addInPlace(deltaScale);
  96626. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  96627. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  96628. }
  96629. _this._anchorMesh.removeChild(_this.attachedMesh);
  96630. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  96631. }
  96632. });
  96633. // Selection/deselection
  96634. _dragBehavior.onDragStartObservable.add(function () {
  96635. _this.onDragStartObservable.notifyObservers({});
  96636. _this._selectNode(box);
  96637. });
  96638. _dragBehavior.onDragEndObservable.add(function () {
  96639. _this.onScaleBoxDragEndObservable.notifyObservers({});
  96640. _this._selectNode(null);
  96641. });
  96642. this_2._scaleBoxesParent.addChild(box);
  96643. };
  96644. var this_2 = this, _dragBehavior;
  96645. for (var k = 0; k < 2; k++) {
  96646. _loop_2();
  96647. }
  96648. }
  96649. }
  96650. _this._rootMesh.addChild(_this._scaleBoxesParent);
  96651. // Hover color change
  96652. var pointerIds = new Array();
  96653. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  96654. if (!pointerIds[pointerInfo.event.pointerId]) {
  96655. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  96656. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  96657. pointerIds[pointerInfo.event.pointerId] = mesh;
  96658. mesh.material = hoverColoredMaterial;
  96659. }
  96660. });
  96661. }
  96662. else {
  96663. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  96664. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  96665. delete pointerIds[pointerInfo.event.pointerId];
  96666. }
  96667. }
  96668. });
  96669. // Update bounding box positions
  96670. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  96671. // Only update the bouding box if scaling has changed
  96672. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  96673. _this.updateBoundingBox();
  96674. }
  96675. });
  96676. _this.updateBoundingBox();
  96677. return _this;
  96678. }
  96679. /** @hidden */
  96680. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  96681. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  96682. // Save old pivot and set pivot to 0,0,0
  96683. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  96684. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  96685. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  96686. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  96687. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  96688. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  96689. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  96690. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  96691. }
  96692. }
  96693. BoundingBoxGizmo._PivotCached++;
  96694. };
  96695. /** @hidden */
  96696. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  96697. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  96698. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  96699. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  96700. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  96701. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  96702. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  96703. }
  96704. this._PivotCached--;
  96705. };
  96706. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  96707. if (value) {
  96708. // Reset anchor mesh to match attached mesh's scale
  96709. // This is needed to avoid invalid box/sphere position on first drag
  96710. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  96711. this._anchorMesh.addChild(value);
  96712. this._anchorMesh.removeChild(value);
  96713. BoundingBoxGizmo._RestorePivotPoint(value);
  96714. this.updateBoundingBox();
  96715. }
  96716. };
  96717. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  96718. this._rotateSpheresParent.getChildMeshes()
  96719. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  96720. m.isVisible = (!selectedMesh || m == selectedMesh);
  96721. });
  96722. };
  96723. /**
  96724. * Updates the bounding box information for the Gizmo
  96725. */
  96726. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  96727. if (this.attachedMesh) {
  96728. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  96729. this._update();
  96730. // Rotate based on axis
  96731. if (!this.attachedMesh.rotationQuaternion) {
  96732. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  96733. }
  96734. if (!this._anchorMesh.rotationQuaternion) {
  96735. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  96736. }
  96737. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  96738. // Store original position and reset mesh to origin before computing the bounding box
  96739. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  96740. this._tmpVector.copyFrom(this.attachedMesh.position);
  96741. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  96742. this.attachedMesh.position.set(0, 0, 0);
  96743. // Update bounding dimensions/positions
  96744. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  96745. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  96746. // Update gizmo to match bounding box scaling and rotation
  96747. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  96748. this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  96749. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  96750. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  96751. this._lineBoundingBox.computeWorldMatrix();
  96752. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  96753. // restore position/rotation values
  96754. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  96755. this.attachedMesh.position.copyFrom(this._tmpVector);
  96756. }
  96757. // Update rotation sphere locations
  96758. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  96759. for (var i = 0; i < 3; i++) {
  96760. for (var j = 0; j < 2; j++) {
  96761. for (var k = 0; k < 2; k++) {
  96762. var index = ((i * 4) + (j * 2)) + k;
  96763. if (i == 0) {
  96764. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  96765. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96766. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96767. }
  96768. if (i == 1) {
  96769. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  96770. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96771. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96772. }
  96773. if (i == 2) {
  96774. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  96775. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96776. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  96777. }
  96778. if (this.fixedDragMeshScreenSize) {
  96779. this._rootMesh.computeWorldMatrix();
  96780. this._rotateSpheresParent.computeWorldMatrix();
  96781. rotateSpheres[index].computeWorldMatrix();
  96782. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  96783. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  96784. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  96785. }
  96786. else {
  96787. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  96788. }
  96789. }
  96790. }
  96791. }
  96792. // Update scale box locations
  96793. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  96794. for (var i = 0; i < 2; i++) {
  96795. for (var j = 0; j < 2; j++) {
  96796. for (var k = 0; k < 2; k++) {
  96797. var index = ((i * 4) + (j * 2)) + k;
  96798. if (scaleBoxes[index]) {
  96799. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  96800. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  96801. if (this.fixedDragMeshScreenSize) {
  96802. this._rootMesh.computeWorldMatrix();
  96803. this._scaleBoxesParent.computeWorldMatrix();
  96804. scaleBoxes[index].computeWorldMatrix();
  96805. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  96806. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  96807. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  96808. }
  96809. else {
  96810. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  96811. }
  96812. }
  96813. }
  96814. }
  96815. }
  96816. if (this.attachedMesh) {
  96817. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  96818. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  96819. }
  96820. };
  96821. /**
  96822. * Enables rotation on the specified axis and disables rotation on the others
  96823. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  96824. */
  96825. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  96826. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  96827. if (i < 4) {
  96828. m.setEnabled(axis.indexOf("x") != -1);
  96829. }
  96830. else if (i < 8) {
  96831. m.setEnabled(axis.indexOf("y") != -1);
  96832. }
  96833. else {
  96834. m.setEnabled(axis.indexOf("z") != -1);
  96835. }
  96836. });
  96837. };
  96838. /**
  96839. * Disposes of the gizmo
  96840. */
  96841. BoundingBoxGizmo.prototype.dispose = function () {
  96842. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  96843. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  96844. this._lineBoundingBox.dispose();
  96845. this._rotateSpheresParent.dispose();
  96846. this._scaleBoxesParent.dispose();
  96847. _super.prototype.dispose.call(this);
  96848. };
  96849. /**
  96850. * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
  96851. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  96852. * @returns the bounding box mesh with the passed in mesh as a child
  96853. */
  96854. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  96855. var makeNotPickable = function (root) {
  96856. root.isPickable = false;
  96857. root.getChildMeshes().forEach(function (c) {
  96858. makeNotPickable(c);
  96859. });
  96860. };
  96861. makeNotPickable(mesh);
  96862. // Reset position to get boudning box from origin with no rotation
  96863. if (!mesh.rotationQuaternion) {
  96864. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  96865. }
  96866. var oldPos = mesh.position.clone();
  96867. var oldRot = mesh.rotationQuaternion.clone();
  96868. mesh.rotationQuaternion.set(0, 0, 0, 1);
  96869. mesh.position.set(0, 0, 0);
  96870. // Update bounding dimensions/positions
  96871. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  96872. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  96873. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  96874. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  96875. // Restore original positions
  96876. mesh.addChild(box);
  96877. mesh.rotationQuaternion.copyFrom(oldRot);
  96878. mesh.position.copyFrom(oldPos);
  96879. // Reverse parenting
  96880. mesh.removeChild(box);
  96881. box.addChild(mesh);
  96882. box.visibility = 0;
  96883. return box;
  96884. };
  96885. /**
  96886. * CustomMeshes are not supported by this gizmo
  96887. * @param mesh The mesh to replace the default mesh of the gizmo
  96888. */
  96889. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  96890. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  96891. };
  96892. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  96893. // store/remove pivot point should only be applied during their outermost calls
  96894. BoundingBoxGizmo._PivotCached = 0;
  96895. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  96896. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  96897. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  96898. return BoundingBoxGizmo;
  96899. }(BABYLON.Gizmo));
  96900. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  96901. })(BABYLON || (BABYLON = {}));
  96902. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  96903. var BABYLON;
  96904. (function (BABYLON) {
  96905. /**
  96906. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  96907. */
  96908. var GizmoManager = /** @class */ (function () {
  96909. /**
  96910. * Instatiates a gizmo manager
  96911. * @param scene the scene to overlay the gizmos on top of
  96912. */
  96913. function GizmoManager(scene) {
  96914. var _this = this;
  96915. this.scene = scene;
  96916. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  96917. this._pointerObserver = null;
  96918. this._attachedMesh = null;
  96919. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  96920. /**
  96921. * When bounding box gizmo is enabled, this can be used to track drag/end events
  96922. */
  96923. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  96924. /**
  96925. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  96926. */
  96927. this.attachableMeshes = null;
  96928. /**
  96929. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  96930. */
  96931. this.usePointerToAttachGizmos = true;
  96932. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  96933. // Instatiate/dispose gizmos based on pointer actions
  96934. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  96935. if (!_this.usePointerToAttachGizmos) {
  96936. return;
  96937. }
  96938. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  96939. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  96940. var node = pointerInfo.pickInfo.pickedMesh;
  96941. if (_this.attachableMeshes == null) {
  96942. // Attach to the most parent node
  96943. while (node && node.parent != null) {
  96944. node = node.parent;
  96945. }
  96946. }
  96947. else {
  96948. // Attach to the parent node that is an attachableMesh
  96949. var found = false;
  96950. _this.attachableMeshes.forEach(function (mesh) {
  96951. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  96952. node = mesh;
  96953. found = true;
  96954. }
  96955. });
  96956. if (!found) {
  96957. node = null;
  96958. }
  96959. }
  96960. if (node instanceof BABYLON.AbstractMesh) {
  96961. _this.attachToMesh(node);
  96962. }
  96963. else {
  96964. _this.attachToMesh(null);
  96965. }
  96966. }
  96967. else {
  96968. _this.attachToMesh(null);
  96969. }
  96970. }
  96971. });
  96972. }
  96973. /**
  96974. * Attaches a set of gizmos to the specified mesh
  96975. * @param mesh The mesh the gizmo's should be attached to
  96976. */
  96977. GizmoManager.prototype.attachToMesh = function (mesh) {
  96978. if (this._attachedMesh) {
  96979. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  96980. }
  96981. this._attachedMesh = mesh;
  96982. for (var key in this.gizmos) {
  96983. var gizmo = (this.gizmos[key]);
  96984. if (gizmo && this._gizmosEnabled[key]) {
  96985. gizmo.attachedMesh = mesh;
  96986. }
  96987. }
  96988. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  96989. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  96990. }
  96991. };
  96992. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  96993. get: function () {
  96994. return this._gizmosEnabled.positionGizmo;
  96995. },
  96996. /**
  96997. * If the position gizmo is enabled
  96998. */
  96999. set: function (value) {
  97000. if (value) {
  97001. if (!this.gizmos.positionGizmo) {
  97002. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  97003. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97004. }
  97005. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  97006. }
  97007. else if (this.gizmos.positionGizmo) {
  97008. this.gizmos.positionGizmo.attachedMesh = null;
  97009. }
  97010. this._gizmosEnabled.positionGizmo = value;
  97011. },
  97012. enumerable: true,
  97013. configurable: true
  97014. });
  97015. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  97016. get: function () {
  97017. return this._gizmosEnabled.rotationGizmo;
  97018. },
  97019. /**
  97020. * If the rotation gizmo is enabled
  97021. */
  97022. set: function (value) {
  97023. if (value) {
  97024. if (!this.gizmos.rotationGizmo) {
  97025. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  97026. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  97027. }
  97028. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  97029. }
  97030. else if (this.gizmos.rotationGizmo) {
  97031. this.gizmos.rotationGizmo.attachedMesh = null;
  97032. }
  97033. this._gizmosEnabled.rotationGizmo = value;
  97034. },
  97035. enumerable: true,
  97036. configurable: true
  97037. });
  97038. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  97039. get: function () {
  97040. return this._gizmosEnabled.scaleGizmo;
  97041. },
  97042. /**
  97043. * If the scale gizmo is enabled
  97044. */
  97045. set: function (value) {
  97046. if (value) {
  97047. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  97048. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  97049. }
  97050. else if (this.gizmos.scaleGizmo) {
  97051. this.gizmos.scaleGizmo.attachedMesh = null;
  97052. }
  97053. this._gizmosEnabled.scaleGizmo = value;
  97054. },
  97055. enumerable: true,
  97056. configurable: true
  97057. });
  97058. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  97059. get: function () {
  97060. return this._gizmosEnabled.boundingBoxGizmo;
  97061. },
  97062. /**
  97063. * If the boundingBox gizmo is enabled
  97064. */
  97065. set: function (value) {
  97066. if (value) {
  97067. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  97068. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  97069. if (this._attachedMesh) {
  97070. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  97071. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  97072. }
  97073. }
  97074. else if (this.gizmos.boundingBoxGizmo) {
  97075. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  97076. }
  97077. this._gizmosEnabled.boundingBoxGizmo = value;
  97078. },
  97079. enumerable: true,
  97080. configurable: true
  97081. });
  97082. /**
  97083. * Disposes of the gizmo manager
  97084. */
  97085. GizmoManager.prototype.dispose = function () {
  97086. this.scene.onPointerObservable.remove(this._pointerObserver);
  97087. for (var key in this.gizmos) {
  97088. var gizmo = (this.gizmos[key]);
  97089. if (gizmo) {
  97090. gizmo.dispose();
  97091. }
  97092. }
  97093. this.boundingBoxDragBehavior.detach();
  97094. };
  97095. return GizmoManager;
  97096. }());
  97097. BABYLON.GizmoManager = GizmoManager;
  97098. })(BABYLON || (BABYLON = {}));
  97099. //# sourceMappingURL=babylon.gizmoManager.js.map
  97100. var BABYLON;
  97101. (function (BABYLON) {
  97102. /**
  97103. * Defines a target to use with MorphTargetManager
  97104. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97105. */
  97106. var MorphTarget = /** @class */ (function () {
  97107. /**
  97108. * Creates a new MorphTarget
  97109. * @param name defines the name of the target
  97110. * @param influence defines the influence to use
  97111. */
  97112. function MorphTarget(
  97113. /** defines the name of the target */
  97114. name, influence, scene) {
  97115. if (influence === void 0) { influence = 0; }
  97116. if (scene === void 0) { scene = null; }
  97117. this.name = name;
  97118. /**
  97119. * Gets or sets the list of animations
  97120. */
  97121. this.animations = new Array();
  97122. this._positions = null;
  97123. this._normals = null;
  97124. this._tangents = null;
  97125. /**
  97126. * Observable raised when the influence changes
  97127. */
  97128. this.onInfluenceChanged = new BABYLON.Observable();
  97129. this._animationPropertiesOverride = null;
  97130. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  97131. this.influence = influence;
  97132. }
  97133. Object.defineProperty(MorphTarget.prototype, "influence", {
  97134. /**
  97135. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  97136. */
  97137. get: function () {
  97138. return this._influence;
  97139. },
  97140. set: function (influence) {
  97141. if (this._influence === influence) {
  97142. return;
  97143. }
  97144. var previous = this._influence;
  97145. this._influence = influence;
  97146. if (this.onInfluenceChanged.hasObservers) {
  97147. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  97148. }
  97149. },
  97150. enumerable: true,
  97151. configurable: true
  97152. });
  97153. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  97154. /**
  97155. * Gets or sets the animation properties override
  97156. */
  97157. get: function () {
  97158. if (!this._animationPropertiesOverride && this._scene) {
  97159. return this._scene.animationPropertiesOverride;
  97160. }
  97161. return this._animationPropertiesOverride;
  97162. },
  97163. set: function (value) {
  97164. this._animationPropertiesOverride = value;
  97165. },
  97166. enumerable: true,
  97167. configurable: true
  97168. });
  97169. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  97170. /**
  97171. * Gets a boolean defining if the target contains position data
  97172. */
  97173. get: function () {
  97174. return !!this._positions;
  97175. },
  97176. enumerable: true,
  97177. configurable: true
  97178. });
  97179. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  97180. /**
  97181. * Gets a boolean defining if the target contains normal data
  97182. */
  97183. get: function () {
  97184. return !!this._normals;
  97185. },
  97186. enumerable: true,
  97187. configurable: true
  97188. });
  97189. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  97190. /**
  97191. * Gets a boolean defining if the target contains tangent data
  97192. */
  97193. get: function () {
  97194. return !!this._tangents;
  97195. },
  97196. enumerable: true,
  97197. configurable: true
  97198. });
  97199. /**
  97200. * Affects position data to this target
  97201. * @param data defines the position data to use
  97202. */
  97203. MorphTarget.prototype.setPositions = function (data) {
  97204. this._positions = data;
  97205. };
  97206. /**
  97207. * Gets the position data stored in this target
  97208. * @returns a FloatArray containing the position data (or null if not present)
  97209. */
  97210. MorphTarget.prototype.getPositions = function () {
  97211. return this._positions;
  97212. };
  97213. /**
  97214. * Affects normal data to this target
  97215. * @param data defines the normal data to use
  97216. */
  97217. MorphTarget.prototype.setNormals = function (data) {
  97218. this._normals = data;
  97219. };
  97220. /**
  97221. * Gets the normal data stored in this target
  97222. * @returns a FloatArray containing the normal data (or null if not present)
  97223. */
  97224. MorphTarget.prototype.getNormals = function () {
  97225. return this._normals;
  97226. };
  97227. /**
  97228. * Affects tangent data to this target
  97229. * @param data defines the tangent data to use
  97230. */
  97231. MorphTarget.prototype.setTangents = function (data) {
  97232. this._tangents = data;
  97233. };
  97234. /**
  97235. * Gets the tangent data stored in this target
  97236. * @returns a FloatArray containing the tangent data (or null if not present)
  97237. */
  97238. MorphTarget.prototype.getTangents = function () {
  97239. return this._tangents;
  97240. };
  97241. /**
  97242. * Serializes the current target into a Serialization object
  97243. * @returns the serialized object
  97244. */
  97245. MorphTarget.prototype.serialize = function () {
  97246. var serializationObject = {};
  97247. serializationObject.name = this.name;
  97248. serializationObject.influence = this.influence;
  97249. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  97250. if (this.hasNormals) {
  97251. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  97252. }
  97253. if (this.hasTangents) {
  97254. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  97255. }
  97256. // Animations
  97257. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  97258. return serializationObject;
  97259. };
  97260. // Statics
  97261. /**
  97262. * Creates a new target from serialized data
  97263. * @param serializationObject defines the serialized data to use
  97264. * @returns a new MorphTarget
  97265. */
  97266. MorphTarget.Parse = function (serializationObject) {
  97267. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  97268. result.setPositions(serializationObject.positions);
  97269. if (serializationObject.normals) {
  97270. result.setNormals(serializationObject.normals);
  97271. }
  97272. if (serializationObject.tangents) {
  97273. result.setTangents(serializationObject.tangents);
  97274. }
  97275. // Animations
  97276. if (serializationObject.animations) {
  97277. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  97278. var parsedAnimation = serializationObject.animations[animationIndex];
  97279. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  97280. }
  97281. }
  97282. return result;
  97283. };
  97284. /**
  97285. * Creates a MorphTarget from mesh data
  97286. * @param mesh defines the source mesh
  97287. * @param name defines the name to use for the new target
  97288. * @param influence defines the influence to attach to the target
  97289. * @returns a new MorphTarget
  97290. */
  97291. MorphTarget.FromMesh = function (mesh, name, influence) {
  97292. if (!name) {
  97293. name = mesh.name;
  97294. }
  97295. var result = new MorphTarget(name, influence, mesh.getScene());
  97296. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  97297. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  97298. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  97299. }
  97300. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  97301. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  97302. }
  97303. return result;
  97304. };
  97305. return MorphTarget;
  97306. }());
  97307. BABYLON.MorphTarget = MorphTarget;
  97308. })(BABYLON || (BABYLON = {}));
  97309. //# sourceMappingURL=babylon.morphTarget.js.map
  97310. var BABYLON;
  97311. (function (BABYLON) {
  97312. /**
  97313. * This class is used to deform meshes using morphing between different targets
  97314. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  97315. */
  97316. var MorphTargetManager = /** @class */ (function () {
  97317. /**
  97318. * Creates a new MorphTargetManager
  97319. * @param scene defines the current scene
  97320. */
  97321. function MorphTargetManager(scene) {
  97322. if (scene === void 0) { scene = null; }
  97323. this._targets = new Array();
  97324. this._targetObservable = new Array();
  97325. this._activeTargets = new BABYLON.SmartArray(16);
  97326. this._supportsNormals = false;
  97327. this._supportsTangents = false;
  97328. this._vertexCount = 0;
  97329. this._uniqueId = 0;
  97330. this._tempInfluences = new Array();
  97331. if (!scene) {
  97332. scene = BABYLON.Engine.LastCreatedScene;
  97333. }
  97334. this._scene = scene;
  97335. if (this._scene) {
  97336. this._scene.morphTargetManagers.push(this);
  97337. this._uniqueId = this._scene.getUniqueId();
  97338. }
  97339. }
  97340. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  97341. /**
  97342. * Gets the unique ID of this manager
  97343. */
  97344. get: function () {
  97345. return this._uniqueId;
  97346. },
  97347. enumerable: true,
  97348. configurable: true
  97349. });
  97350. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  97351. /**
  97352. * Gets the number of vertices handled by this manager
  97353. */
  97354. get: function () {
  97355. return this._vertexCount;
  97356. },
  97357. enumerable: true,
  97358. configurable: true
  97359. });
  97360. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  97361. /**
  97362. * Gets a boolean indicating if this manager supports morphing of normals
  97363. */
  97364. get: function () {
  97365. return this._supportsNormals;
  97366. },
  97367. enumerable: true,
  97368. configurable: true
  97369. });
  97370. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  97371. /**
  97372. * Gets a boolean indicating if this manager supports morphing of tangents
  97373. */
  97374. get: function () {
  97375. return this._supportsTangents;
  97376. },
  97377. enumerable: true,
  97378. configurable: true
  97379. });
  97380. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  97381. /**
  97382. * Gets the number of targets stored in this manager
  97383. */
  97384. get: function () {
  97385. return this._targets.length;
  97386. },
  97387. enumerable: true,
  97388. configurable: true
  97389. });
  97390. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  97391. /**
  97392. * Gets the number of influencers (ie. the number of targets with influences > 0)
  97393. */
  97394. get: function () {
  97395. return this._activeTargets.length;
  97396. },
  97397. enumerable: true,
  97398. configurable: true
  97399. });
  97400. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  97401. /**
  97402. * Gets the list of influences (one per target)
  97403. */
  97404. get: function () {
  97405. return this._influences;
  97406. },
  97407. enumerable: true,
  97408. configurable: true
  97409. });
  97410. /**
  97411. * Gets the active target at specified index. An active target is a target with an influence > 0
  97412. * @param index defines the index to check
  97413. * @returns the requested target
  97414. */
  97415. MorphTargetManager.prototype.getActiveTarget = function (index) {
  97416. return this._activeTargets.data[index];
  97417. };
  97418. /**
  97419. * Gets the target at specified index
  97420. * @param index defines the index to check
  97421. * @returns the requested target
  97422. */
  97423. MorphTargetManager.prototype.getTarget = function (index) {
  97424. return this._targets[index];
  97425. };
  97426. /**
  97427. * Add a new target to this manager
  97428. * @param target defines the target to add
  97429. */
  97430. MorphTargetManager.prototype.addTarget = function (target) {
  97431. var _this = this;
  97432. this._targets.push(target);
  97433. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  97434. _this._syncActiveTargets(needUpdate);
  97435. }));
  97436. this._syncActiveTargets(true);
  97437. };
  97438. /**
  97439. * Removes a target from the manager
  97440. * @param target defines the target to remove
  97441. */
  97442. MorphTargetManager.prototype.removeTarget = function (target) {
  97443. var index = this._targets.indexOf(target);
  97444. if (index >= 0) {
  97445. this._targets.splice(index, 1);
  97446. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  97447. this._syncActiveTargets(true);
  97448. }
  97449. };
  97450. /**
  97451. * Serializes the current manager into a Serialization object
  97452. * @returns the serialized object
  97453. */
  97454. MorphTargetManager.prototype.serialize = function () {
  97455. var serializationObject = {};
  97456. serializationObject.id = this.uniqueId;
  97457. serializationObject.targets = [];
  97458. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97459. var target = _a[_i];
  97460. serializationObject.targets.push(target.serialize());
  97461. }
  97462. return serializationObject;
  97463. };
  97464. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  97465. var influenceCount = 0;
  97466. this._activeTargets.reset();
  97467. this._supportsNormals = true;
  97468. this._supportsTangents = true;
  97469. this._vertexCount = 0;
  97470. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  97471. var target = _a[_i];
  97472. this._activeTargets.push(target);
  97473. this._tempInfluences[influenceCount++] = target.influence;
  97474. var positions = target.getPositions();
  97475. if (positions) {
  97476. this._supportsNormals = this._supportsNormals && target.hasNormals;
  97477. this._supportsTangents = this._supportsTangents && target.hasTangents;
  97478. var vertexCount = positions.length / 3;
  97479. if (this._vertexCount === 0) {
  97480. this._vertexCount = vertexCount;
  97481. }
  97482. else if (this._vertexCount !== vertexCount) {
  97483. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  97484. return;
  97485. }
  97486. }
  97487. }
  97488. if (!this._influences || this._influences.length !== influenceCount) {
  97489. this._influences = new Float32Array(influenceCount);
  97490. }
  97491. for (var index = 0; index < influenceCount; index++) {
  97492. this._influences[index] = this._tempInfluences[index];
  97493. }
  97494. if (needUpdate) {
  97495. this.synchronize();
  97496. }
  97497. };
  97498. /**
  97499. * Syncrhonize the targets with all the meshes using this morph target manager
  97500. */
  97501. MorphTargetManager.prototype.synchronize = function () {
  97502. if (!this._scene) {
  97503. return;
  97504. }
  97505. // Flag meshes as dirty to resync with the active targets
  97506. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  97507. var mesh = _a[_i];
  97508. if (mesh.morphTargetManager === this) {
  97509. mesh._syncGeometryWithMorphTargetManager();
  97510. }
  97511. }
  97512. };
  97513. // Statics
  97514. /**
  97515. * Creates a new MorphTargetManager from serialized data
  97516. * @param serializationObject defines the serialized data
  97517. * @param scene defines the hosting scene
  97518. * @returns the new MorphTargetManager
  97519. */
  97520. MorphTargetManager.Parse = function (serializationObject, scene) {
  97521. var result = new MorphTargetManager(scene);
  97522. result._uniqueId = serializationObject.id;
  97523. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  97524. var targetData = _a[_i];
  97525. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  97526. }
  97527. return result;
  97528. };
  97529. return MorphTargetManager;
  97530. }());
  97531. BABYLON.MorphTargetManager = MorphTargetManager;
  97532. })(BABYLON || (BABYLON = {}));
  97533. //# sourceMappingURL=babylon.morphTargetManager.js.map
  97534. var BABYLON;
  97535. (function (BABYLON) {
  97536. var Octree = /** @class */ (function () {
  97537. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  97538. if (maxDepth === void 0) { maxDepth = 2; }
  97539. this.maxDepth = maxDepth;
  97540. this.dynamicContent = new Array();
  97541. this._maxBlockCapacity = maxBlockCapacity || 64;
  97542. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  97543. this._creationFunc = creationFunc;
  97544. }
  97545. // Methods
  97546. Octree.prototype.update = function (worldMin, worldMax, entries) {
  97547. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  97548. };
  97549. Octree.prototype.addMesh = function (entry) {
  97550. for (var index = 0; index < this.blocks.length; index++) {
  97551. var block = this.blocks[index];
  97552. block.addEntry(entry);
  97553. }
  97554. };
  97555. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  97556. this._selectionContent.reset();
  97557. for (var index = 0; index < this.blocks.length; index++) {
  97558. var block = this.blocks[index];
  97559. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  97560. }
  97561. if (allowDuplicate) {
  97562. this._selectionContent.concat(this.dynamicContent);
  97563. }
  97564. else {
  97565. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97566. }
  97567. return this._selectionContent;
  97568. };
  97569. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  97570. this._selectionContent.reset();
  97571. for (var index = 0; index < this.blocks.length; index++) {
  97572. var block = this.blocks[index];
  97573. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  97574. }
  97575. if (allowDuplicate) {
  97576. this._selectionContent.concat(this.dynamicContent);
  97577. }
  97578. else {
  97579. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97580. }
  97581. return this._selectionContent;
  97582. };
  97583. Octree.prototype.intersectsRay = function (ray) {
  97584. this._selectionContent.reset();
  97585. for (var index = 0; index < this.blocks.length; index++) {
  97586. var block = this.blocks[index];
  97587. block.intersectsRay(ray, this._selectionContent);
  97588. }
  97589. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  97590. return this._selectionContent;
  97591. };
  97592. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  97593. target.blocks = new Array();
  97594. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  97595. // Segmenting space
  97596. for (var x = 0; x < 2; x++) {
  97597. for (var y = 0; y < 2; y++) {
  97598. for (var z = 0; z < 2; z++) {
  97599. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  97600. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  97601. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  97602. block.addEntries(entries);
  97603. target.blocks.push(block);
  97604. }
  97605. }
  97606. }
  97607. };
  97608. Octree.CreationFuncForMeshes = function (entry, block) {
  97609. var boundingInfo = entry.getBoundingInfo();
  97610. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  97611. block.entries.push(entry);
  97612. }
  97613. };
  97614. Octree.CreationFuncForSubMeshes = function (entry, block) {
  97615. var boundingInfo = entry.getBoundingInfo();
  97616. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  97617. block.entries.push(entry);
  97618. }
  97619. };
  97620. return Octree;
  97621. }());
  97622. BABYLON.Octree = Octree;
  97623. })(BABYLON || (BABYLON = {}));
  97624. //# sourceMappingURL=babylon.octree.js.map
  97625. var BABYLON;
  97626. (function (BABYLON) {
  97627. var OctreeBlock = /** @class */ (function () {
  97628. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  97629. this.entries = new Array();
  97630. this._boundingVectors = new Array();
  97631. this._capacity = capacity;
  97632. this._depth = depth;
  97633. this._maxDepth = maxDepth;
  97634. this._creationFunc = creationFunc;
  97635. this._minPoint = minPoint;
  97636. this._maxPoint = maxPoint;
  97637. this._boundingVectors.push(minPoint.clone());
  97638. this._boundingVectors.push(maxPoint.clone());
  97639. this._boundingVectors.push(minPoint.clone());
  97640. this._boundingVectors[2].x = maxPoint.x;
  97641. this._boundingVectors.push(minPoint.clone());
  97642. this._boundingVectors[3].y = maxPoint.y;
  97643. this._boundingVectors.push(minPoint.clone());
  97644. this._boundingVectors[4].z = maxPoint.z;
  97645. this._boundingVectors.push(maxPoint.clone());
  97646. this._boundingVectors[5].z = minPoint.z;
  97647. this._boundingVectors.push(maxPoint.clone());
  97648. this._boundingVectors[6].x = minPoint.x;
  97649. this._boundingVectors.push(maxPoint.clone());
  97650. this._boundingVectors[7].y = minPoint.y;
  97651. }
  97652. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  97653. // Property
  97654. get: function () {
  97655. return this._capacity;
  97656. },
  97657. enumerable: true,
  97658. configurable: true
  97659. });
  97660. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  97661. get: function () {
  97662. return this._minPoint;
  97663. },
  97664. enumerable: true,
  97665. configurable: true
  97666. });
  97667. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  97668. get: function () {
  97669. return this._maxPoint;
  97670. },
  97671. enumerable: true,
  97672. configurable: true
  97673. });
  97674. // Methods
  97675. OctreeBlock.prototype.addEntry = function (entry) {
  97676. if (this.blocks) {
  97677. for (var index = 0; index < this.blocks.length; index++) {
  97678. var block = this.blocks[index];
  97679. block.addEntry(entry);
  97680. }
  97681. return;
  97682. }
  97683. this._creationFunc(entry, this);
  97684. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  97685. this.createInnerBlocks();
  97686. }
  97687. };
  97688. OctreeBlock.prototype.addEntries = function (entries) {
  97689. for (var index = 0; index < entries.length; index++) {
  97690. var mesh = entries[index];
  97691. this.addEntry(mesh);
  97692. }
  97693. };
  97694. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  97695. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  97696. if (this.blocks) {
  97697. for (var index = 0; index < this.blocks.length; index++) {
  97698. var block = this.blocks[index];
  97699. block.select(frustumPlanes, selection, allowDuplicate);
  97700. }
  97701. return;
  97702. }
  97703. if (allowDuplicate) {
  97704. selection.concat(this.entries);
  97705. }
  97706. else {
  97707. selection.concatWithNoDuplicate(this.entries);
  97708. }
  97709. }
  97710. };
  97711. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  97712. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  97713. if (this.blocks) {
  97714. for (var index = 0; index < this.blocks.length; index++) {
  97715. var block = this.blocks[index];
  97716. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  97717. }
  97718. return;
  97719. }
  97720. if (allowDuplicate) {
  97721. selection.concat(this.entries);
  97722. }
  97723. else {
  97724. selection.concatWithNoDuplicate(this.entries);
  97725. }
  97726. }
  97727. };
  97728. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  97729. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  97730. if (this.blocks) {
  97731. for (var index = 0; index < this.blocks.length; index++) {
  97732. var block = this.blocks[index];
  97733. block.intersectsRay(ray, selection);
  97734. }
  97735. return;
  97736. }
  97737. selection.concatWithNoDuplicate(this.entries);
  97738. }
  97739. };
  97740. OctreeBlock.prototype.createInnerBlocks = function () {
  97741. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  97742. };
  97743. return OctreeBlock;
  97744. }());
  97745. BABYLON.OctreeBlock = OctreeBlock;
  97746. })(BABYLON || (BABYLON = {}));
  97747. //# sourceMappingURL=babylon.octreeBlock.js.map
  97748. var BABYLON;
  97749. (function (BABYLON) {
  97750. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  97751. if (maxCapacity === void 0) { maxCapacity = 64; }
  97752. if (maxDepth === void 0) { maxDepth = 2; }
  97753. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  97754. if (!component) {
  97755. component = new OctreeSceneComponent(this);
  97756. this._addComponent(component);
  97757. }
  97758. if (!this._selectionOctree) {
  97759. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  97760. }
  97761. var worldExtends = this.getWorldExtends();
  97762. // Update octree
  97763. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  97764. return this._selectionOctree;
  97765. };
  97766. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  97767. get: function () {
  97768. return this._selectionOctree;
  97769. },
  97770. enumerable: true,
  97771. configurable: true
  97772. });
  97773. /**
  97774. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  97775. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  97776. * @param maxCapacity defines the maximum size of each block (64 by default)
  97777. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  97778. * @returns the new octree
  97779. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  97780. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  97781. */
  97782. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  97783. if (maxCapacity === void 0) { maxCapacity = 64; }
  97784. if (maxDepth === void 0) { maxDepth = 2; }
  97785. var scene = this.getScene();
  97786. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  97787. if (!component) {
  97788. component = new OctreeSceneComponent(scene);
  97789. scene._addComponent(component);
  97790. }
  97791. if (!this._submeshesOctree) {
  97792. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  97793. }
  97794. this.computeWorldMatrix(true);
  97795. var boundingInfo = this.getBoundingInfo();
  97796. // Update octree
  97797. var bbox = boundingInfo.boundingBox;
  97798. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  97799. return this._submeshesOctree;
  97800. };
  97801. /**
  97802. * Defines the octree scene component responsible to manage any octrees
  97803. * in a given scene.
  97804. */
  97805. var OctreeSceneComponent = /** @class */ (function () {
  97806. /**
  97807. * Creates a new instance of the component for the given scene
  97808. * @param scene Defines the scene to register the component in
  97809. */
  97810. function OctreeSceneComponent(scene) {
  97811. /**
  97812. * The component name helpfull to identify the component in the list of scene components.
  97813. */
  97814. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  97815. /**
  97816. * Indicates if the meshes have been checked to make sure they are isEnabled()
  97817. */
  97818. this.checksIsEnabled = true;
  97819. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  97820. this.scene = scene;
  97821. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  97822. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  97823. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  97824. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  97825. }
  97826. /**
  97827. * Registers the component in a given scene
  97828. */
  97829. OctreeSceneComponent.prototype.register = function () {
  97830. var _this = this;
  97831. this.scene.onMeshRemovedObservable.add(function (mesh) {
  97832. var sceneOctree = _this.scene.selectionOctree;
  97833. if (sceneOctree !== undefined && sceneOctree !== null) {
  97834. var index = sceneOctree.dynamicContent.indexOf(mesh);
  97835. if (index !== -1) {
  97836. sceneOctree.dynamicContent.splice(index, 1);
  97837. }
  97838. }
  97839. });
  97840. this.scene.onMeshImportedObservable.add(function (mesh) {
  97841. var sceneOctree = _this.scene.selectionOctree;
  97842. if (sceneOctree !== undefined && sceneOctree !== null) {
  97843. sceneOctree.addMesh(mesh);
  97844. }
  97845. });
  97846. };
  97847. /**
  97848. * Return the list of active meshes
  97849. * @returns the list of active meshes
  97850. */
  97851. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  97852. if (this.scene._selectionOctree) {
  97853. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  97854. return selection;
  97855. }
  97856. return this.scene._getDefaultMeshCandidates();
  97857. };
  97858. /**
  97859. * Return the list of active sub meshes
  97860. * @param mesh The mesh to get the candidates sub meshes from
  97861. * @returns the list of active sub meshes
  97862. */
  97863. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  97864. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  97865. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  97866. return intersections;
  97867. }
  97868. return this.scene._getDefaultSubMeshCandidates(mesh);
  97869. };
  97870. /**
  97871. * Return the list of sub meshes intersecting with a given local ray
  97872. * @param mesh defines the mesh to find the submesh for
  97873. * @param localRay defines the ray in local space
  97874. * @returns the list of intersecting sub meshes
  97875. */
  97876. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  97877. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  97878. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  97879. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  97880. return intersections;
  97881. }
  97882. return this.scene._getDefaultSubMeshCandidates(mesh);
  97883. };
  97884. /**
  97885. * Return the list of sub meshes colliding with a collider
  97886. * @param mesh defines the mesh to find the submesh for
  97887. * @param collider defines the collider to evaluate the collision against
  97888. * @returns the list of colliding sub meshes
  97889. */
  97890. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  97891. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  97892. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  97893. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  97894. return intersections;
  97895. }
  97896. return this.scene._getDefaultSubMeshCandidates(mesh);
  97897. };
  97898. /**
  97899. * Rebuilds the elements related to this component in case of
  97900. * context lost for instance.
  97901. */
  97902. OctreeSceneComponent.prototype.rebuild = function () {
  97903. // Nothing to do here.
  97904. };
  97905. /**
  97906. * Disposes the component and the associated ressources.
  97907. */
  97908. OctreeSceneComponent.prototype.dispose = function () {
  97909. // Nothing to do here.
  97910. };
  97911. return OctreeSceneComponent;
  97912. }());
  97913. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  97914. })(BABYLON || (BABYLON = {}));
  97915. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  97916. var BABYLON;
  97917. (function (BABYLON) {
  97918. /**
  97919. * Postprocess used to generate anaglyphic rendering
  97920. */
  97921. var AnaglyphPostProcess = /** @class */ (function (_super) {
  97922. __extends(AnaglyphPostProcess, _super);
  97923. /**
  97924. * Creates a new AnaglyphPostProcess
  97925. * @param name defines postprocess name
  97926. * @param options defines creation options or target ratio scale
  97927. * @param rigCameras defines cameras using this postprocess
  97928. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  97929. * @param engine defines hosting engine
  97930. * @param reusable defines if the postprocess will be reused multiple times per frame
  97931. */
  97932. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  97933. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  97934. _this._passedProcess = rigCameras[0]._rigPostProcess;
  97935. _this.onApplyObservable.add(function (effect) {
  97936. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  97937. });
  97938. return _this;
  97939. }
  97940. return AnaglyphPostProcess;
  97941. }(BABYLON.PostProcess));
  97942. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  97943. })(BABYLON || (BABYLON = {}));
  97944. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  97945. var BABYLON;
  97946. (function (BABYLON) {
  97947. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  97948. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  97949. });
  97950. /**
  97951. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  97952. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  97953. */
  97954. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  97955. __extends(AnaglyphArcRotateCamera, _super);
  97956. /**
  97957. * Creates a new AnaglyphArcRotateCamera
  97958. * @param name defines camera name
  97959. * @param alpha defines alpha angle (in radians)
  97960. * @param beta defines beta angle (in radians)
  97961. * @param radius defines radius
  97962. * @param target defines camera target
  97963. * @param interaxialDistance defines distance between each color axis
  97964. * @param scene defines the hosting scene
  97965. */
  97966. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  97967. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  97968. _this.interaxialDistance = interaxialDistance;
  97969. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  97970. return _this;
  97971. }
  97972. /**
  97973. * Gets camera class name
  97974. * @returns AnaglyphArcRotateCamera
  97975. */
  97976. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  97977. return "AnaglyphArcRotateCamera";
  97978. };
  97979. return AnaglyphArcRotateCamera;
  97980. }(BABYLON.ArcRotateCamera));
  97981. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  97982. })(BABYLON || (BABYLON = {}));
  97983. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  97984. var BABYLON;
  97985. (function (BABYLON) {
  97986. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  97987. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  97988. });
  97989. /**
  97990. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  97991. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  97992. */
  97993. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  97994. __extends(AnaglyphFreeCamera, _super);
  97995. /**
  97996. * Creates a new AnaglyphFreeCamera
  97997. * @param name defines camera name
  97998. * @param position defines initial position
  97999. * @param interaxialDistance defines distance between each color axis
  98000. * @param scene defines the hosting scene
  98001. */
  98002. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  98003. var _this = _super.call(this, name, position, scene) || this;
  98004. _this.interaxialDistance = interaxialDistance;
  98005. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98006. return _this;
  98007. }
  98008. /**
  98009. * Gets camera class name
  98010. * @returns AnaglyphFreeCamera
  98011. */
  98012. AnaglyphFreeCamera.prototype.getClassName = function () {
  98013. return "AnaglyphFreeCamera";
  98014. };
  98015. return AnaglyphFreeCamera;
  98016. }(BABYLON.FreeCamera));
  98017. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  98018. })(BABYLON || (BABYLON = {}));
  98019. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  98020. var BABYLON;
  98021. (function (BABYLON) {
  98022. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  98023. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98024. });
  98025. /**
  98026. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  98027. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98028. */
  98029. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  98030. __extends(AnaglyphGamepadCamera, _super);
  98031. /**
  98032. * Creates a new AnaglyphGamepadCamera
  98033. * @param name defines camera name
  98034. * @param position defines initial position
  98035. * @param interaxialDistance defines distance between each color axis
  98036. * @param scene defines the hosting scene
  98037. */
  98038. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  98039. var _this = _super.call(this, name, position, scene) || this;
  98040. _this.interaxialDistance = interaxialDistance;
  98041. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98042. return _this;
  98043. }
  98044. /**
  98045. * Gets camera class name
  98046. * @returns AnaglyphGamepadCamera
  98047. */
  98048. AnaglyphGamepadCamera.prototype.getClassName = function () {
  98049. return "AnaglyphGamepadCamera";
  98050. };
  98051. return AnaglyphGamepadCamera;
  98052. }(BABYLON.GamepadCamera));
  98053. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  98054. })(BABYLON || (BABYLON = {}));
  98055. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  98056. var BABYLON;
  98057. (function (BABYLON) {
  98058. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  98059. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  98060. });
  98061. /**
  98062. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  98063. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  98064. */
  98065. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  98066. __extends(AnaglyphUniversalCamera, _super);
  98067. /**
  98068. * Creates a new AnaglyphUniversalCamera
  98069. * @param name defines camera name
  98070. * @param position defines initial position
  98071. * @param interaxialDistance defines distance between each color axis
  98072. * @param scene defines the hosting scene
  98073. */
  98074. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  98075. var _this = _super.call(this, name, position, scene) || this;
  98076. _this.interaxialDistance = interaxialDistance;
  98077. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  98078. return _this;
  98079. }
  98080. /**
  98081. * Gets camera class name
  98082. * @returns AnaglyphUniversalCamera
  98083. */
  98084. AnaglyphUniversalCamera.prototype.getClassName = function () {
  98085. return "AnaglyphUniversalCamera";
  98086. };
  98087. return AnaglyphUniversalCamera;
  98088. }(BABYLON.UniversalCamera));
  98089. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  98090. })(BABYLON || (BABYLON = {}));
  98091. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  98092. var BABYLON;
  98093. (function (BABYLON) {
  98094. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  98095. __extends(StereoscopicInterlacePostProcess, _super);
  98096. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  98097. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  98098. _this._passedProcess = rigCameras[0]._rigPostProcess;
  98099. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98100. _this.onSizeChangedObservable.add(function () {
  98101. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  98102. });
  98103. _this.onApplyObservable.add(function (effect) {
  98104. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  98105. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  98106. });
  98107. return _this;
  98108. }
  98109. return StereoscopicInterlacePostProcess;
  98110. }(BABYLON.PostProcess));
  98111. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  98112. })(BABYLON || (BABYLON = {}));
  98113. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  98114. var BABYLON;
  98115. (function (BABYLON) {
  98116. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  98117. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98118. });
  98119. /**
  98120. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  98121. * @see http://doc.babylonjs.com/features/cameras
  98122. */
  98123. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  98124. __extends(StereoscopicArcRotateCamera, _super);
  98125. /**
  98126. * Creates a new StereoscopicArcRotateCamera
  98127. * @param name defines camera name
  98128. * @param alpha defines alpha angle (in radians)
  98129. * @param beta defines beta angle (in radians)
  98130. * @param radius defines radius
  98131. * @param target defines camera target
  98132. * @param interaxialDistance defines distance between each color axis
  98133. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98134. * @param scene defines the hosting scene
  98135. */
  98136. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  98137. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  98138. _this.interaxialDistance = interaxialDistance;
  98139. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98140. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98141. return _this;
  98142. }
  98143. /**
  98144. * Gets camera class name
  98145. * @returns StereoscopicArcRotateCamera
  98146. */
  98147. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  98148. return "StereoscopicArcRotateCamera";
  98149. };
  98150. return StereoscopicArcRotateCamera;
  98151. }(BABYLON.ArcRotateCamera));
  98152. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  98153. })(BABYLON || (BABYLON = {}));
  98154. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  98155. var BABYLON;
  98156. (function (BABYLON) {
  98157. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98158. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98159. });
  98160. /**
  98161. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  98162. * @see http://doc.babylonjs.com/features/cameras
  98163. */
  98164. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  98165. __extends(StereoscopicFreeCamera, _super);
  98166. /**
  98167. * Creates a new StereoscopicFreeCamera
  98168. * @param name defines camera name
  98169. * @param position defines initial position
  98170. * @param interaxialDistance defines distance between each color axis
  98171. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98172. * @param scene defines the hosting scene
  98173. */
  98174. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98175. var _this = _super.call(this, name, position, scene) || this;
  98176. _this.interaxialDistance = interaxialDistance;
  98177. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98178. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98179. return _this;
  98180. }
  98181. /**
  98182. * Gets camera class name
  98183. * @returns StereoscopicFreeCamera
  98184. */
  98185. StereoscopicFreeCamera.prototype.getClassName = function () {
  98186. return "StereoscopicFreeCamera";
  98187. };
  98188. return StereoscopicFreeCamera;
  98189. }(BABYLON.FreeCamera));
  98190. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  98191. })(BABYLON || (BABYLON = {}));
  98192. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  98193. var BABYLON;
  98194. (function (BABYLON) {
  98195. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  98196. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98197. });
  98198. /**
  98199. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  98200. * @see http://doc.babylonjs.com/features/cameras
  98201. */
  98202. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  98203. __extends(StereoscopicGamepadCamera, _super);
  98204. /**
  98205. * Creates a new StereoscopicGamepadCamera
  98206. * @param name defines camera name
  98207. * @param position defines initial position
  98208. * @param interaxialDistance defines distance between each color axis
  98209. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98210. * @param scene defines the hosting scene
  98211. */
  98212. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98213. var _this = _super.call(this, name, position, scene) || this;
  98214. _this.interaxialDistance = interaxialDistance;
  98215. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98216. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98217. return _this;
  98218. }
  98219. /**
  98220. * Gets camera class name
  98221. * @returns StereoscopicGamepadCamera
  98222. */
  98223. StereoscopicGamepadCamera.prototype.getClassName = function () {
  98224. return "StereoscopicGamepadCamera";
  98225. };
  98226. return StereoscopicGamepadCamera;
  98227. }(BABYLON.GamepadCamera));
  98228. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  98229. })(BABYLON || (BABYLON = {}));
  98230. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  98231. var BABYLON;
  98232. (function (BABYLON) {
  98233. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  98234. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  98235. });
  98236. /**
  98237. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  98238. * @see http://doc.babylonjs.com/features/cameras
  98239. */
  98240. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  98241. __extends(StereoscopicUniversalCamera, _super);
  98242. /**
  98243. * Creates a new StereoscopicUniversalCamera
  98244. * @param name defines camera name
  98245. * @param position defines initial position
  98246. * @param interaxialDistance defines distance between each color axis
  98247. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  98248. * @param scene defines the hosting scene
  98249. */
  98250. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  98251. var _this = _super.call(this, name, position, scene) || this;
  98252. _this.interaxialDistance = interaxialDistance;
  98253. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  98254. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  98255. return _this;
  98256. }
  98257. /**
  98258. * Gets camera class name
  98259. * @returns StereoscopicUniversalCamera
  98260. */
  98261. StereoscopicUniversalCamera.prototype.getClassName = function () {
  98262. return "StereoscopicUniversalCamera";
  98263. };
  98264. return StereoscopicUniversalCamera;
  98265. }(BABYLON.UniversalCamera));
  98266. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  98267. })(BABYLON || (BABYLON = {}));
  98268. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  98269. var BABYLON;
  98270. (function (BABYLON) {
  98271. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  98272. __extends(VRDistortionCorrectionPostProcess, _super);
  98273. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  98274. var _this = _super.call(this, name, "vrDistortionCorrection", [
  98275. 'LensCenter',
  98276. 'Scale',
  98277. 'ScaleIn',
  98278. 'HmdWarpParam'
  98279. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  98280. _this._isRightEye = isRightEye;
  98281. _this._distortionFactors = vrMetrics.distortionK;
  98282. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  98283. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  98284. _this.adaptScaleToCurrentViewport = true;
  98285. _this.onSizeChangedObservable.add(function () {
  98286. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  98287. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  98288. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  98289. });
  98290. _this.onApplyObservable.add(function (effect) {
  98291. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  98292. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  98293. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  98294. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  98295. });
  98296. return _this;
  98297. }
  98298. return VRDistortionCorrectionPostProcess;
  98299. }(BABYLON.PostProcess));
  98300. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  98301. })(BABYLON || (BABYLON = {}));
  98302. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  98303. var BABYLON;
  98304. (function (BABYLON) {
  98305. /**
  98306. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  98307. * Screen rotation is taken into account.
  98308. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98309. */
  98310. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  98311. /**
  98312. * Instantiates a new input
  98313. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98314. */
  98315. function FreeCameraDeviceOrientationInput() {
  98316. var _this = this;
  98317. this._screenOrientationAngle = 0;
  98318. this._screenQuaternion = new BABYLON.Quaternion();
  98319. this._alpha = 0;
  98320. this._beta = 0;
  98321. this._gamma = 0;
  98322. this._orientationChanged = function () {
  98323. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  98324. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  98325. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  98326. };
  98327. this._deviceOrientation = function (evt) {
  98328. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  98329. _this._beta = evt.beta !== null ? evt.beta : 0;
  98330. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  98331. };
  98332. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  98333. this._orientationChanged();
  98334. }
  98335. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  98336. /**
  98337. * Define the camera controlled by the input.
  98338. */
  98339. get: function () {
  98340. return this._camera;
  98341. },
  98342. set: function (camera) {
  98343. this._camera = camera;
  98344. if (this._camera != null && !this._camera.rotationQuaternion) {
  98345. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  98346. }
  98347. },
  98348. enumerable: true,
  98349. configurable: true
  98350. });
  98351. /**
  98352. * Attach the input controls to a specific dom element to get the input from.
  98353. * @param element Defines the element the controls should be listened from
  98354. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98355. */
  98356. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98357. window.addEventListener("orientationchange", this._orientationChanged);
  98358. window.addEventListener("deviceorientation", this._deviceOrientation);
  98359. //In certain cases, the attach control is called AFTER orientation was changed,
  98360. //So this is needed.
  98361. this._orientationChanged();
  98362. };
  98363. /**
  98364. * Detach the current controls from the specified dom element.
  98365. * @param element Defines the element to stop listening the inputs from
  98366. */
  98367. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  98368. window.removeEventListener("orientationchange", this._orientationChanged);
  98369. window.removeEventListener("deviceorientation", this._deviceOrientation);
  98370. };
  98371. /**
  98372. * Update the current camera state depending on the inputs that have been used this frame.
  98373. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98374. */
  98375. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  98376. //if no device orientation provided, don't update the rotation.
  98377. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  98378. if (!this._alpha)
  98379. return;
  98380. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  98381. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  98382. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  98383. //Mirror on XY Plane
  98384. this._camera.rotationQuaternion.z *= -1;
  98385. this._camera.rotationQuaternion.w *= -1;
  98386. };
  98387. /**
  98388. * Gets the class name of the current intput.
  98389. * @returns the class name
  98390. */
  98391. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  98392. return "FreeCameraDeviceOrientationInput";
  98393. };
  98394. /**
  98395. * Get the friendly name associated with the input class.
  98396. * @returns the input friendly name
  98397. */
  98398. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  98399. return "deviceOrientation";
  98400. };
  98401. return FreeCameraDeviceOrientationInput;
  98402. }());
  98403. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  98404. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  98405. })(BABYLON || (BABYLON = {}));
  98406. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  98407. var BABYLON;
  98408. (function (BABYLON) {
  98409. /**
  98410. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  98411. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  98412. */
  98413. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  98414. /**
  98415. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  98416. */
  98417. function ArcRotateCameraVRDeviceOrientationInput() {
  98418. /**
  98419. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  98420. */
  98421. this.alphaCorrection = 1;
  98422. /**
  98423. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  98424. */
  98425. this.betaCorrection = 1;
  98426. /**
  98427. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  98428. */
  98429. this.gammaCorrection = 1;
  98430. this._alpha = 0;
  98431. this._gamma = 0;
  98432. this._dirty = false;
  98433. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  98434. }
  98435. /**
  98436. * Attach the input controls to a specific dom element to get the input from.
  98437. * @param element Defines the element the controls should be listened from
  98438. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  98439. */
  98440. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  98441. this.camera.attachControl(element, noPreventDefault);
  98442. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  98443. };
  98444. /** @hidden */
  98445. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  98446. if (evt.alpha !== null) {
  98447. this._alpha = +evt.alpha | 0;
  98448. }
  98449. if (evt.gamma !== null) {
  98450. this._gamma = +evt.gamma | 0;
  98451. }
  98452. this._dirty = true;
  98453. };
  98454. /**
  98455. * Update the current camera state depending on the inputs that have been used this frame.
  98456. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  98457. */
  98458. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  98459. if (this._dirty) {
  98460. this._dirty = false;
  98461. if (this._gamma < 0) {
  98462. this._gamma = 180 + this._gamma;
  98463. }
  98464. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  98465. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  98466. }
  98467. };
  98468. /**
  98469. * Detach the current controls from the specified dom element.
  98470. * @param element Defines the element to stop listening the inputs from
  98471. */
  98472. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  98473. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  98474. };
  98475. /**
  98476. * Gets the class name of the current intput.
  98477. * @returns the class name
  98478. */
  98479. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  98480. return "ArcRotateCameraVRDeviceOrientationInput";
  98481. };
  98482. /**
  98483. * Get the friendly name associated with the input class.
  98484. * @returns the input friendly name
  98485. */
  98486. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  98487. return "VRDeviceOrientation";
  98488. };
  98489. return ArcRotateCameraVRDeviceOrientationInput;
  98490. }());
  98491. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  98492. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  98493. })(BABYLON || (BABYLON = {}));
  98494. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  98495. var BABYLON;
  98496. (function (BABYLON) {
  98497. /**
  98498. * This represents all the required metrics to create a VR camera.
  98499. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  98500. */
  98501. var VRCameraMetrics = /** @class */ (function () {
  98502. function VRCameraMetrics() {
  98503. /**
  98504. * Define if the current vr camera should compensate the distortion of the lense or not.
  98505. */
  98506. this.compensateDistortion = true;
  98507. }
  98508. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  98509. /**
  98510. * Gets the rendering aspect ratio based on the provided resolutions.
  98511. */
  98512. get: function () {
  98513. return this.hResolution / (2 * this.vResolution);
  98514. },
  98515. enumerable: true,
  98516. configurable: true
  98517. });
  98518. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  98519. /**
  98520. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  98521. */
  98522. get: function () {
  98523. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  98524. },
  98525. enumerable: true,
  98526. configurable: true
  98527. });
  98528. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  98529. /**
  98530. * @hidden
  98531. */
  98532. get: function () {
  98533. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  98534. var h = (4 * meters) / this.hScreenSize;
  98535. return BABYLON.Matrix.Translation(h, 0, 0);
  98536. },
  98537. enumerable: true,
  98538. configurable: true
  98539. });
  98540. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  98541. /**
  98542. * @hidden
  98543. */
  98544. get: function () {
  98545. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  98546. var h = (4 * meters) / this.hScreenSize;
  98547. return BABYLON.Matrix.Translation(-h, 0, 0);
  98548. },
  98549. enumerable: true,
  98550. configurable: true
  98551. });
  98552. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  98553. /**
  98554. * @hidden
  98555. */
  98556. get: function () {
  98557. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  98558. },
  98559. enumerable: true,
  98560. configurable: true
  98561. });
  98562. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  98563. /**
  98564. * @hidden
  98565. */
  98566. get: function () {
  98567. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  98568. },
  98569. enumerable: true,
  98570. configurable: true
  98571. });
  98572. /**
  98573. * Get the default VRMetrics based on the most generic setup.
  98574. * @returns the default vr metrics
  98575. */
  98576. VRCameraMetrics.GetDefault = function () {
  98577. var result = new VRCameraMetrics();
  98578. result.hResolution = 1280;
  98579. result.vResolution = 800;
  98580. result.hScreenSize = 0.149759993;
  98581. result.vScreenSize = 0.0935999975;
  98582. result.vScreenCenter = 0.0467999987;
  98583. result.eyeToScreenDistance = 0.0410000011;
  98584. result.lensSeparationDistance = 0.0635000020;
  98585. result.interpupillaryDistance = 0.0640000030;
  98586. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  98587. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  98588. result.postProcessScaleFactor = 1.714605507808412;
  98589. result.lensCenterOffset = 0.151976421;
  98590. return result;
  98591. };
  98592. return VRCameraMetrics;
  98593. }());
  98594. BABYLON.VRCameraMetrics = VRCameraMetrics;
  98595. })(BABYLON || (BABYLON = {}));
  98596. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  98597. var BABYLON;
  98598. (function (BABYLON) {
  98599. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  98600. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  98601. });
  98602. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  98603. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  98604. });
  98605. /**
  98606. * This represents a WebVR camera.
  98607. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  98608. * @example http://doc.babylonjs.com/how_to/webvr_camera
  98609. */
  98610. var WebVRFreeCamera = /** @class */ (function (_super) {
  98611. __extends(WebVRFreeCamera, _super);
  98612. /**
  98613. * Instantiates a WebVRFreeCamera.
  98614. * @param name The name of the WebVRFreeCamera
  98615. * @param position The starting anchor position for the camera
  98616. * @param scene The scene the camera belongs to
  98617. * @param webVROptions a set of customizable options for the webVRCamera
  98618. */
  98619. function WebVRFreeCamera(name, position, scene, webVROptions) {
  98620. if (webVROptions === void 0) { webVROptions = {}; }
  98621. var _this = _super.call(this, name, position, scene) || this;
  98622. _this.webVROptions = webVROptions;
  98623. /**
  98624. * @hidden
  98625. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  98626. */
  98627. _this._vrDevice = null;
  98628. /**
  98629. * The rawPose of the vrDevice.
  98630. */
  98631. _this.rawPose = null;
  98632. _this._specsVersion = "1.1";
  98633. _this._attached = false;
  98634. _this._descendants = [];
  98635. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  98636. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  98637. /** @hidden */
  98638. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  98639. _this._standingMatrix = null;
  98640. /**
  98641. * Represents device position in babylon space.
  98642. */
  98643. _this.devicePosition = BABYLON.Vector3.Zero();
  98644. /**
  98645. * Represents device rotation in babylon space.
  98646. */
  98647. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  98648. /**
  98649. * The scale of the device to be used when translating from device space to babylon space.
  98650. */
  98651. _this.deviceScaleFactor = 1;
  98652. _this._deviceToWorld = BABYLON.Matrix.Identity();
  98653. _this._worldToDevice = BABYLON.Matrix.Identity();
  98654. /**
  98655. * References to the webVR controllers for the vrDevice.
  98656. */
  98657. _this.controllers = [];
  98658. /**
  98659. * Emits an event when a controller is attached.
  98660. */
  98661. _this.onControllersAttachedObservable = new BABYLON.Observable();
  98662. /**
  98663. * Emits an event when a controller's mesh has been loaded;
  98664. */
  98665. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  98666. /**
  98667. * Emits an event when the HMD's pose has been updated.
  98668. */
  98669. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  98670. _this._poseSet = false;
  98671. /**
  98672. * If the rig cameras be used as parent instead of this camera.
  98673. */
  98674. _this.rigParenting = true;
  98675. _this._defaultHeight = undefined;
  98676. _this._htmlElementAttached = null;
  98677. _this._detachIfAttached = function () {
  98678. var vrDisplay = _this.getEngine().getVRDevice();
  98679. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  98680. _this.detachControl(_this._htmlElementAttached);
  98681. }
  98682. };
  98683. _this._workingVector = BABYLON.Vector3.Zero();
  98684. _this._oneVector = BABYLON.Vector3.One();
  98685. _this._workingMatrix = BABYLON.Matrix.Identity();
  98686. _this._tmpMatrix = new BABYLON.Matrix();
  98687. _this._cache.position = BABYLON.Vector3.Zero();
  98688. if (webVROptions.defaultHeight) {
  98689. _this._defaultHeight = webVROptions.defaultHeight;
  98690. _this.position.y = _this._defaultHeight;
  98691. }
  98692. _this.minZ = 0.1;
  98693. //legacy support - the compensation boolean was removed.
  98694. if (arguments.length === 5) {
  98695. _this.webVROptions = arguments[4];
  98696. }
  98697. // default webVR options
  98698. if (_this.webVROptions.trackPosition == undefined) {
  98699. _this.webVROptions.trackPosition = true;
  98700. }
  98701. if (_this.webVROptions.controllerMeshes == undefined) {
  98702. _this.webVROptions.controllerMeshes = true;
  98703. }
  98704. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  98705. _this.webVROptions.defaultLightingOnControllers = true;
  98706. }
  98707. _this.rotationQuaternion = new BABYLON.Quaternion();
  98708. if (_this.webVROptions && _this.webVROptions.positionScale) {
  98709. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  98710. }
  98711. //enable VR
  98712. var engine = _this.getEngine();
  98713. _this._onVREnabled = function (success) { if (success) {
  98714. _this.initControllers();
  98715. } };
  98716. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  98717. engine.initWebVR().add(function (event) {
  98718. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  98719. return;
  98720. }
  98721. _this._vrDevice = event.vrDisplay;
  98722. //reset the rig parameters.
  98723. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  98724. if (_this._attached) {
  98725. _this.getEngine().enableVR();
  98726. }
  98727. });
  98728. if (typeof (VRFrameData) !== "undefined")
  98729. _this._frameData = new VRFrameData();
  98730. /**
  98731. * The idea behind the following lines:
  98732. * objects that have the camera as parent should actually have the rig cameras as a parent.
  98733. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  98734. * the second will not show it correctly.
  98735. *
  98736. * To solve this - each object that has the camera as parent will be added to a protected array.
  98737. * When the rig camera renders, it will take this array and set all of those to be its children.
  98738. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  98739. * Amazing!
  98740. */
  98741. scene.onBeforeCameraRenderObservable.add(function (camera) {
  98742. if (camera.parent === _this && _this.rigParenting) {
  98743. _this._descendants = _this.getDescendants(true, function (n) {
  98744. // don't take the cameras or the controllers!
  98745. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  98746. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  98747. return !isController && !isRigCamera;
  98748. });
  98749. _this._descendants.forEach(function (node) {
  98750. node.parent = camera;
  98751. });
  98752. }
  98753. });
  98754. scene.onAfterCameraRenderObservable.add(function (camera) {
  98755. if (camera.parent === _this && _this.rigParenting) {
  98756. _this._descendants.forEach(function (node) {
  98757. node.parent = _this;
  98758. });
  98759. }
  98760. });
  98761. return _this;
  98762. }
  98763. /**
  98764. * Gets the device distance from the ground in meters.
  98765. * @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.
  98766. */
  98767. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  98768. if (this._standingMatrix) {
  98769. // Add standing matrix offset to get real offset from ground in room
  98770. this._standingMatrix.getTranslationToRef(this._workingVector);
  98771. return this._deviceRoomPosition.y + this._workingVector.y;
  98772. }
  98773. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  98774. return this._defaultHeight || 0;
  98775. };
  98776. /**
  98777. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  98778. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  98779. */
  98780. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  98781. var _this = this;
  98782. if (callback === void 0) { callback = function (bool) { }; }
  98783. // Use standing matrix if available
  98784. this.getEngine().initWebVRAsync().then(function (result) {
  98785. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  98786. callback(false);
  98787. }
  98788. else {
  98789. _this._standingMatrix = new BABYLON.Matrix();
  98790. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  98791. if (!_this.getScene().useRightHandedSystem) {
  98792. [2, 6, 8, 9, 14].forEach(function (num) {
  98793. if (_this._standingMatrix) {
  98794. _this._standingMatrix.m[num] *= -1;
  98795. }
  98796. });
  98797. }
  98798. callback(true);
  98799. }
  98800. });
  98801. };
  98802. /**
  98803. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  98804. * @returns A promise with a boolean set to if the standing matrix is supported.
  98805. */
  98806. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  98807. var _this = this;
  98808. return new Promise(function (res, rej) {
  98809. _this.useStandingMatrix(function (supported) {
  98810. res(supported);
  98811. });
  98812. });
  98813. };
  98814. /**
  98815. * Disposes the camera
  98816. */
  98817. WebVRFreeCamera.prototype.dispose = function () {
  98818. this._detachIfAttached();
  98819. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  98820. _super.prototype.dispose.call(this);
  98821. };
  98822. /**
  98823. * Gets a vrController by name.
  98824. * @param name The name of the controller to retreive
  98825. * @returns the controller matching the name specified or null if not found
  98826. */
  98827. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  98828. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  98829. var gp = _a[_i];
  98830. if (gp.hand === name) {
  98831. return gp;
  98832. }
  98833. }
  98834. return null;
  98835. };
  98836. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  98837. /**
  98838. * The controller corrisponding to the users left hand.
  98839. */
  98840. get: function () {
  98841. if (!this._leftController) {
  98842. this._leftController = this.getControllerByName("left");
  98843. }
  98844. return this._leftController;
  98845. },
  98846. enumerable: true,
  98847. configurable: true
  98848. });
  98849. ;
  98850. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  98851. /**
  98852. * The controller corrisponding to the users right hand.
  98853. */
  98854. get: function () {
  98855. if (!this._rightController) {
  98856. this._rightController = this.getControllerByName("right");
  98857. }
  98858. return this._rightController;
  98859. },
  98860. enumerable: true,
  98861. configurable: true
  98862. });
  98863. ;
  98864. /**
  98865. * Casts a ray forward from the vrCamera's gaze.
  98866. * @param length Length of the ray (default: 100)
  98867. * @returns the ray corrisponding to the gaze
  98868. */
  98869. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  98870. if (length === void 0) { length = 100; }
  98871. if (this.leftCamera) {
  98872. // Use left eye to avoid computation to compute center on every call
  98873. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  98874. }
  98875. else {
  98876. return _super.prototype.getForwardRay.call(this, length);
  98877. }
  98878. };
  98879. /**
  98880. * @hidden
  98881. * Updates the camera based on device's frame data
  98882. */
  98883. WebVRFreeCamera.prototype._checkInputs = function () {
  98884. if (this._vrDevice && this._vrDevice.isPresenting) {
  98885. this._vrDevice.getFrameData(this._frameData);
  98886. this.updateFromDevice(this._frameData.pose);
  98887. }
  98888. _super.prototype._checkInputs.call(this);
  98889. };
  98890. /**
  98891. * Updates the poseControlled values based on the input device pose.
  98892. * @param poseData Pose coming from the device
  98893. */
  98894. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  98895. if (poseData && poseData.orientation) {
  98896. this.rawPose = poseData;
  98897. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  98898. if (this.getScene().useRightHandedSystem) {
  98899. this._deviceRoomRotationQuaternion.z *= -1;
  98900. this._deviceRoomRotationQuaternion.w *= -1;
  98901. }
  98902. if (this.webVROptions.trackPosition && this.rawPose.position) {
  98903. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  98904. if (this.getScene().useRightHandedSystem) {
  98905. this._deviceRoomPosition.z *= -1;
  98906. }
  98907. }
  98908. this._poseSet = true;
  98909. }
  98910. };
  98911. /**
  98912. * WebVR's attach control will start broadcasting frames to the device.
  98913. * Note that in certain browsers (chrome for example) this function must be called
  98914. * within a user-interaction callback. Example:
  98915. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  98916. *
  98917. * @param element html element to attach the vrDevice to
  98918. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  98919. */
  98920. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  98921. _super.prototype.attachControl.call(this, element, noPreventDefault);
  98922. this._attached = true;
  98923. this._htmlElementAttached = element;
  98924. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  98925. if (this._vrDevice) {
  98926. this.getEngine().enableVR();
  98927. }
  98928. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  98929. };
  98930. /**
  98931. * Detaches the camera from the html element and disables VR
  98932. *
  98933. * @param element html element to detach from
  98934. */
  98935. WebVRFreeCamera.prototype.detachControl = function (element) {
  98936. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  98937. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  98938. _super.prototype.detachControl.call(this, element);
  98939. this._attached = false;
  98940. this.getEngine().disableVR();
  98941. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  98942. };
  98943. /**
  98944. * @returns the name of this class
  98945. */
  98946. WebVRFreeCamera.prototype.getClassName = function () {
  98947. return "WebVRFreeCamera";
  98948. };
  98949. /**
  98950. * Calls resetPose on the vrDisplay
  98951. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  98952. */
  98953. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  98954. //uses the vrDisplay's "resetPose()".
  98955. //pitch and roll won't be affected.
  98956. this._vrDevice.resetPose();
  98957. };
  98958. /**
  98959. * @hidden
  98960. * Updates the rig cameras (left and right eye)
  98961. */
  98962. WebVRFreeCamera.prototype._updateRigCameras = function () {
  98963. var camLeft = this._rigCameras[0];
  98964. var camRight = this._rigCameras[1];
  98965. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  98966. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  98967. camLeft.position.copyFrom(this._deviceRoomPosition);
  98968. camRight.position.copyFrom(this._deviceRoomPosition);
  98969. };
  98970. // Remove translation from 6dof headset if trackposition is set to false
  98971. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  98972. if (isViewMatrix === void 0) { isViewMatrix = false; }
  98973. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  98974. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  98975. if (!isViewMatrix) {
  98976. this._tmpMatrix.invert();
  98977. }
  98978. this._tmpMatrix.multiplyToRef(matrix, matrix);
  98979. }
  98980. };
  98981. /**
  98982. * @hidden
  98983. * Updates the cached values of the camera
  98984. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  98985. */
  98986. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  98987. var _this = this;
  98988. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  98989. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  98990. if (!this.updateCacheCalled) {
  98991. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  98992. this.updateCacheCalled = true;
  98993. this.update();
  98994. }
  98995. // Set working vector to the device position in room space rotated by the new rotation
  98996. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  98997. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  98998. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  98999. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  99000. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  99001. // Add translation from anchor position
  99002. this._deviceToWorld.getTranslationToRef(this._workingVector);
  99003. this._workingVector.addInPlace(this.position);
  99004. this._workingVector.subtractInPlace(this._cache.position);
  99005. this._deviceToWorld.setTranslation(this._workingVector);
  99006. // Set an inverted matrix to be used when updating the camera
  99007. this._deviceToWorld.invertToRef(this._worldToDevice);
  99008. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  99009. this.controllers.forEach(function (controller) {
  99010. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  99011. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  99012. controller.update();
  99013. });
  99014. }
  99015. if (!ignoreParentClass) {
  99016. _super.prototype._updateCache.call(this);
  99017. }
  99018. this.updateCacheCalled = false;
  99019. };
  99020. /**
  99021. * Updates the current device position and rotation in the babylon world
  99022. */
  99023. WebVRFreeCamera.prototype.update = function () {
  99024. // Get current device position in babylon world
  99025. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  99026. // Get current device rotation in babylon world
  99027. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  99028. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  99029. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  99030. if (this._poseSet) {
  99031. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  99032. }
  99033. _super.prototype.update.call(this);
  99034. };
  99035. /**
  99036. * @hidden
  99037. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  99038. * @returns an identity matrix
  99039. */
  99040. WebVRFreeCamera.prototype._getViewMatrix = function () {
  99041. return BABYLON.Matrix.Identity();
  99042. };
  99043. /**
  99044. * This function is called by the two RIG cameras.
  99045. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  99046. */
  99047. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  99048. var _this = this;
  99049. // Update the parent camera prior to using a child camera to avoid desynchronization
  99050. var parentCamera = this._cameraRigParams["parentCamera"];
  99051. parentCamera._updateCache();
  99052. //WebVR 1.1
  99053. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  99054. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  99055. if (!this.getScene().useRightHandedSystem) {
  99056. [2, 6, 8, 9, 14].forEach(function (num) {
  99057. _this._webvrViewMatrix.m[num] *= -1;
  99058. });
  99059. }
  99060. // update the camera rotation matrix
  99061. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  99062. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  99063. // Computing target and final matrix
  99064. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  99065. // should the view matrix be updated with scale and position offset?
  99066. if (parentCamera.deviceScaleFactor !== 1) {
  99067. this._webvrViewMatrix.invert();
  99068. // scale the position, if set
  99069. if (parentCamera.deviceScaleFactor) {
  99070. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  99071. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  99072. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  99073. }
  99074. this._webvrViewMatrix.invert();
  99075. }
  99076. // Remove translation from 6dof headset if trackposition is set to false
  99077. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  99078. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  99079. // Compute global position
  99080. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  99081. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  99082. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  99083. this._workingMatrix.getTranslationToRef(this._globalPosition);
  99084. this._markSyncedWithParent();
  99085. return this._webvrViewMatrix;
  99086. };
  99087. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  99088. var _this = this;
  99089. var parentCamera = this.parent;
  99090. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  99091. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  99092. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  99093. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  99094. //babylon compatible matrix
  99095. if (!this.getScene().useRightHandedSystem) {
  99096. [8, 9, 10, 11].forEach(function (num) {
  99097. _this._projectionMatrix.m[num] *= -1;
  99098. });
  99099. }
  99100. return this._projectionMatrix;
  99101. };
  99102. /**
  99103. * Initializes the controllers and their meshes
  99104. */
  99105. WebVRFreeCamera.prototype.initControllers = function () {
  99106. var _this = this;
  99107. this.controllers = [];
  99108. var manager = this.getScene().gamepadManager;
  99109. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  99110. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99111. var webVrController = gamepad;
  99112. if (webVrController.defaultModel) {
  99113. webVrController.defaultModel.setEnabled(false);
  99114. }
  99115. if (webVrController.hand === "right") {
  99116. _this._rightController = null;
  99117. }
  99118. if (webVrController.hand === "left") {
  99119. _this._leftController = null;
  99120. }
  99121. var controllerIndex = _this.controllers.indexOf(webVrController);
  99122. if (controllerIndex !== -1) {
  99123. _this.controllers.splice(controllerIndex, 1);
  99124. }
  99125. }
  99126. });
  99127. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  99128. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  99129. var webVrController_1 = gamepad;
  99130. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  99131. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  99132. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  99133. if (_this.webVROptions.controllerMeshes) {
  99134. if (webVrController_1.defaultModel) {
  99135. webVrController_1.defaultModel.setEnabled(true);
  99136. }
  99137. else {
  99138. // Load the meshes
  99139. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  99140. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  99141. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  99142. if (_this.webVROptions.defaultLightingOnControllers) {
  99143. if (!_this._lightOnControllers) {
  99144. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  99145. }
  99146. var activateLightOnSubMeshes_1 = function (mesh, light) {
  99147. var children = mesh.getChildren();
  99148. if (children && children.length !== 0) {
  99149. children.forEach(function (mesh) {
  99150. light.includedOnlyMeshes.push(mesh);
  99151. activateLightOnSubMeshes_1(mesh, light);
  99152. });
  99153. }
  99154. };
  99155. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  99156. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  99157. }
  99158. });
  99159. }
  99160. }
  99161. webVrController_1.attachToPoseControlledCamera(_this);
  99162. // since this is async - sanity check. Is the controller already stored?
  99163. if (_this.controllers.indexOf(webVrController_1) === -1) {
  99164. //add to the controllers array
  99165. _this.controllers.push(webVrController_1);
  99166. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  99167. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  99168. // So we're overriding setting left & right manually to be sure
  99169. var firstViveWandDetected = false;
  99170. for (var i = 0; i < _this.controllers.length; i++) {
  99171. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  99172. if (!firstViveWandDetected) {
  99173. firstViveWandDetected = true;
  99174. _this.controllers[i].hand = "left";
  99175. }
  99176. else {
  99177. _this.controllers[i].hand = "right";
  99178. }
  99179. }
  99180. }
  99181. //did we find enough controllers? Great! let the developer know.
  99182. if (_this.controllers.length >= 2) {
  99183. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  99184. }
  99185. }
  99186. }
  99187. });
  99188. };
  99189. return WebVRFreeCamera;
  99190. }(BABYLON.FreeCamera));
  99191. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  99192. })(BABYLON || (BABYLON = {}));
  99193. //# sourceMappingURL=babylon.webVRCamera.js.map
  99194. var BABYLON;
  99195. (function (BABYLON) {
  99196. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  99197. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  99198. });
  99199. // We're mainly based on the logic defined into the FreeCamera code
  99200. /**
  99201. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  99202. * being tilted forward or back and left or right.
  99203. */
  99204. var DeviceOrientationCamera = /** @class */ (function (_super) {
  99205. __extends(DeviceOrientationCamera, _super);
  99206. /**
  99207. * Creates a new device orientation camera
  99208. * @param name The name of the camera
  99209. * @param position The start position camera
  99210. * @param scene The scene the camera belongs to
  99211. */
  99212. function DeviceOrientationCamera(name, position, scene) {
  99213. var _this = _super.call(this, name, position, scene) || this;
  99214. _this._quaternionCache = new BABYLON.Quaternion();
  99215. _this.inputs.addDeviceOrientation();
  99216. return _this;
  99217. }
  99218. /**
  99219. * Gets the current instance class name ("DeviceOrientationCamera").
  99220. * This helps avoiding instanceof at run time.
  99221. * @returns the class name
  99222. */
  99223. DeviceOrientationCamera.prototype.getClassName = function () {
  99224. return "DeviceOrientationCamera";
  99225. };
  99226. /**
  99227. * @hidden
  99228. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  99229. */
  99230. DeviceOrientationCamera.prototype._checkInputs = function () {
  99231. _super.prototype._checkInputs.call(this);
  99232. this._quaternionCache.copyFrom(this.rotationQuaternion);
  99233. if (this._initialQuaternion) {
  99234. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99235. }
  99236. };
  99237. /**
  99238. * Reset the camera to its default orientation on the specified axis only.
  99239. * @param axis The axis to reset
  99240. */
  99241. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  99242. var _this = this;
  99243. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  99244. //can only work if this camera has a rotation quaternion already.
  99245. if (!this.rotationQuaternion)
  99246. return;
  99247. if (!this._initialQuaternion) {
  99248. this._initialQuaternion = new BABYLON.Quaternion();
  99249. }
  99250. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  99251. ['x', 'y', 'z'].forEach(function (axisName) {
  99252. if (!axis[axisName]) {
  99253. _this._initialQuaternion[axisName] = 0;
  99254. }
  99255. else {
  99256. _this._initialQuaternion[axisName] *= -1;
  99257. }
  99258. });
  99259. this._initialQuaternion.normalize();
  99260. //force rotation update
  99261. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  99262. };
  99263. return DeviceOrientationCamera;
  99264. }(BABYLON.FreeCamera));
  99265. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  99266. })(BABYLON || (BABYLON = {}));
  99267. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  99268. var BABYLON;
  99269. (function (BABYLON) {
  99270. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99271. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  99272. });
  99273. /**
  99274. * Camera used to simulate VR rendering (based on FreeCamera)
  99275. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99276. */
  99277. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  99278. __extends(VRDeviceOrientationFreeCamera, _super);
  99279. /**
  99280. * Creates a new VRDeviceOrientationFreeCamera
  99281. * @param name defines camera name
  99282. * @param position defines the start position of the camera
  99283. * @param scene defines the scene the camera belongs to
  99284. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99285. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99286. */
  99287. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99288. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99289. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99290. var _this = _super.call(this, name, position, scene) || this;
  99291. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99292. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99293. return _this;
  99294. }
  99295. /**
  99296. * Gets camera class name
  99297. * @returns VRDeviceOrientationFreeCamera
  99298. */
  99299. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  99300. return "VRDeviceOrientationFreeCamera";
  99301. };
  99302. return VRDeviceOrientationFreeCamera;
  99303. }(BABYLON.DeviceOrientationCamera));
  99304. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  99305. })(BABYLON || (BABYLON = {}));
  99306. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  99307. var BABYLON;
  99308. (function (BABYLON) {
  99309. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  99310. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  99311. });
  99312. /**
  99313. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  99314. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99315. */
  99316. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  99317. __extends(VRDeviceOrientationArcRotateCamera, _super);
  99318. /**
  99319. * Creates a new VRDeviceOrientationArcRotateCamera
  99320. * @param name defines camera name
  99321. * @param alpha defines the camera rotation along the logitudinal axis
  99322. * @param beta defines the camera rotation along the latitudinal axis
  99323. * @param radius defines the camera distance from its target
  99324. * @param target defines the camera target
  99325. * @param scene defines the scene the camera belongs to
  99326. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99327. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99328. */
  99329. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  99330. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99331. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99332. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  99333. vrCameraMetrics.compensateDistortion = compensateDistortion;
  99334. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  99335. _this.inputs.addVRDeviceOrientation();
  99336. return _this;
  99337. }
  99338. /**
  99339. * Gets camera class name
  99340. * @returns VRDeviceOrientationArcRotateCamera
  99341. */
  99342. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  99343. return "VRDeviceOrientationArcRotateCamera";
  99344. };
  99345. return VRDeviceOrientationArcRotateCamera;
  99346. }(BABYLON.ArcRotateCamera));
  99347. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  99348. })(BABYLON || (BABYLON = {}));
  99349. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  99350. var BABYLON;
  99351. (function (BABYLON) {
  99352. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  99353. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  99354. });
  99355. /**
  99356. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  99357. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  99358. */
  99359. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  99360. __extends(VRDeviceOrientationGamepadCamera, _super);
  99361. /**
  99362. * Creates a new VRDeviceOrientationGamepadCamera
  99363. * @param name defines camera name
  99364. * @param position defines the start position of the camera
  99365. * @param scene defines the scene the camera belongs to
  99366. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  99367. * @param vrCameraMetrics defines the vr metrics associated to the camera
  99368. */
  99369. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  99370. if (compensateDistortion === void 0) { compensateDistortion = true; }
  99371. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  99372. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  99373. _this.inputs.addGamepad();
  99374. return _this;
  99375. }
  99376. /**
  99377. * Gets camera class name
  99378. * @returns VRDeviceOrientationGamepadCamera
  99379. */
  99380. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  99381. return "VRDeviceOrientationGamepadCamera";
  99382. };
  99383. return VRDeviceOrientationGamepadCamera;
  99384. }(BABYLON.VRDeviceOrientationFreeCamera));
  99385. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  99386. })(BABYLON || (BABYLON = {}));
  99387. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  99388. var BABYLON;
  99389. (function (BABYLON) {
  99390. var VRExperienceHelperGazer = /** @class */ (function () {
  99391. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  99392. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  99393. this.scene = scene;
  99394. /** @hidden */
  99395. this._pointerDownOnMeshAsked = false;
  99396. /** @hidden */
  99397. this._isActionableMesh = false;
  99398. /** @hidden */
  99399. this._teleportationRequestInitiated = false;
  99400. /** @hidden */
  99401. this._teleportationBackRequestInitiated = false;
  99402. /** @hidden */
  99403. this._rotationRightAsked = false;
  99404. /** @hidden */
  99405. this._rotationLeftAsked = false;
  99406. /** @hidden */
  99407. this._dpadPressed = true;
  99408. /** @hidden */
  99409. this._activePointer = false;
  99410. this._id = VRExperienceHelperGazer._idCounter++;
  99411. // Gaze tracker
  99412. if (!gazeTrackerToClone) {
  99413. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  99414. this._gazeTracker.bakeCurrentTransformIntoVertices();
  99415. this._gazeTracker.isPickable = false;
  99416. this._gazeTracker.isVisible = false;
  99417. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  99418. targetMat.specularColor = BABYLON.Color3.Black();
  99419. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99420. targetMat.backFaceCulling = false;
  99421. this._gazeTracker.material = targetMat;
  99422. }
  99423. else {
  99424. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  99425. }
  99426. }
  99427. /** @hidden */
  99428. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  99429. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  99430. };
  99431. /** @hidden */
  99432. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  99433. this._pointerDownOnMeshAsked = true;
  99434. if (this._currentHit) {
  99435. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  99436. }
  99437. };
  99438. /** @hidden */
  99439. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  99440. if (this._currentHit) {
  99441. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  99442. }
  99443. this._pointerDownOnMeshAsked = false;
  99444. };
  99445. /** @hidden */
  99446. VRExperienceHelperGazer.prototype._activatePointer = function () {
  99447. this._activePointer = true;
  99448. };
  99449. /** @hidden */
  99450. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  99451. this._activePointer = false;
  99452. };
  99453. /** @hidden */
  99454. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  99455. if (distance === void 0) { distance = 100; }
  99456. };
  99457. VRExperienceHelperGazer.prototype.dispose = function () {
  99458. this._interactionsEnabled = false;
  99459. this._teleportationEnabled = false;
  99460. if (this._gazeTracker) {
  99461. this._gazeTracker.dispose();
  99462. }
  99463. };
  99464. VRExperienceHelperGazer._idCounter = 0;
  99465. return VRExperienceHelperGazer;
  99466. }());
  99467. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  99468. __extends(VRExperienceHelperControllerGazer, _super);
  99469. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  99470. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  99471. _this.webVRController = webVRController;
  99472. // Laser pointer
  99473. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  99474. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  99475. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  99476. laserPointerMaterial.alpha = 0.6;
  99477. _this._laserPointer.material = laserPointerMaterial;
  99478. _this._laserPointer.rotation.x = Math.PI / 2;
  99479. _this._laserPointer.position.z = -0.5;
  99480. _this._laserPointer.isVisible = false;
  99481. _this._laserPointer.isPickable = false;
  99482. if (!webVRController.mesh) {
  99483. // Create an empty mesh that is used prior to loading the high quality model
  99484. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  99485. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  99486. preloadPointerPose.rotation.x = -0.7;
  99487. preloadMesh.addChild(preloadPointerPose);
  99488. webVRController.attachToMesh(preloadMesh);
  99489. }
  99490. _this._setLaserPointerParent(webVRController.mesh);
  99491. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  99492. _this._setLaserPointerParent(mesh);
  99493. });
  99494. return _this;
  99495. }
  99496. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  99497. return this.webVRController.getForwardRay(length);
  99498. };
  99499. /** @hidden */
  99500. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  99501. _super.prototype._activatePointer.call(this);
  99502. this._laserPointer.isVisible = true;
  99503. };
  99504. /** @hidden */
  99505. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  99506. _super.prototype._deactivatePointer.call(this);
  99507. this._laserPointer.isVisible = false;
  99508. };
  99509. /** @hidden */
  99510. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  99511. this._laserPointer.material.emissiveColor = color;
  99512. };
  99513. /** @hidden */
  99514. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  99515. var makeNotPick = function (root) {
  99516. root.isPickable = false;
  99517. root.getChildMeshes().forEach(function (c) {
  99518. makeNotPick(c);
  99519. });
  99520. };
  99521. makeNotPick(mesh);
  99522. var childMeshes = mesh.getChildMeshes();
  99523. this.webVRController._pointingPoseNode = null;
  99524. for (var i = 0; i < childMeshes.length; i++) {
  99525. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  99526. mesh = childMeshes[i];
  99527. this.webVRController._pointingPoseNode = mesh;
  99528. break;
  99529. }
  99530. }
  99531. this._laserPointer.parent = mesh;
  99532. };
  99533. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  99534. if (distance === void 0) { distance = 100; }
  99535. this._laserPointer.scaling.y = distance;
  99536. this._laserPointer.position.z = -distance / 2;
  99537. };
  99538. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  99539. _super.prototype.dispose.call(this);
  99540. this._laserPointer.dispose();
  99541. if (this._meshAttachedObserver) {
  99542. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  99543. }
  99544. };
  99545. return VRExperienceHelperControllerGazer;
  99546. }(VRExperienceHelperGazer));
  99547. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  99548. __extends(VRExperienceHelperCameraGazer, _super);
  99549. function VRExperienceHelperCameraGazer(getCamera, scene) {
  99550. var _this = _super.call(this, scene) || this;
  99551. _this.getCamera = getCamera;
  99552. return _this;
  99553. }
  99554. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  99555. var camera = this.getCamera();
  99556. if (camera) {
  99557. return camera.getForwardRay(length);
  99558. }
  99559. else {
  99560. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  99561. }
  99562. };
  99563. return VRExperienceHelperCameraGazer;
  99564. }(VRExperienceHelperGazer));
  99565. /**
  99566. * Helps to quickly add VR support to an existing scene.
  99567. * See http://doc.babylonjs.com/how_to/webvr_helper
  99568. */
  99569. var VRExperienceHelper = /** @class */ (function () {
  99570. /**
  99571. * Instantiates a VRExperienceHelper.
  99572. * Helps to quickly add VR support to an existing scene.
  99573. * @param scene The scene the VRExperienceHelper belongs to.
  99574. * @param webVROptions Options to modify the vr experience helper's behavior.
  99575. */
  99576. function VRExperienceHelper(scene,
  99577. /** Options to modify the vr experience helper's behavior. */
  99578. webVROptions) {
  99579. if (webVROptions === void 0) { webVROptions = {}; }
  99580. var _this = this;
  99581. this.webVROptions = webVROptions;
  99582. // Can the system support WebVR, even if a headset isn't plugged in?
  99583. this._webVRsupported = false;
  99584. // If WebVR is supported, is a headset plugged in and are we ready to present?
  99585. this._webVRready = false;
  99586. // Are we waiting for the requestPresent callback to complete?
  99587. this._webVRrequesting = false;
  99588. // Are we presenting to the headset right now? (this is the vrDevice state)
  99589. this._webVRpresenting = false;
  99590. // Are we presenting in the fullscreen fallback?
  99591. this._fullscreenVRpresenting = false;
  99592. /**
  99593. * Observable raised when entering VR.
  99594. */
  99595. this.onEnteringVRObservable = new BABYLON.Observable();
  99596. /**
  99597. * Observable raised when exiting VR.
  99598. */
  99599. this.onExitingVRObservable = new BABYLON.Observable();
  99600. /**
  99601. * Observable raised when controller mesh is loaded.
  99602. */
  99603. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  99604. this._useCustomVRButton = false;
  99605. this._teleportationRequested = false;
  99606. this._teleportActive = false;
  99607. this._floorMeshesCollection = [];
  99608. this._rotationAllowed = true;
  99609. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  99610. this._isDefaultTeleportationTarget = true;
  99611. this._teleportationFillColor = "#444444";
  99612. this._teleportationBorderColor = "#FFFFFF";
  99613. this._rotationAngle = 0;
  99614. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  99615. this._padSensibilityUp = 0.65;
  99616. this._padSensibilityDown = 0.35;
  99617. this._leftController = null;
  99618. this._rightController = null;
  99619. /**
  99620. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  99621. */
  99622. this.onNewMeshSelected = new BABYLON.Observable();
  99623. /**
  99624. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  99625. */
  99626. this.onNewMeshPicked = new BABYLON.Observable();
  99627. /**
  99628. * Observable raised before camera teleportation
  99629. */
  99630. this.onBeforeCameraTeleport = new BABYLON.Observable();
  99631. /**
  99632. * Observable raised after camera teleportation
  99633. */
  99634. this.onAfterCameraTeleport = new BABYLON.Observable();
  99635. /**
  99636. * Observable raised when current selected mesh gets unselected
  99637. */
  99638. this.onSelectedMeshUnselected = new BABYLON.Observable();
  99639. /**
  99640. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  99641. */
  99642. this.teleportationEnabled = true;
  99643. this._teleportationInitialized = false;
  99644. this._interactionsEnabled = false;
  99645. this._interactionsRequested = false;
  99646. this._displayGaze = true;
  99647. this._displayLaserPointer = true;
  99648. /**
  99649. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  99650. */
  99651. this.updateGazeTrackerScale = true;
  99652. this._onResize = function () {
  99653. _this.moveButtonToBottomRight();
  99654. if (_this._fullscreenVRpresenting && _this._webVRready) {
  99655. _this.exitVR();
  99656. }
  99657. };
  99658. this._onFullscreenChange = function () {
  99659. if (document.fullscreen !== undefined) {
  99660. _this._fullscreenVRpresenting = document.fullscreen;
  99661. }
  99662. else if (document.mozFullScreen !== undefined) {
  99663. _this._fullscreenVRpresenting = document.mozFullScreen;
  99664. }
  99665. else if (document.webkitIsFullScreen !== undefined) {
  99666. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  99667. }
  99668. else if (document.msIsFullScreen !== undefined) {
  99669. _this._fullscreenVRpresenting = document.msIsFullScreen;
  99670. }
  99671. else if (document.msFullscreenElement !== undefined) {
  99672. _this._fullscreenVRpresenting = document.msFullscreenElement;
  99673. }
  99674. if (!_this._fullscreenVRpresenting && _this._canvas) {
  99675. _this.exitVR();
  99676. if (!_this._useCustomVRButton) {
  99677. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  99678. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  99679. }
  99680. }
  99681. };
  99682. this.beforeRender = function () {
  99683. if (_this._leftController && _this._leftController._activePointer) {
  99684. _this._castRayAndSelectObject(_this._leftController);
  99685. }
  99686. if (_this._rightController && _this._rightController._activePointer) {
  99687. _this._castRayAndSelectObject(_this._rightController);
  99688. }
  99689. if (_this._noControllerIsActive) {
  99690. _this._castRayAndSelectObject(_this._cameraGazer);
  99691. }
  99692. else {
  99693. _this._cameraGazer._gazeTracker.isVisible = false;
  99694. }
  99695. };
  99696. this._onNewGamepadConnected = function (gamepad) {
  99697. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  99698. if (gamepad.leftStick) {
  99699. gamepad.onleftstickchanged(function (stickValues) {
  99700. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  99701. // Listening to classic/xbox gamepad only if no VR controller is active
  99702. if ((!_this._leftController && !_this._rightController) ||
  99703. ((_this._leftController && !_this._leftController._activePointer) &&
  99704. (_this._rightController && !_this._rightController._activePointer))) {
  99705. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  99706. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  99707. }
  99708. }
  99709. });
  99710. }
  99711. if (gamepad.rightStick) {
  99712. gamepad.onrightstickchanged(function (stickValues) {
  99713. if (_this._teleportationInitialized) {
  99714. _this._checkRotate(stickValues, _this._cameraGazer);
  99715. }
  99716. });
  99717. }
  99718. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  99719. gamepad.onbuttondown(function (buttonPressed) {
  99720. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  99721. _this._cameraGazer._selectionPointerDown();
  99722. }
  99723. });
  99724. gamepad.onbuttonup(function (buttonPressed) {
  99725. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  99726. _this._cameraGazer._selectionPointerUp();
  99727. }
  99728. });
  99729. }
  99730. }
  99731. else {
  99732. var webVRController = gamepad;
  99733. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  99734. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  99735. _this._rightController = controller;
  99736. }
  99737. else {
  99738. _this._leftController = controller;
  99739. }
  99740. _this._tryEnableInteractionOnController(controller);
  99741. }
  99742. };
  99743. // 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
  99744. this._tryEnableInteractionOnController = function (controller) {
  99745. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  99746. _this._enableInteractionOnController(controller);
  99747. }
  99748. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  99749. _this._enableTeleportationOnController(controller);
  99750. }
  99751. };
  99752. this._onNewGamepadDisconnected = function (gamepad) {
  99753. if (gamepad instanceof BABYLON.WebVRController) {
  99754. if (gamepad.hand === "left" && _this._leftController != null) {
  99755. _this._leftController.dispose();
  99756. _this._leftController = null;
  99757. }
  99758. if (gamepad.hand === "right" && _this._rightController != null) {
  99759. _this._rightController.dispose();
  99760. _this._rightController = null;
  99761. }
  99762. }
  99763. };
  99764. this._workingVector = BABYLON.Vector3.Zero();
  99765. this._workingQuaternion = BABYLON.Quaternion.Identity();
  99766. this._workingMatrix = BABYLON.Matrix.Identity();
  99767. this._scene = scene;
  99768. this._canvas = scene.getEngine().getRenderingCanvas();
  99769. // Parse options
  99770. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  99771. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  99772. }
  99773. if (webVROptions.createDeviceOrientationCamera === undefined) {
  99774. webVROptions.createDeviceOrientationCamera = true;
  99775. }
  99776. if (webVROptions.laserToggle === undefined) {
  99777. webVROptions.laserToggle = true;
  99778. }
  99779. if (webVROptions.defaultHeight === undefined) {
  99780. webVROptions.defaultHeight = 1.7;
  99781. }
  99782. if (webVROptions.useCustomVRButton) {
  99783. this._useCustomVRButton = true;
  99784. if (webVROptions.customVRButton) {
  99785. this._btnVR = webVROptions.customVRButton;
  99786. }
  99787. }
  99788. if (webVROptions.rayLength) {
  99789. this._rayLength = webVROptions.rayLength;
  99790. }
  99791. this._defaultHeight = webVROptions.defaultHeight;
  99792. if (webVROptions.positionScale) {
  99793. this._rayLength *= webVROptions.positionScale;
  99794. this._defaultHeight *= webVROptions.positionScale;
  99795. }
  99796. this._hasEnteredVR = false;
  99797. // Set position
  99798. if (this._scene.activeCamera) {
  99799. this._position = this._scene.activeCamera.position.clone();
  99800. }
  99801. else {
  99802. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  99803. }
  99804. // Set non-vr camera
  99805. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  99806. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  99807. // Copy data from existing camera
  99808. if (this._scene.activeCamera) {
  99809. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  99810. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  99811. // Set rotation from previous camera
  99812. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  99813. var targetCamera = this._scene.activeCamera;
  99814. if (targetCamera.rotationQuaternion) {
  99815. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  99816. }
  99817. else {
  99818. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  99819. }
  99820. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  99821. }
  99822. }
  99823. this._scene.activeCamera = this._deviceOrientationCamera;
  99824. if (this._canvas) {
  99825. this._scene.activeCamera.attachControl(this._canvas);
  99826. }
  99827. }
  99828. else {
  99829. this._existingCamera = this._scene.activeCamera;
  99830. }
  99831. // Create VR cameras
  99832. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  99833. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  99834. }
  99835. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  99836. this._webVRCamera.useStandingMatrix();
  99837. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  99838. // Create default button
  99839. if (!this._useCustomVRButton) {
  99840. this._btnVR = document.createElement("BUTTON");
  99841. this._btnVR.className = "babylonVRicon";
  99842. this._btnVR.id = "babylonVRiconbtn";
  99843. this._btnVR.title = "Click to switch to VR";
  99844. 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) }";
  99845. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  99846. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  99847. // css += ".babylonVRicon.vrdisplaysupported { }";
  99848. // css += ".babylonVRicon.vrdisplayready { }";
  99849. // css += ".babylonVRicon.vrdisplayrequesting { }";
  99850. var style = document.createElement('style');
  99851. style.appendChild(document.createTextNode(css));
  99852. document.getElementsByTagName('head')[0].appendChild(style);
  99853. this.moveButtonToBottomRight();
  99854. }
  99855. // VR button click event
  99856. if (this._btnVR) {
  99857. this._btnVR.addEventListener("click", function () {
  99858. if (!_this.isInVRMode) {
  99859. _this.enterVR();
  99860. }
  99861. else {
  99862. _this.exitVR();
  99863. }
  99864. });
  99865. }
  99866. // Window events
  99867. window.addEventListener("resize", this._onResize);
  99868. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  99869. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  99870. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  99871. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  99872. document.onmsfullscreenchange = this._onFullscreenChange;
  99873. // Display vr button when headset is connected
  99874. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  99875. this.displayVRButton();
  99876. }
  99877. else {
  99878. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  99879. if (e.vrDisplay) {
  99880. _this.displayVRButton();
  99881. }
  99882. });
  99883. }
  99884. // Exiting VR mode using 'ESC' key on desktop
  99885. this._onKeyDown = function (event) {
  99886. if (event.keyCode === 27 && _this.isInVRMode) {
  99887. _this.exitVR();
  99888. }
  99889. };
  99890. document.addEventListener("keydown", this._onKeyDown);
  99891. // Exiting VR mode double tapping the touch screen
  99892. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  99893. if (_this.isInVRMode) {
  99894. _this.exitVR();
  99895. if (_this._fullscreenVRpresenting) {
  99896. _this._scene.getEngine().switchFullscreen(true);
  99897. }
  99898. }
  99899. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  99900. // Listen for WebVR display changes
  99901. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  99902. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  99903. this._onVRRequestPresentStart = function () {
  99904. _this._webVRrequesting = true;
  99905. _this.updateButtonVisibility();
  99906. };
  99907. this._onVRRequestPresentComplete = function (success) {
  99908. _this._webVRrequesting = false;
  99909. _this.updateButtonVisibility();
  99910. };
  99911. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  99912. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  99913. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  99914. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  99915. scene.onDisposeObservable.add(function () {
  99916. _this.dispose();
  99917. });
  99918. // Gamepad connection events
  99919. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  99920. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  99921. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  99922. this.updateButtonVisibility();
  99923. //create easing functions
  99924. this._circleEase = new BABYLON.CircleEase();
  99925. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  99926. if (this.webVROptions.floorMeshes) {
  99927. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  99928. }
  99929. }
  99930. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  99931. /** Return this.onEnteringVRObservable
  99932. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  99933. */
  99934. get: function () {
  99935. return this.onEnteringVRObservable;
  99936. },
  99937. enumerable: true,
  99938. configurable: true
  99939. });
  99940. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  99941. /** Return this.onExitingVRObservable
  99942. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  99943. */
  99944. get: function () {
  99945. return this.onExitingVRObservable;
  99946. },
  99947. enumerable: true,
  99948. configurable: true
  99949. });
  99950. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  99951. /** Return this.onControllerMeshLoadedObservable
  99952. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  99953. */
  99954. get: function () {
  99955. return this.onControllerMeshLoadedObservable;
  99956. },
  99957. enumerable: true,
  99958. configurable: true
  99959. });
  99960. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  99961. /**
  99962. * The mesh used to display where the user is going to teleport.
  99963. */
  99964. get: function () {
  99965. return this._teleportationTarget;
  99966. },
  99967. /**
  99968. * Sets the mesh to be used to display where the user is going to teleport.
  99969. */
  99970. set: function (value) {
  99971. if (value) {
  99972. value.name = "teleportationTarget";
  99973. this._isDefaultTeleportationTarget = false;
  99974. this._teleportationTarget = value;
  99975. }
  99976. },
  99977. enumerable: true,
  99978. configurable: true
  99979. });
  99980. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  99981. /**
  99982. * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
  99983. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  99984. * See http://doc.babylonjs.com/resources/baking_transformations
  99985. */
  99986. get: function () {
  99987. return this._cameraGazer._gazeTracker;
  99988. },
  99989. set: function (value) {
  99990. if (value) {
  99991. // Dispose of existing meshes
  99992. if (this._cameraGazer._gazeTracker) {
  99993. this._cameraGazer._gazeTracker.dispose();
  99994. }
  99995. if (this._leftController && this._leftController._gazeTracker) {
  99996. this._leftController._gazeTracker.dispose();
  99997. }
  99998. if (this._rightController && this._rightController._gazeTracker) {
  99999. this._rightController._gazeTracker.dispose();
  100000. }
  100001. // Set and create gaze trackers on head and controllers
  100002. this._cameraGazer._gazeTracker = value;
  100003. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  100004. this._cameraGazer._gazeTracker.isPickable = false;
  100005. this._cameraGazer._gazeTracker.isVisible = false;
  100006. this._cameraGazer._gazeTracker.name = "gazeTracker";
  100007. if (this._leftController) {
  100008. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100009. }
  100010. if (this._rightController) {
  100011. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  100012. }
  100013. }
  100014. },
  100015. enumerable: true,
  100016. configurable: true
  100017. });
  100018. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  100019. /**
  100020. * The gaze tracking mesh corresponding to the left controller
  100021. */
  100022. get: function () {
  100023. if (this._leftController) {
  100024. return this._leftController._gazeTracker;
  100025. }
  100026. return null;
  100027. },
  100028. enumerable: true,
  100029. configurable: true
  100030. });
  100031. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  100032. /**
  100033. * The gaze tracking mesh corresponding to the right controller
  100034. */
  100035. get: function () {
  100036. if (this._rightController) {
  100037. return this._rightController._gazeTracker;
  100038. }
  100039. return null;
  100040. },
  100041. enumerable: true,
  100042. configurable: true
  100043. });
  100044. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  100045. /**
  100046. * If the ray of the gaze should be displayed.
  100047. */
  100048. get: function () {
  100049. return this._displayGaze;
  100050. },
  100051. /**
  100052. * Sets if the ray of the gaze should be displayed.
  100053. */
  100054. set: function (value) {
  100055. this._displayGaze = value;
  100056. if (!value) {
  100057. this._cameraGazer._gazeTracker.isVisible = false;
  100058. if (this._leftController) {
  100059. this._leftController._gazeTracker.isVisible = false;
  100060. }
  100061. if (this._rightController) {
  100062. this._rightController._gazeTracker.isVisible = false;
  100063. }
  100064. }
  100065. },
  100066. enumerable: true,
  100067. configurable: true
  100068. });
  100069. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  100070. /**
  100071. * If the ray of the LaserPointer should be displayed.
  100072. */
  100073. get: function () {
  100074. return this._displayLaserPointer;
  100075. },
  100076. /**
  100077. * Sets if the ray of the LaserPointer should be displayed.
  100078. */
  100079. set: function (value) {
  100080. this._displayLaserPointer = value;
  100081. if (!value) {
  100082. if (this._rightController) {
  100083. this._rightController._deactivatePointer();
  100084. this._rightController._gazeTracker.isVisible = false;
  100085. }
  100086. if (this._leftController) {
  100087. this._leftController._deactivatePointer();
  100088. this._leftController._gazeTracker.isVisible = false;
  100089. }
  100090. }
  100091. else {
  100092. if (this._rightController) {
  100093. this._rightController._activatePointer();
  100094. }
  100095. if (this._leftController) {
  100096. this._leftController._activatePointer();
  100097. }
  100098. }
  100099. },
  100100. enumerable: true,
  100101. configurable: true
  100102. });
  100103. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  100104. /**
  100105. * The deviceOrientationCamera used as the camera when not in VR.
  100106. */
  100107. get: function () {
  100108. return this._deviceOrientationCamera;
  100109. },
  100110. enumerable: true,
  100111. configurable: true
  100112. });
  100113. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  100114. /**
  100115. * Based on the current WebVR support, returns the current VR camera used.
  100116. */
  100117. get: function () {
  100118. if (this._webVRready) {
  100119. return this._webVRCamera;
  100120. }
  100121. else {
  100122. return this._scene.activeCamera;
  100123. }
  100124. },
  100125. enumerable: true,
  100126. configurable: true
  100127. });
  100128. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  100129. /**
  100130. * The webVRCamera which is used when in VR.
  100131. */
  100132. get: function () {
  100133. return this._webVRCamera;
  100134. },
  100135. enumerable: true,
  100136. configurable: true
  100137. });
  100138. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  100139. /**
  100140. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  100141. */
  100142. get: function () {
  100143. return this._vrDeviceOrientationCamera;
  100144. },
  100145. enumerable: true,
  100146. configurable: true
  100147. });
  100148. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  100149. get: function () {
  100150. var result = this._cameraGazer._teleportationRequestInitiated
  100151. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  100152. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  100153. return result;
  100154. },
  100155. enumerable: true,
  100156. configurable: true
  100157. });
  100158. // Raised when one of the controller has loaded successfully its associated default mesh
  100159. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  100160. if (this._leftController && this._leftController.webVRController == webVRController) {
  100161. if (webVRController.mesh) {
  100162. this._leftController._setLaserPointerParent(webVRController.mesh);
  100163. }
  100164. }
  100165. if (this._rightController && this._rightController.webVRController == webVRController) {
  100166. if (webVRController.mesh) {
  100167. this._rightController._setLaserPointerParent(webVRController.mesh);
  100168. }
  100169. }
  100170. try {
  100171. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  100172. }
  100173. catch (err) {
  100174. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  100175. }
  100176. };
  100177. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  100178. /**
  100179. * Gets a value indicating if we are currently in VR mode.
  100180. */
  100181. get: function () {
  100182. return this._webVRpresenting || this._fullscreenVRpresenting;
  100183. },
  100184. enumerable: true,
  100185. configurable: true
  100186. });
  100187. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  100188. var vrDisplay = this._scene.getEngine().getVRDevice();
  100189. if (vrDisplay) {
  100190. var wasPresenting = this._webVRpresenting;
  100191. this._webVRpresenting = vrDisplay.isPresenting;
  100192. if (wasPresenting && !this._webVRpresenting)
  100193. this.exitVR();
  100194. }
  100195. else {
  100196. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  100197. }
  100198. this.updateButtonVisibility();
  100199. };
  100200. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  100201. this._webVRsupported = eventArgs.vrSupported;
  100202. this._webVRready = !!eventArgs.vrDisplay;
  100203. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  100204. this.updateButtonVisibility();
  100205. };
  100206. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  100207. if (this._canvas && !this._useCustomVRButton) {
  100208. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  100209. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  100210. }
  100211. };
  100212. VRExperienceHelper.prototype.displayVRButton = function () {
  100213. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  100214. document.body.appendChild(this._btnVR);
  100215. this._btnVRDisplayed = true;
  100216. }
  100217. };
  100218. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  100219. if (!this._btnVR || this._useCustomVRButton) {
  100220. return;
  100221. }
  100222. this._btnVR.className = "babylonVRicon";
  100223. if (this.isInVRMode) {
  100224. this._btnVR.className += " vrdisplaypresenting";
  100225. }
  100226. else {
  100227. if (this._webVRready)
  100228. this._btnVR.className += " vrdisplayready";
  100229. if (this._webVRsupported)
  100230. this._btnVR.className += " vrdisplaysupported";
  100231. if (this._webVRrequesting)
  100232. this._btnVR.className += " vrdisplayrequesting";
  100233. }
  100234. };
  100235. /**
  100236. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  100237. * Otherwise, will use the fullscreen API.
  100238. */
  100239. VRExperienceHelper.prototype.enterVR = function () {
  100240. if (this.onEnteringVRObservable) {
  100241. try {
  100242. this.onEnteringVRObservable.notifyObservers(this);
  100243. }
  100244. catch (err) {
  100245. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  100246. }
  100247. }
  100248. if (this._scene.activeCamera) {
  100249. this._position = this._scene.activeCamera.position.clone();
  100250. // make sure that we return to the last active camera
  100251. this._existingCamera = this._scene.activeCamera;
  100252. }
  100253. if (this._webVRrequesting)
  100254. return;
  100255. // If WebVR is supported and a headset is connected
  100256. if (this._webVRready) {
  100257. if (!this._webVRpresenting) {
  100258. this._webVRCamera.position = this._position;
  100259. this._scene.activeCamera = this._webVRCamera;
  100260. }
  100261. }
  100262. else if (this._vrDeviceOrientationCamera) {
  100263. this._vrDeviceOrientationCamera.position = this._position;
  100264. if (this._scene.activeCamera) {
  100265. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  100266. }
  100267. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  100268. this._scene.getEngine().switchFullscreen(true);
  100269. this.updateButtonVisibility();
  100270. }
  100271. if (this._scene.activeCamera && this._canvas) {
  100272. this._scene.activeCamera.attachControl(this._canvas);
  100273. }
  100274. if (this._interactionsEnabled) {
  100275. this._scene.registerBeforeRender(this.beforeRender);
  100276. }
  100277. this._hasEnteredVR = true;
  100278. };
  100279. /**
  100280. * Attempt to exit VR, or fullscreen.
  100281. */
  100282. VRExperienceHelper.prototype.exitVR = function () {
  100283. if (this._hasEnteredVR) {
  100284. if (this.onExitingVRObservable) {
  100285. try {
  100286. this.onExitingVRObservable.notifyObservers(this);
  100287. }
  100288. catch (err) {
  100289. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  100290. }
  100291. }
  100292. if (this._webVRpresenting) {
  100293. this._scene.getEngine().disableVR();
  100294. }
  100295. if (this._scene.activeCamera) {
  100296. this._position = this._scene.activeCamera.position.clone();
  100297. }
  100298. if (this._deviceOrientationCamera) {
  100299. this._deviceOrientationCamera.position = this._position;
  100300. this._scene.activeCamera = this._deviceOrientationCamera;
  100301. if (this._canvas) {
  100302. this._scene.activeCamera.attachControl(this._canvas);
  100303. }
  100304. }
  100305. else if (this._existingCamera) {
  100306. this._existingCamera.position = this._position;
  100307. this._scene.activeCamera = this._existingCamera;
  100308. }
  100309. this.updateButtonVisibility();
  100310. if (this._interactionsEnabled) {
  100311. this._scene.unregisterBeforeRender(this.beforeRender);
  100312. this._cameraGazer._gazeTracker.isVisible = false;
  100313. if (this._leftController) {
  100314. this._leftController._gazeTracker.isVisible = false;
  100315. }
  100316. if (this._rightController) {
  100317. this._rightController._gazeTracker.isVisible = false;
  100318. }
  100319. }
  100320. // resize to update width and height when exiting vr exits fullscreen
  100321. this._scene.getEngine().resize();
  100322. this._hasEnteredVR = false;
  100323. }
  100324. };
  100325. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  100326. /**
  100327. * The position of the vr experience helper.
  100328. */
  100329. get: function () {
  100330. return this._position;
  100331. },
  100332. /**
  100333. * Sets the position of the vr experience helper.
  100334. */
  100335. set: function (value) {
  100336. this._position = value;
  100337. if (this._scene.activeCamera) {
  100338. this._scene.activeCamera.position = value;
  100339. }
  100340. },
  100341. enumerable: true,
  100342. configurable: true
  100343. });
  100344. /**
  100345. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  100346. */
  100347. VRExperienceHelper.prototype.enableInteractions = function () {
  100348. var _this = this;
  100349. if (!this._interactionsEnabled) {
  100350. this._interactionsRequested = true;
  100351. if (this._leftController) {
  100352. this._enableInteractionOnController(this._leftController);
  100353. }
  100354. if (this._rightController) {
  100355. this._enableInteractionOnController(this._rightController);
  100356. }
  100357. this.raySelectionPredicate = function (mesh) {
  100358. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  100359. };
  100360. this.meshSelectionPredicate = function (mesh) {
  100361. return true;
  100362. };
  100363. this._raySelectionPredicate = function (mesh) {
  100364. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  100365. && mesh.name.indexOf("teleportationTarget") === -1
  100366. && mesh.name.indexOf("torusTeleportation") === -1)) {
  100367. return _this.raySelectionPredicate(mesh);
  100368. }
  100369. return false;
  100370. };
  100371. this._interactionsEnabled = true;
  100372. }
  100373. };
  100374. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  100375. get: function () {
  100376. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  100377. },
  100378. enumerable: true,
  100379. configurable: true
  100380. });
  100381. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  100382. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  100383. if (this._floorMeshesCollection[i].id === mesh.id) {
  100384. return true;
  100385. }
  100386. }
  100387. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  100388. return true;
  100389. }
  100390. return false;
  100391. };
  100392. /**
  100393. * Adds a floor mesh to be used for teleportation.
  100394. * @param floorMesh the mesh to be used for teleportation.
  100395. */
  100396. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  100397. if (!this._floorMeshesCollection) {
  100398. return;
  100399. }
  100400. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  100401. return;
  100402. }
  100403. this._floorMeshesCollection.push(floorMesh);
  100404. };
  100405. /**
  100406. * Removes a floor mesh from being used for teleportation.
  100407. * @param floorMesh the mesh to be removed.
  100408. */
  100409. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  100410. if (!this._floorMeshesCollection) {
  100411. return;
  100412. }
  100413. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  100414. if (meshIndex !== -1) {
  100415. this._floorMeshesCollection.splice(meshIndex, 1);
  100416. }
  100417. };
  100418. /**
  100419. * Enables interactions and teleportation using the VR controllers and gaze.
  100420. * @param vrTeleportationOptions options to modify teleportation behavior.
  100421. */
  100422. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  100423. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  100424. if (!this._teleportationInitialized) {
  100425. this._teleportationRequested = true;
  100426. this.enableInteractions();
  100427. if (vrTeleportationOptions.floorMeshName) {
  100428. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  100429. }
  100430. if (vrTeleportationOptions.floorMeshes) {
  100431. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  100432. }
  100433. if (this._leftController != null) {
  100434. this._enableTeleportationOnController(this._leftController);
  100435. }
  100436. if (this._rightController != null) {
  100437. this._enableTeleportationOnController(this._rightController);
  100438. }
  100439. // Creates an image processing post process for the vignette not relying
  100440. // on the main scene configuration for image processing to reduce setup and spaces
  100441. // (gamma/linear) conflicts.
  100442. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  100443. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  100444. imageProcessingConfiguration.vignetteEnabled = true;
  100445. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  100446. this._webVRCamera.detachPostProcess(this._postProcessMove);
  100447. this._teleportationInitialized = true;
  100448. if (this._isDefaultTeleportationTarget) {
  100449. this._createTeleportationCircles();
  100450. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  100451. }
  100452. }
  100453. };
  100454. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  100455. var _this = this;
  100456. var controllerMesh = controller.webVRController.mesh;
  100457. if (controllerMesh) {
  100458. controller._interactionsEnabled = true;
  100459. controller._activatePointer();
  100460. if (this.webVROptions.laserToggle) {
  100461. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  100462. // Enabling / disabling laserPointer
  100463. if (_this._displayLaserPointer && stateObject.value === 1) {
  100464. if (controller._activePointer) {
  100465. controller._deactivatePointer();
  100466. }
  100467. else {
  100468. controller._activatePointer();
  100469. }
  100470. if (_this.displayGaze) {
  100471. controller._gazeTracker.isVisible = controller._activePointer;
  100472. }
  100473. }
  100474. });
  100475. }
  100476. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  100477. var gazer = controller;
  100478. if (_this._noControllerIsActive) {
  100479. gazer = _this._cameraGazer;
  100480. }
  100481. if (!gazer._pointerDownOnMeshAsked) {
  100482. if (stateObject.value > _this._padSensibilityUp) {
  100483. gazer._selectionPointerDown();
  100484. }
  100485. }
  100486. else if (stateObject.value < _this._padSensibilityDown) {
  100487. gazer._selectionPointerUp();
  100488. }
  100489. });
  100490. }
  100491. };
  100492. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  100493. // Dont teleport if another gaze already requested teleportation
  100494. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  100495. return;
  100496. }
  100497. if (!gazer._teleportationRequestInitiated) {
  100498. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  100499. gazer._activatePointer();
  100500. gazer._teleportationRequestInitiated = true;
  100501. }
  100502. }
  100503. else {
  100504. // Listening to the proper controller values changes to confirm teleportation
  100505. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  100506. if (this._teleportActive) {
  100507. this.teleportCamera(this._haloCenter);
  100508. }
  100509. gazer._teleportationRequestInitiated = false;
  100510. }
  100511. }
  100512. };
  100513. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  100514. // Only rotate when user is not currently selecting a teleportation location
  100515. if (gazer._teleportationRequestInitiated) {
  100516. return;
  100517. }
  100518. if (!gazer._rotationLeftAsked) {
  100519. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  100520. gazer._rotationLeftAsked = true;
  100521. if (this._rotationAllowed) {
  100522. this._rotateCamera(false);
  100523. }
  100524. }
  100525. }
  100526. else {
  100527. if (stateObject.x > -this._padSensibilityDown) {
  100528. gazer._rotationLeftAsked = false;
  100529. }
  100530. }
  100531. if (!gazer._rotationRightAsked) {
  100532. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  100533. gazer._rotationRightAsked = true;
  100534. if (this._rotationAllowed) {
  100535. this._rotateCamera(true);
  100536. }
  100537. }
  100538. }
  100539. else {
  100540. if (stateObject.x < this._padSensibilityDown) {
  100541. gazer._rotationRightAsked = false;
  100542. }
  100543. }
  100544. };
  100545. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  100546. // Only teleport backwards when user is not currently selecting a teleportation location
  100547. if (gazer._teleportationRequestInitiated) {
  100548. return;
  100549. }
  100550. // Teleport backwards
  100551. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  100552. if (!gazer._teleportationBackRequestInitiated) {
  100553. if (!this.currentVRCamera) {
  100554. return;
  100555. }
  100556. // Get rotation and position of the current camera
  100557. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  100558. var position = this.currentVRCamera.position;
  100559. // If the camera has device position, use that instead
  100560. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  100561. rotation = this.currentVRCamera.deviceRotationQuaternion;
  100562. position = this.currentVRCamera.devicePosition;
  100563. }
  100564. // Get matrix with only the y rotation of the device rotation
  100565. rotation.toEulerAnglesToRef(this._workingVector);
  100566. this._workingVector.z = 0;
  100567. this._workingVector.x = 0;
  100568. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  100569. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  100570. // Rotate backwards ray by device rotation to cast at the ground behind the user
  100571. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  100572. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  100573. var ray = new BABYLON.Ray(position, this._workingVector);
  100574. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  100575. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  100576. this.teleportCamera(hit.pickedPoint);
  100577. }
  100578. gazer._teleportationBackRequestInitiated = true;
  100579. }
  100580. }
  100581. else {
  100582. gazer._teleportationBackRequestInitiated = false;
  100583. }
  100584. };
  100585. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  100586. var _this = this;
  100587. var controllerMesh = controller.webVRController.mesh;
  100588. if (controllerMesh) {
  100589. if (!controller._interactionsEnabled) {
  100590. this._enableInteractionOnController(controller);
  100591. }
  100592. controller._interactionsEnabled = true;
  100593. controller._teleportationEnabled = true;
  100594. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  100595. controller._dpadPressed = false;
  100596. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  100597. controller._dpadPressed = stateObject.pressed;
  100598. if (!controller._dpadPressed) {
  100599. controller._rotationLeftAsked = false;
  100600. controller._rotationRightAsked = false;
  100601. controller._teleportationBackRequestInitiated = false;
  100602. }
  100603. });
  100604. }
  100605. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  100606. if (_this.teleportationEnabled) {
  100607. _this._checkTeleportBackwards(stateObject, controller);
  100608. _this._checkTeleportWithRay(stateObject, controller);
  100609. }
  100610. _this._checkRotate(stateObject, controller);
  100611. });
  100612. }
  100613. };
  100614. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  100615. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  100616. this._teleportationTarget.isPickable = false;
  100617. var length = 512;
  100618. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  100619. dynamicTexture.hasAlpha = true;
  100620. var context = dynamicTexture.getContext();
  100621. var centerX = length / 2;
  100622. var centerY = length / 2;
  100623. var radius = 200;
  100624. context.beginPath();
  100625. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  100626. context.fillStyle = this._teleportationFillColor;
  100627. context.fill();
  100628. context.lineWidth = 10;
  100629. context.strokeStyle = this._teleportationBorderColor;
  100630. context.stroke();
  100631. context.closePath();
  100632. dynamicTexture.update();
  100633. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  100634. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  100635. this._teleportationTarget.material = teleportationCircleMaterial;
  100636. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  100637. torus.isPickable = false;
  100638. torus.parent = this._teleportationTarget;
  100639. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  100640. var keys = [];
  100641. keys.push({
  100642. frame: 0,
  100643. value: 0
  100644. });
  100645. keys.push({
  100646. frame: 30,
  100647. value: 0.4
  100648. });
  100649. keys.push({
  100650. frame: 60,
  100651. value: 0
  100652. });
  100653. animationInnerCircle.setKeys(keys);
  100654. var easingFunction = new BABYLON.SineEase();
  100655. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  100656. animationInnerCircle.setEasingFunction(easingFunction);
  100657. torus.animations = [];
  100658. torus.animations.push(animationInnerCircle);
  100659. this._scene.beginAnimation(torus, 0, 60, true);
  100660. this._hideTeleportationTarget();
  100661. };
  100662. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  100663. this._teleportActive = true;
  100664. if (this._teleportationInitialized) {
  100665. this._teleportationTarget.isVisible = true;
  100666. if (this._isDefaultTeleportationTarget) {
  100667. this._teleportationTarget.getChildren()[0].isVisible = true;
  100668. }
  100669. }
  100670. };
  100671. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  100672. this._teleportActive = false;
  100673. if (this._teleportationInitialized) {
  100674. this._teleportationTarget.isVisible = false;
  100675. if (this._isDefaultTeleportationTarget) {
  100676. this._teleportationTarget.getChildren()[0].isVisible = false;
  100677. }
  100678. }
  100679. };
  100680. VRExperienceHelper.prototype._rotateCamera = function (right) {
  100681. var _this = this;
  100682. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  100683. return;
  100684. }
  100685. if (right) {
  100686. this._rotationAngle++;
  100687. }
  100688. else {
  100689. this._rotationAngle--;
  100690. }
  100691. this.currentVRCamera.animations = [];
  100692. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  100693. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100694. var animationRotationKeys = [];
  100695. animationRotationKeys.push({
  100696. frame: 0,
  100697. value: this.currentVRCamera.rotationQuaternion
  100698. });
  100699. animationRotationKeys.push({
  100700. frame: 6,
  100701. value: target
  100702. });
  100703. animationRotation.setKeys(animationRotationKeys);
  100704. animationRotation.setEasingFunction(this._circleEase);
  100705. this.currentVRCamera.animations.push(animationRotation);
  100706. this._postProcessMove.animations = [];
  100707. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100708. var vignetteWeightKeys = [];
  100709. vignetteWeightKeys.push({
  100710. frame: 0,
  100711. value: 0
  100712. });
  100713. vignetteWeightKeys.push({
  100714. frame: 3,
  100715. value: 4
  100716. });
  100717. vignetteWeightKeys.push({
  100718. frame: 6,
  100719. value: 0
  100720. });
  100721. animationPP.setKeys(vignetteWeightKeys);
  100722. animationPP.setEasingFunction(this._circleEase);
  100723. this._postProcessMove.animations.push(animationPP);
  100724. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100725. var vignetteStretchKeys = [];
  100726. vignetteStretchKeys.push({
  100727. frame: 0,
  100728. value: 0
  100729. });
  100730. vignetteStretchKeys.push({
  100731. frame: 3,
  100732. value: 10
  100733. });
  100734. vignetteStretchKeys.push({
  100735. frame: 6,
  100736. value: 0
  100737. });
  100738. animationPP2.setKeys(vignetteStretchKeys);
  100739. animationPP2.setEasingFunction(this._circleEase);
  100740. this._postProcessMove.animations.push(animationPP2);
  100741. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  100742. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  100743. this._postProcessMove.samples = 4;
  100744. this._webVRCamera.attachPostProcess(this._postProcessMove);
  100745. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  100746. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  100747. });
  100748. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  100749. };
  100750. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  100751. if (hit.pickedPoint) {
  100752. if (gazer._teleportationRequestInitiated) {
  100753. this._displayTeleportationTarget();
  100754. this._haloCenter.copyFrom(hit.pickedPoint);
  100755. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  100756. }
  100757. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  100758. if (pickNormal) {
  100759. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  100760. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  100761. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  100762. }
  100763. this._teleportationTarget.position.y += 0.1;
  100764. }
  100765. };
  100766. /**
  100767. * Teleports the users feet to the desired location
  100768. * @param location The location where the user's feet should be placed
  100769. */
  100770. VRExperienceHelper.prototype.teleportCamera = function (location) {
  100771. var _this = this;
  100772. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  100773. return;
  100774. }
  100775. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  100776. // offset of the headset from the anchor.
  100777. if (this.webVRCamera.leftCamera) {
  100778. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  100779. this._workingVector.subtractInPlace(this.webVRCamera.position);
  100780. location.subtractToRef(this._workingVector, this._workingVector);
  100781. }
  100782. else {
  100783. this._workingVector.copyFrom(location);
  100784. }
  100785. // Add height to account for user's height offset
  100786. if (this.isInVRMode) {
  100787. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  100788. }
  100789. else {
  100790. this._workingVector.y += this._defaultHeight;
  100791. }
  100792. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  100793. // Create animation from the camera's position to the new location
  100794. this.currentVRCamera.animations = [];
  100795. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100796. var animationCameraTeleportationKeys = [{
  100797. frame: 0,
  100798. value: this.currentVRCamera.position
  100799. },
  100800. {
  100801. frame: 11,
  100802. value: this._workingVector
  100803. }
  100804. ];
  100805. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  100806. animationCameraTeleportation.setEasingFunction(this._circleEase);
  100807. this.currentVRCamera.animations.push(animationCameraTeleportation);
  100808. this._postProcessMove.animations = [];
  100809. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100810. var vignetteWeightKeys = [];
  100811. vignetteWeightKeys.push({
  100812. frame: 0,
  100813. value: 0
  100814. });
  100815. vignetteWeightKeys.push({
  100816. frame: 5,
  100817. value: 8
  100818. });
  100819. vignetteWeightKeys.push({
  100820. frame: 11,
  100821. value: 0
  100822. });
  100823. animationPP.setKeys(vignetteWeightKeys);
  100824. this._postProcessMove.animations.push(animationPP);
  100825. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  100826. var vignetteStretchKeys = [];
  100827. vignetteStretchKeys.push({
  100828. frame: 0,
  100829. value: 0
  100830. });
  100831. vignetteStretchKeys.push({
  100832. frame: 5,
  100833. value: 10
  100834. });
  100835. vignetteStretchKeys.push({
  100836. frame: 11,
  100837. value: 0
  100838. });
  100839. animationPP2.setKeys(vignetteStretchKeys);
  100840. this._postProcessMove.animations.push(animationPP2);
  100841. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  100842. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  100843. this._webVRCamera.attachPostProcess(this._postProcessMove);
  100844. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  100845. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  100846. });
  100847. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  100848. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  100849. });
  100850. this._hideTeleportationTarget();
  100851. };
  100852. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  100853. if (normal) {
  100854. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  100855. if (angle < Math.PI / 2) {
  100856. normal.scaleInPlace(-1);
  100857. }
  100858. }
  100859. return normal;
  100860. };
  100861. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  100862. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  100863. return;
  100864. }
  100865. var ray = gazer._getForwardRay(this._rayLength);
  100866. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  100867. if (hit) {
  100868. // Populate the contrllers mesh that can be used for drag/drop
  100869. if (gazer._laserPointer) {
  100870. hit.originMesh = gazer._laserPointer.parent;
  100871. }
  100872. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  100873. }
  100874. gazer._currentHit = hit;
  100875. // Moving the gazeTracker on the mesh face targetted
  100876. if (hit && hit.pickedPoint) {
  100877. if (this._displayGaze) {
  100878. var multiplier = 1;
  100879. gazer._gazeTracker.isVisible = true;
  100880. if (gazer._isActionableMesh) {
  100881. multiplier = 3;
  100882. }
  100883. if (this.updateGazeTrackerScale) {
  100884. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  100885. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  100886. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  100887. }
  100888. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  100889. // To avoid z-fighting
  100890. var deltaFighting = 0.002;
  100891. if (pickNormal) {
  100892. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  100893. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  100894. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  100895. }
  100896. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  100897. if (gazer._gazeTracker.position.x < 0) {
  100898. gazer._gazeTracker.position.x += deltaFighting;
  100899. }
  100900. else {
  100901. gazer._gazeTracker.position.x -= deltaFighting;
  100902. }
  100903. if (gazer._gazeTracker.position.y < 0) {
  100904. gazer._gazeTracker.position.y += deltaFighting;
  100905. }
  100906. else {
  100907. gazer._gazeTracker.position.y -= deltaFighting;
  100908. }
  100909. if (gazer._gazeTracker.position.z < 0) {
  100910. gazer._gazeTracker.position.z += deltaFighting;
  100911. }
  100912. else {
  100913. gazer._gazeTracker.position.z -= deltaFighting;
  100914. }
  100915. }
  100916. // Changing the size of the laser pointer based on the distance from the targetted point
  100917. gazer._updatePointerDistance(hit.distance);
  100918. }
  100919. else {
  100920. gazer._updatePointerDistance();
  100921. gazer._gazeTracker.isVisible = false;
  100922. }
  100923. if (hit && hit.pickedMesh) {
  100924. // The object selected is the floor, we're in a teleportation scenario
  100925. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  100926. // Moving the teleportation area to this targetted point
  100927. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  100928. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  100929. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  100930. }
  100931. gazer._currentMeshSelected = null;
  100932. if (gazer._teleportationRequestInitiated) {
  100933. this._moveTeleportationSelectorTo(hit, gazer, ray);
  100934. }
  100935. return;
  100936. }
  100937. // If not, we're in a selection scenario
  100938. //this._teleportationAllowed = false;
  100939. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  100940. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  100941. this.onNewMeshPicked.notifyObservers(hit);
  100942. gazer._currentMeshSelected = hit.pickedMesh;
  100943. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  100944. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  100945. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  100946. gazer._isActionableMesh = true;
  100947. }
  100948. else {
  100949. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100950. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100951. gazer._isActionableMesh = false;
  100952. }
  100953. try {
  100954. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  100955. }
  100956. catch (err) {
  100957. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  100958. }
  100959. }
  100960. else {
  100961. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  100962. gazer._currentMeshSelected = null;
  100963. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100964. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100965. }
  100966. }
  100967. }
  100968. else {
  100969. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  100970. gazer._currentMeshSelected = null;
  100971. //this._teleportationAllowed = false;
  100972. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100973. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  100974. }
  100975. };
  100976. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  100977. if (mesh) {
  100978. this.onSelectedMeshUnselected.notifyObservers(mesh);
  100979. }
  100980. };
  100981. /**
  100982. * Sets the color of the laser ray from the vr controllers.
  100983. * @param color new color for the ray.
  100984. */
  100985. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  100986. if (this._leftController) {
  100987. this._leftController._setLaserPointerColor(color);
  100988. }
  100989. if (this._rightController) {
  100990. this._rightController._setLaserPointerColor(color);
  100991. }
  100992. };
  100993. /**
  100994. * Sets the color of the ray from the vr headsets gaze.
  100995. * @param color new color for the ray.
  100996. */
  100997. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  100998. if (!this._cameraGazer._gazeTracker.material) {
  100999. return;
  101000. }
  101001. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  101002. if (this._leftController) {
  101003. this._leftController._gazeTracker.material.emissiveColor = color;
  101004. }
  101005. if (this._rightController) {
  101006. this._rightController._gazeTracker.material.emissiveColor = color;
  101007. }
  101008. };
  101009. /**
  101010. * Exits VR and disposes of the vr experience helper
  101011. */
  101012. VRExperienceHelper.prototype.dispose = function () {
  101013. if (this.isInVRMode) {
  101014. this.exitVR();
  101015. }
  101016. if (this._postProcessMove) {
  101017. this._postProcessMove.dispose();
  101018. }
  101019. if (this._webVRCamera) {
  101020. this._webVRCamera.dispose();
  101021. }
  101022. if (this._vrDeviceOrientationCamera) {
  101023. this._vrDeviceOrientationCamera.dispose();
  101024. }
  101025. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  101026. document.body.removeChild(this._btnVR);
  101027. }
  101028. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  101029. this._deviceOrientationCamera.dispose();
  101030. }
  101031. if (this._cameraGazer) {
  101032. this._cameraGazer.dispose();
  101033. }
  101034. if (this._leftController) {
  101035. this._leftController.dispose();
  101036. }
  101037. if (this._rightController) {
  101038. this._rightController.dispose();
  101039. }
  101040. if (this._teleportationTarget) {
  101041. this._teleportationTarget.dispose();
  101042. }
  101043. this._floorMeshesCollection = [];
  101044. document.removeEventListener("keydown", this._onKeyDown);
  101045. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101046. window.removeEventListener("resize", this._onResize);
  101047. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  101048. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  101049. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  101050. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  101051. document.onmsfullscreenchange = null;
  101052. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  101053. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  101054. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  101055. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  101056. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  101057. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  101058. this._scene.unregisterBeforeRender(this.beforeRender);
  101059. };
  101060. /**
  101061. * Gets the name of the VRExperienceHelper class
  101062. * @returns "VRExperienceHelper"
  101063. */
  101064. VRExperienceHelper.prototype.getClassName = function () {
  101065. return "VRExperienceHelper";
  101066. };
  101067. return VRExperienceHelper;
  101068. }());
  101069. BABYLON.VRExperienceHelper = VRExperienceHelper;
  101070. })(BABYLON || (BABYLON = {}));
  101071. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  101072. // Mainly based on these 2 articles :
  101073. // 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
  101074. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  101075. var BABYLON;
  101076. (function (BABYLON) {
  101077. /**
  101078. * Defines the potential axis of a Joystick
  101079. */
  101080. var JoystickAxis;
  101081. (function (JoystickAxis) {
  101082. /** X axis */
  101083. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  101084. /** Y axis */
  101085. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  101086. /** Z axis */
  101087. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  101088. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  101089. /**
  101090. * Class used to define virtual joystick (used in touch mode)
  101091. */
  101092. var VirtualJoystick = /** @class */ (function () {
  101093. /**
  101094. * Creates a new virtual joystick
  101095. * @param leftJoystick defines that the joystick is for left hand (false by default)
  101096. */
  101097. function VirtualJoystick(leftJoystick) {
  101098. var _this = this;
  101099. if (leftJoystick) {
  101100. this._leftJoystick = true;
  101101. }
  101102. else {
  101103. this._leftJoystick = false;
  101104. }
  101105. VirtualJoystick._globalJoystickIndex++;
  101106. // By default left & right arrow keys are moving the X
  101107. // and up & down keys are moving the Y
  101108. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101109. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101110. this.reverseLeftRight = false;
  101111. this.reverseUpDown = false;
  101112. // collections of pointers
  101113. this._touches = new BABYLON.StringDictionary();
  101114. this.deltaPosition = BABYLON.Vector3.Zero();
  101115. this._joystickSensibility = 25;
  101116. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101117. this._onResize = function (evt) {
  101118. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101119. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101120. if (VirtualJoystick.vjCanvas) {
  101121. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  101122. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  101123. }
  101124. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  101125. };
  101126. // injecting a canvas element on top of the canvas 3D game
  101127. if (!VirtualJoystick.vjCanvas) {
  101128. window.addEventListener("resize", this._onResize, false);
  101129. VirtualJoystick.vjCanvas = document.createElement("canvas");
  101130. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  101131. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  101132. VirtualJoystick.vjCanvas.width = window.innerWidth;
  101133. VirtualJoystick.vjCanvas.height = window.innerHeight;
  101134. VirtualJoystick.vjCanvas.style.width = "100%";
  101135. VirtualJoystick.vjCanvas.style.height = "100%";
  101136. VirtualJoystick.vjCanvas.style.position = "absolute";
  101137. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  101138. VirtualJoystick.vjCanvas.style.top = "0px";
  101139. VirtualJoystick.vjCanvas.style.left = "0px";
  101140. VirtualJoystick.vjCanvas.style.zIndex = "5";
  101141. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  101142. // Support for jQuery PEP polyfill
  101143. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  101144. var context = VirtualJoystick.vjCanvas.getContext('2d');
  101145. if (!context) {
  101146. throw new Error("Unable to create canvas for virtual joystick");
  101147. }
  101148. VirtualJoystick.vjCanvasContext = context;
  101149. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  101150. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101151. document.body.appendChild(VirtualJoystick.vjCanvas);
  101152. }
  101153. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  101154. this.pressed = false;
  101155. // default joystick color
  101156. this._joystickColor = "cyan";
  101157. this._joystickPointerID = -1;
  101158. // current joystick position
  101159. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  101160. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  101161. // origin joystick position
  101162. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  101163. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  101164. this._onPointerDownHandlerRef = function (evt) {
  101165. _this._onPointerDown(evt);
  101166. };
  101167. this._onPointerMoveHandlerRef = function (evt) {
  101168. _this._onPointerMove(evt);
  101169. };
  101170. this._onPointerUpHandlerRef = function (evt) {
  101171. _this._onPointerUp(evt);
  101172. };
  101173. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  101174. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  101175. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  101176. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  101177. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  101178. evt.preventDefault(); // Disables system menu
  101179. }, false);
  101180. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101181. }
  101182. /**
  101183. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  101184. * @param newJoystickSensibility defines the new sensibility
  101185. */
  101186. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  101187. this._joystickSensibility = newJoystickSensibility;
  101188. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  101189. };
  101190. VirtualJoystick.prototype._onPointerDown = function (e) {
  101191. var positionOnScreenCondition;
  101192. e.preventDefault();
  101193. if (this._leftJoystick === true) {
  101194. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  101195. }
  101196. else {
  101197. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  101198. }
  101199. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  101200. // First contact will be dedicated to the virtual joystick
  101201. this._joystickPointerID = e.pointerId;
  101202. this._joystickPointerStartPos.x = e.clientX;
  101203. this._joystickPointerStartPos.y = e.clientY;
  101204. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  101205. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  101206. this._deltaJoystickVector.x = 0;
  101207. this._deltaJoystickVector.y = 0;
  101208. this.pressed = true;
  101209. this._touches.add(e.pointerId.toString(), e);
  101210. }
  101211. else {
  101212. // You can only trigger the action buttons with a joystick declared
  101213. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  101214. this._action();
  101215. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  101216. }
  101217. }
  101218. };
  101219. VirtualJoystick.prototype._onPointerMove = function (e) {
  101220. // If the current pointer is the one associated to the joystick (first touch contact)
  101221. if (this._joystickPointerID == e.pointerId) {
  101222. this._joystickPointerPos.x = e.clientX;
  101223. this._joystickPointerPos.y = e.clientY;
  101224. this._deltaJoystickVector = this._joystickPointerPos.clone();
  101225. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  101226. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  101227. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  101228. switch (this._axisTargetedByLeftAndRight) {
  101229. case JoystickAxis.X:
  101230. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  101231. break;
  101232. case JoystickAxis.Y:
  101233. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  101234. break;
  101235. case JoystickAxis.Z:
  101236. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  101237. break;
  101238. }
  101239. var directionUpDown = this.reverseUpDown ? 1 : -1;
  101240. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  101241. switch (this._axisTargetedByUpAndDown) {
  101242. case JoystickAxis.X:
  101243. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  101244. break;
  101245. case JoystickAxis.Y:
  101246. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  101247. break;
  101248. case JoystickAxis.Z:
  101249. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  101250. break;
  101251. }
  101252. }
  101253. else {
  101254. var data = this._touches.get(e.pointerId.toString());
  101255. if (data) {
  101256. data.x = e.clientX;
  101257. data.y = e.clientY;
  101258. }
  101259. }
  101260. };
  101261. VirtualJoystick.prototype._onPointerUp = function (e) {
  101262. if (this._joystickPointerID == e.pointerId) {
  101263. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  101264. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  101265. this._joystickPointerID = -1;
  101266. this.pressed = false;
  101267. }
  101268. else {
  101269. var touch = this._touches.get(e.pointerId.toString());
  101270. if (touch) {
  101271. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101272. }
  101273. }
  101274. this._deltaJoystickVector.x = 0;
  101275. this._deltaJoystickVector.y = 0;
  101276. this._touches.remove(e.pointerId.toString());
  101277. };
  101278. /**
  101279. * Change the color of the virtual joystick
  101280. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  101281. */
  101282. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  101283. this._joystickColor = newColor;
  101284. };
  101285. /**
  101286. * Defines a callback to call when the joystick is touched
  101287. * @param action defines the callback
  101288. */
  101289. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  101290. this._action = action;
  101291. };
  101292. /**
  101293. * Defines which axis you'd like to control for left & right
  101294. * @param axis defines the axis to use
  101295. */
  101296. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  101297. switch (axis) {
  101298. case JoystickAxis.X:
  101299. case JoystickAxis.Y:
  101300. case JoystickAxis.Z:
  101301. this._axisTargetedByLeftAndRight = axis;
  101302. break;
  101303. default:
  101304. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  101305. break;
  101306. }
  101307. };
  101308. /**
  101309. * Defines which axis you'd like to control for up & down
  101310. * @param axis defines the axis to use
  101311. */
  101312. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  101313. switch (axis) {
  101314. case JoystickAxis.X:
  101315. case JoystickAxis.Y:
  101316. case JoystickAxis.Z:
  101317. this._axisTargetedByUpAndDown = axis;
  101318. break;
  101319. default:
  101320. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  101321. break;
  101322. }
  101323. };
  101324. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  101325. var _this = this;
  101326. if (this.pressed) {
  101327. this._touches.forEach(function (key, touch) {
  101328. if (touch.pointerId === _this._joystickPointerID) {
  101329. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  101330. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  101331. VirtualJoystick.vjCanvasContext.beginPath();
  101332. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101333. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101334. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  101335. VirtualJoystick.vjCanvasContext.stroke();
  101336. VirtualJoystick.vjCanvasContext.closePath();
  101337. VirtualJoystick.vjCanvasContext.beginPath();
  101338. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101339. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  101340. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  101341. VirtualJoystick.vjCanvasContext.stroke();
  101342. VirtualJoystick.vjCanvasContext.closePath();
  101343. VirtualJoystick.vjCanvasContext.beginPath();
  101344. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  101345. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  101346. VirtualJoystick.vjCanvasContext.stroke();
  101347. VirtualJoystick.vjCanvasContext.closePath();
  101348. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  101349. }
  101350. else {
  101351. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  101352. VirtualJoystick.vjCanvasContext.beginPath();
  101353. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  101354. VirtualJoystick.vjCanvasContext.beginPath();
  101355. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  101356. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  101357. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  101358. VirtualJoystick.vjCanvasContext.stroke();
  101359. VirtualJoystick.vjCanvasContext.closePath();
  101360. touch.prevX = touch.x;
  101361. touch.prevY = touch.y;
  101362. }
  101363. ;
  101364. });
  101365. }
  101366. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  101367. };
  101368. /**
  101369. * Release internal HTML canvas
  101370. */
  101371. VirtualJoystick.prototype.releaseCanvas = function () {
  101372. if (VirtualJoystick.vjCanvas) {
  101373. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  101374. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  101375. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  101376. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  101377. window.removeEventListener("resize", this._onResize);
  101378. document.body.removeChild(VirtualJoystick.vjCanvas);
  101379. VirtualJoystick.vjCanvas = null;
  101380. }
  101381. };
  101382. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  101383. VirtualJoystick._globalJoystickIndex = 0;
  101384. return VirtualJoystick;
  101385. }());
  101386. BABYLON.VirtualJoystick = VirtualJoystick;
  101387. })(BABYLON || (BABYLON = {}));
  101388. //# sourceMappingURL=babylon.virtualJoystick.js.map
  101389. var BABYLON;
  101390. (function (BABYLON) {
  101391. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  101392. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  101393. });
  101394. /**
  101395. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  101396. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101397. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101398. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101399. */
  101400. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  101401. __extends(VirtualJoysticksCamera, _super);
  101402. /**
  101403. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  101404. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  101405. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  101406. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  101407. * @param name Define the name of the camera in the scene
  101408. * @param position Define the start position of the camera in the scene
  101409. * @param scene Define the scene the camera belongs to
  101410. */
  101411. function VirtualJoysticksCamera(name, position, scene) {
  101412. var _this = _super.call(this, name, position, scene) || this;
  101413. _this.inputs.addVirtualJoystick();
  101414. return _this;
  101415. }
  101416. /**
  101417. * Gets the current object class name.
  101418. * @return the class name
  101419. */
  101420. VirtualJoysticksCamera.prototype.getClassName = function () {
  101421. return "VirtualJoysticksCamera";
  101422. };
  101423. return VirtualJoysticksCamera;
  101424. }(BABYLON.FreeCamera));
  101425. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  101426. })(BABYLON || (BABYLON = {}));
  101427. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  101428. var BABYLON;
  101429. (function (BABYLON) {
  101430. /**
  101431. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  101432. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  101433. */
  101434. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  101435. function FreeCameraVirtualJoystickInput() {
  101436. }
  101437. /**
  101438. * Gets the left stick of the virtual joystick.
  101439. * @returns The virtual Joystick
  101440. */
  101441. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  101442. return this._leftjoystick;
  101443. };
  101444. /**
  101445. * Gets the right stick of the virtual joystick.
  101446. * @returns The virtual Joystick
  101447. */
  101448. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  101449. return this._rightjoystick;
  101450. };
  101451. /**
  101452. * Update the current camera state depending on the inputs that have been used this frame.
  101453. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  101454. */
  101455. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  101456. if (this._leftjoystick) {
  101457. var camera = this.camera;
  101458. var speed = camera._computeLocalCameraSpeed() * 50;
  101459. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  101460. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  101461. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  101462. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  101463. if (!this._leftjoystick.pressed) {
  101464. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  101465. }
  101466. if (!this._rightjoystick.pressed) {
  101467. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  101468. }
  101469. }
  101470. };
  101471. /**
  101472. * Attach the input controls to a specific dom element to get the input from.
  101473. * @param element Defines the element the controls should be listened from
  101474. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  101475. */
  101476. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  101477. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  101478. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  101479. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  101480. this._leftjoystick.setJoystickSensibility(0.15);
  101481. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  101482. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  101483. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  101484. this._rightjoystick.reverseUpDown = true;
  101485. this._rightjoystick.setJoystickSensibility(0.05);
  101486. this._rightjoystick.setJoystickColor("yellow");
  101487. };
  101488. /**
  101489. * Detach the current controls from the specified dom element.
  101490. * @param element Defines the element to stop listening the inputs from
  101491. */
  101492. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  101493. this._leftjoystick.releaseCanvas();
  101494. this._rightjoystick.releaseCanvas();
  101495. };
  101496. /**
  101497. * Gets the class name of the current intput.
  101498. * @returns the class name
  101499. */
  101500. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  101501. return "FreeCameraVirtualJoystickInput";
  101502. };
  101503. /**
  101504. * Get the friendly name associated with the input class.
  101505. * @returns the input friendly name
  101506. */
  101507. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  101508. return "virtualJoystick";
  101509. };
  101510. return FreeCameraVirtualJoystickInput;
  101511. }());
  101512. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  101513. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  101514. })(BABYLON || (BABYLON = {}));
  101515. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  101516. var BABYLON;
  101517. (function (BABYLON) {
  101518. var SimplificationSettings = /** @class */ (function () {
  101519. function SimplificationSettings(quality, distance, optimizeMesh) {
  101520. this.quality = quality;
  101521. this.distance = distance;
  101522. this.optimizeMesh = optimizeMesh;
  101523. }
  101524. return SimplificationSettings;
  101525. }());
  101526. BABYLON.SimplificationSettings = SimplificationSettings;
  101527. var SimplificationQueue = /** @class */ (function () {
  101528. function SimplificationQueue() {
  101529. this.running = false;
  101530. this._simplificationArray = [];
  101531. }
  101532. SimplificationQueue.prototype.addTask = function (task) {
  101533. this._simplificationArray.push(task);
  101534. };
  101535. SimplificationQueue.prototype.executeNext = function () {
  101536. var task = this._simplificationArray.pop();
  101537. if (task) {
  101538. this.running = true;
  101539. this.runSimplification(task);
  101540. }
  101541. else {
  101542. this.running = false;
  101543. }
  101544. };
  101545. SimplificationQueue.prototype.runSimplification = function (task) {
  101546. var _this = this;
  101547. if (task.parallelProcessing) {
  101548. //parallel simplifier
  101549. task.settings.forEach(function (setting) {
  101550. var simplifier = _this.getSimplifier(task);
  101551. simplifier.simplify(setting, function (newMesh) {
  101552. task.mesh.addLODLevel(setting.distance, newMesh);
  101553. newMesh.isVisible = true;
  101554. //check if it is the last
  101555. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  101556. //all done, run the success callback.
  101557. task.successCallback();
  101558. }
  101559. _this.executeNext();
  101560. });
  101561. });
  101562. }
  101563. else {
  101564. //single simplifier.
  101565. var simplifier = this.getSimplifier(task);
  101566. var runDecimation = function (setting, callback) {
  101567. simplifier.simplify(setting, function (newMesh) {
  101568. task.mesh.addLODLevel(setting.distance, newMesh);
  101569. newMesh.isVisible = true;
  101570. //run the next quality level
  101571. callback();
  101572. });
  101573. };
  101574. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  101575. runDecimation(task.settings[loop.index], function () {
  101576. loop.executeNext();
  101577. });
  101578. }, function () {
  101579. //execution ended, run the success callback.
  101580. if (task.successCallback) {
  101581. task.successCallback();
  101582. }
  101583. _this.executeNext();
  101584. });
  101585. }
  101586. };
  101587. SimplificationQueue.prototype.getSimplifier = function (task) {
  101588. switch (task.simplificationType) {
  101589. case SimplificationType.QUADRATIC:
  101590. default:
  101591. return new QuadraticErrorSimplification(task.mesh);
  101592. }
  101593. };
  101594. return SimplificationQueue;
  101595. }());
  101596. BABYLON.SimplificationQueue = SimplificationQueue;
  101597. /**
  101598. * The implemented types of simplification
  101599. * At the moment only Quadratic Error Decimation is implemented
  101600. */
  101601. var SimplificationType;
  101602. (function (SimplificationType) {
  101603. /** Quadratic error decimation */
  101604. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  101605. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  101606. var DecimationTriangle = /** @class */ (function () {
  101607. function DecimationTriangle(vertices) {
  101608. this.vertices = vertices;
  101609. this.error = new Array(4);
  101610. this.deleted = false;
  101611. this.isDirty = false;
  101612. this.deletePending = false;
  101613. this.borderFactor = 0;
  101614. }
  101615. return DecimationTriangle;
  101616. }());
  101617. BABYLON.DecimationTriangle = DecimationTriangle;
  101618. var DecimationVertex = /** @class */ (function () {
  101619. function DecimationVertex(position, id) {
  101620. this.position = position;
  101621. this.id = id;
  101622. this.isBorder = true;
  101623. this.q = new QuadraticMatrix();
  101624. this.triangleCount = 0;
  101625. this.triangleStart = 0;
  101626. this.originalOffsets = [];
  101627. }
  101628. DecimationVertex.prototype.updatePosition = function (newPosition) {
  101629. this.position.copyFrom(newPosition);
  101630. };
  101631. return DecimationVertex;
  101632. }());
  101633. BABYLON.DecimationVertex = DecimationVertex;
  101634. var QuadraticMatrix = /** @class */ (function () {
  101635. function QuadraticMatrix(data) {
  101636. this.data = new Array(10);
  101637. for (var i = 0; i < 10; ++i) {
  101638. if (data && data[i]) {
  101639. this.data[i] = data[i];
  101640. }
  101641. else {
  101642. this.data[i] = 0;
  101643. }
  101644. }
  101645. }
  101646. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  101647. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  101648. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  101649. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  101650. return det;
  101651. };
  101652. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  101653. for (var i = 0; i < 10; ++i) {
  101654. this.data[i] += matrix.data[i];
  101655. }
  101656. };
  101657. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  101658. for (var i = 0; i < 10; ++i) {
  101659. this.data[i] += data[i];
  101660. }
  101661. };
  101662. QuadraticMatrix.prototype.add = function (matrix) {
  101663. var m = new QuadraticMatrix();
  101664. for (var i = 0; i < 10; ++i) {
  101665. m.data[i] = this.data[i] + matrix.data[i];
  101666. }
  101667. return m;
  101668. };
  101669. QuadraticMatrix.FromData = function (a, b, c, d) {
  101670. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  101671. };
  101672. //returning an array to avoid garbage collection
  101673. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  101674. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  101675. };
  101676. return QuadraticMatrix;
  101677. }());
  101678. BABYLON.QuadraticMatrix = QuadraticMatrix;
  101679. var Reference = /** @class */ (function () {
  101680. function Reference(vertexId, triangleId) {
  101681. this.vertexId = vertexId;
  101682. this.triangleId = triangleId;
  101683. }
  101684. return Reference;
  101685. }());
  101686. BABYLON.Reference = Reference;
  101687. /**
  101688. * An implementation of the Quadratic Error simplification algorithm.
  101689. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  101690. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  101691. * @author RaananW
  101692. */
  101693. var QuadraticErrorSimplification = /** @class */ (function () {
  101694. function QuadraticErrorSimplification(_mesh) {
  101695. this._mesh = _mesh;
  101696. this.syncIterations = 5000;
  101697. this.aggressiveness = 7;
  101698. this.decimationIterations = 100;
  101699. this.boundingBoxEpsilon = BABYLON.Epsilon;
  101700. }
  101701. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  101702. var _this = this;
  101703. this.initDecimatedMesh();
  101704. //iterating through the submeshes array, one after the other.
  101705. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  101706. _this.initWithMesh(loop.index, function () {
  101707. _this.runDecimation(settings, loop.index, function () {
  101708. loop.executeNext();
  101709. });
  101710. }, settings.optimizeMesh);
  101711. }, function () {
  101712. setTimeout(function () {
  101713. successCallback(_this._reconstructedMesh);
  101714. }, 0);
  101715. });
  101716. };
  101717. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  101718. var _this = this;
  101719. var targetCount = ~~(this.triangles.length * settings.quality);
  101720. var deletedTriangles = 0;
  101721. var triangleCount = this.triangles.length;
  101722. var iterationFunction = function (iteration, callback) {
  101723. setTimeout(function () {
  101724. if (iteration % 5 === 0) {
  101725. _this.updateMesh(iteration === 0);
  101726. }
  101727. for (var i = 0; i < _this.triangles.length; ++i) {
  101728. _this.triangles[i].isDirty = false;
  101729. }
  101730. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  101731. var trianglesIterator = function (i) {
  101732. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  101733. var t = _this.triangles[tIdx];
  101734. if (!t)
  101735. return;
  101736. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  101737. return;
  101738. }
  101739. for (var j = 0; j < 3; ++j) {
  101740. if (t.error[j] < threshold) {
  101741. var deleted0 = [];
  101742. var deleted1 = [];
  101743. var v0 = t.vertices[j];
  101744. var v1 = t.vertices[(j + 1) % 3];
  101745. if (v0.isBorder || v1.isBorder)
  101746. continue;
  101747. var p = BABYLON.Vector3.Zero();
  101748. var n = BABYLON.Vector3.Zero();
  101749. var uv = BABYLON.Vector2.Zero();
  101750. var color = new BABYLON.Color4(0, 0, 0, 1);
  101751. _this.calculateError(v0, v1, p, n, uv, color);
  101752. var delTr = new Array();
  101753. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  101754. continue;
  101755. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  101756. continue;
  101757. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  101758. continue;
  101759. var uniqueArray = new Array();
  101760. delTr.forEach(function (deletedT) {
  101761. if (uniqueArray.indexOf(deletedT) === -1) {
  101762. deletedT.deletePending = true;
  101763. uniqueArray.push(deletedT);
  101764. }
  101765. });
  101766. if (uniqueArray.length % 2 !== 0) {
  101767. continue;
  101768. }
  101769. v0.q = v1.q.add(v0.q);
  101770. v0.updatePosition(p);
  101771. var tStart = _this.references.length;
  101772. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  101773. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  101774. var tCount = _this.references.length - tStart;
  101775. if (tCount <= v0.triangleCount) {
  101776. if (tCount) {
  101777. for (var c = 0; c < tCount; c++) {
  101778. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  101779. }
  101780. }
  101781. }
  101782. else {
  101783. v0.triangleStart = tStart;
  101784. }
  101785. v0.triangleCount = tCount;
  101786. break;
  101787. }
  101788. }
  101789. };
  101790. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  101791. }, 0);
  101792. };
  101793. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  101794. if (triangleCount - deletedTriangles <= targetCount)
  101795. loop.breakLoop();
  101796. else {
  101797. iterationFunction(loop.index, function () {
  101798. loop.executeNext();
  101799. });
  101800. }
  101801. }, function () {
  101802. setTimeout(function () {
  101803. //reconstruct this part of the mesh
  101804. _this.reconstructMesh(submeshIndex);
  101805. successCallback();
  101806. }, 0);
  101807. });
  101808. };
  101809. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  101810. var _this = this;
  101811. this.vertices = [];
  101812. this.triangles = [];
  101813. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  101814. var indices = this._mesh.getIndices();
  101815. var submesh = this._mesh.subMeshes[submeshIndex];
  101816. var findInVertices = function (positionToSearch) {
  101817. if (optimizeMesh) {
  101818. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  101819. if (_this.vertices[ii].position.equals(positionToSearch)) {
  101820. return _this.vertices[ii];
  101821. }
  101822. }
  101823. }
  101824. return null;
  101825. };
  101826. var vertexReferences = [];
  101827. var vertexInit = function (i) {
  101828. if (!positionData) {
  101829. return;
  101830. }
  101831. var offset = i + submesh.verticesStart;
  101832. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  101833. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  101834. vertex.originalOffsets.push(offset);
  101835. if (vertex.id === _this.vertices.length) {
  101836. _this.vertices.push(vertex);
  101837. }
  101838. vertexReferences.push(vertex.id);
  101839. };
  101840. //var totalVertices = mesh.getTotalVertices();
  101841. var totalVertices = submesh.verticesCount;
  101842. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  101843. var indicesInit = function (i) {
  101844. if (!indices) {
  101845. return;
  101846. }
  101847. var offset = (submesh.indexStart / 3) + i;
  101848. var pos = (offset * 3);
  101849. var i0 = indices[pos + 0];
  101850. var i1 = indices[pos + 1];
  101851. var i2 = indices[pos + 2];
  101852. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  101853. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  101854. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  101855. var triangle = new DecimationTriangle([v0, v1, v2]);
  101856. triangle.originalOffset = pos;
  101857. _this.triangles.push(triangle);
  101858. };
  101859. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  101860. _this.init(callback);
  101861. });
  101862. });
  101863. };
  101864. QuadraticErrorSimplification.prototype.init = function (callback) {
  101865. var _this = this;
  101866. var triangleInit1 = function (i) {
  101867. var t = _this.triangles[i];
  101868. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  101869. for (var j = 0; j < 3; j++) {
  101870. 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))));
  101871. }
  101872. };
  101873. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  101874. var triangleInit2 = function (i) {
  101875. var t = _this.triangles[i];
  101876. for (var j = 0; j < 3; ++j) {
  101877. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  101878. }
  101879. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  101880. };
  101881. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  101882. callback();
  101883. });
  101884. });
  101885. };
  101886. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  101887. var newTriangles = [];
  101888. var i;
  101889. for (i = 0; i < this.vertices.length; ++i) {
  101890. this.vertices[i].triangleCount = 0;
  101891. }
  101892. var t;
  101893. var j;
  101894. for (i = 0; i < this.triangles.length; ++i) {
  101895. if (!this.triangles[i].deleted) {
  101896. t = this.triangles[i];
  101897. for (j = 0; j < 3; ++j) {
  101898. t.vertices[j].triangleCount = 1;
  101899. }
  101900. newTriangles.push(t);
  101901. }
  101902. }
  101903. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  101904. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  101905. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  101906. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  101907. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  101908. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  101909. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  101910. var vertexCount = 0;
  101911. for (i = 0; i < this.vertices.length; ++i) {
  101912. var vertex = this.vertices[i];
  101913. vertex.id = vertexCount;
  101914. if (vertex.triangleCount) {
  101915. vertex.originalOffsets.forEach(function (originalOffset) {
  101916. if (!normalData) {
  101917. return;
  101918. }
  101919. newPositionData.push(vertex.position.x);
  101920. newPositionData.push(vertex.position.y);
  101921. newPositionData.push(vertex.position.z);
  101922. newNormalData.push(normalData[originalOffset * 3]);
  101923. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  101924. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  101925. if (uvs && uvs.length) {
  101926. newUVsData.push(uvs[(originalOffset * 2)]);
  101927. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  101928. }
  101929. else if (colorsData && colorsData.length) {
  101930. newColorsData.push(colorsData[(originalOffset * 4)]);
  101931. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  101932. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  101933. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  101934. }
  101935. ++vertexCount;
  101936. });
  101937. }
  101938. }
  101939. var startingIndex = this._reconstructedMesh.getTotalIndices();
  101940. var startingVertex = this._reconstructedMesh.getTotalVertices();
  101941. var submeshesArray = this._reconstructedMesh.subMeshes;
  101942. this._reconstructedMesh.subMeshes = [];
  101943. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  101944. var originalIndices = this._mesh.getIndices();
  101945. for (i = 0; i < newTriangles.length; ++i) {
  101946. t = newTriangles[i]; //now get the new referencing point for each vertex
  101947. [0, 1, 2].forEach(function (idx) {
  101948. var id = originalIndices[t.originalOffset + idx];
  101949. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  101950. if (offset < 0)
  101951. offset = 0;
  101952. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  101953. });
  101954. }
  101955. //overwriting the old vertex buffers and indices.
  101956. this._reconstructedMesh.setIndices(newIndicesArray);
  101957. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  101958. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  101959. if (newUVsData.length > 0)
  101960. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  101961. if (newColorsData.length > 0)
  101962. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  101963. //create submesh
  101964. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  101965. if (submeshIndex > 0) {
  101966. this._reconstructedMesh.subMeshes = [];
  101967. submeshesArray.forEach(function (submesh) {
  101968. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  101969. });
  101970. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  101971. }
  101972. };
  101973. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  101974. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  101975. this._reconstructedMesh.material = this._mesh.material;
  101976. this._reconstructedMesh.parent = this._mesh.parent;
  101977. this._reconstructedMesh.isVisible = false;
  101978. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  101979. };
  101980. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  101981. for (var i = 0; i < vertex1.triangleCount; ++i) {
  101982. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  101983. if (t.deleted)
  101984. continue;
  101985. var s = this.references[vertex1.triangleStart + i].vertexId;
  101986. var v1 = t.vertices[(s + 1) % 3];
  101987. var v2 = t.vertices[(s + 2) % 3];
  101988. if ((v1 === vertex2 || v2 === vertex2)) {
  101989. deletedArray[i] = true;
  101990. delTr.push(t);
  101991. continue;
  101992. }
  101993. var d1 = v1.position.subtract(point);
  101994. d1 = d1.normalize();
  101995. var d2 = v2.position.subtract(point);
  101996. d2 = d2.normalize();
  101997. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  101998. return true;
  101999. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  102000. deletedArray[i] = false;
  102001. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  102002. return true;
  102003. }
  102004. return false;
  102005. };
  102006. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  102007. var newDeleted = deletedTriangles;
  102008. for (var i = 0; i < vertex.triangleCount; ++i) {
  102009. var ref = this.references[vertex.triangleStart + i];
  102010. var t = this.triangles[ref.triangleId];
  102011. if (t.deleted)
  102012. continue;
  102013. if (deletedArray[i] && t.deletePending) {
  102014. t.deleted = true;
  102015. newDeleted++;
  102016. continue;
  102017. }
  102018. t.vertices[ref.vertexId] = origVertex;
  102019. t.isDirty = true;
  102020. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  102021. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  102022. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  102023. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  102024. this.references.push(ref);
  102025. }
  102026. return newDeleted;
  102027. };
  102028. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  102029. for (var i = 0; i < this.vertices.length; ++i) {
  102030. var vCount = [];
  102031. var vId = [];
  102032. var v = this.vertices[i];
  102033. var j;
  102034. for (j = 0; j < v.triangleCount; ++j) {
  102035. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  102036. for (var ii = 0; ii < 3; ii++) {
  102037. var ofs = 0;
  102038. var vv = triangle.vertices[ii];
  102039. while (ofs < vCount.length) {
  102040. if (vId[ofs] === vv.id)
  102041. break;
  102042. ++ofs;
  102043. }
  102044. if (ofs === vCount.length) {
  102045. vCount.push(1);
  102046. vId.push(vv.id);
  102047. }
  102048. else {
  102049. vCount[ofs]++;
  102050. }
  102051. }
  102052. }
  102053. for (j = 0; j < vCount.length; ++j) {
  102054. if (vCount[j] === 1) {
  102055. this.vertices[vId[j]].isBorder = true;
  102056. }
  102057. else {
  102058. this.vertices[vId[j]].isBorder = false;
  102059. }
  102060. }
  102061. }
  102062. };
  102063. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  102064. if (identifyBorders === void 0) { identifyBorders = false; }
  102065. var i;
  102066. if (!identifyBorders) {
  102067. var newTrianglesVector = [];
  102068. for (i = 0; i < this.triangles.length; ++i) {
  102069. if (!this.triangles[i].deleted) {
  102070. newTrianglesVector.push(this.triangles[i]);
  102071. }
  102072. }
  102073. this.triangles = newTrianglesVector;
  102074. }
  102075. for (i = 0; i < this.vertices.length; ++i) {
  102076. this.vertices[i].triangleCount = 0;
  102077. this.vertices[i].triangleStart = 0;
  102078. }
  102079. var t;
  102080. var j;
  102081. var v;
  102082. for (i = 0; i < this.triangles.length; ++i) {
  102083. t = this.triangles[i];
  102084. for (j = 0; j < 3; ++j) {
  102085. v = t.vertices[j];
  102086. v.triangleCount++;
  102087. }
  102088. }
  102089. var tStart = 0;
  102090. for (i = 0; i < this.vertices.length; ++i) {
  102091. this.vertices[i].triangleStart = tStart;
  102092. tStart += this.vertices[i].triangleCount;
  102093. this.vertices[i].triangleCount = 0;
  102094. }
  102095. var newReferences = new Array(this.triangles.length * 3);
  102096. for (i = 0; i < this.triangles.length; ++i) {
  102097. t = this.triangles[i];
  102098. for (j = 0; j < 3; ++j) {
  102099. v = t.vertices[j];
  102100. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  102101. v.triangleCount++;
  102102. }
  102103. }
  102104. this.references = newReferences;
  102105. if (identifyBorders) {
  102106. this.identifyBorder();
  102107. }
  102108. };
  102109. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  102110. var x = point.x;
  102111. var y = point.y;
  102112. var z = point.z;
  102113. 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
  102114. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  102115. };
  102116. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  102117. var q = vertex1.q.add(vertex2.q);
  102118. var border = vertex1.isBorder && vertex2.isBorder;
  102119. var error = 0;
  102120. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  102121. if (qDet !== 0 && !border) {
  102122. if (!pointResult) {
  102123. pointResult = BABYLON.Vector3.Zero();
  102124. }
  102125. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  102126. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  102127. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  102128. error = this.vertexError(q, pointResult);
  102129. }
  102130. else {
  102131. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  102132. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  102133. var error1 = this.vertexError(q, vertex1.position);
  102134. var error2 = this.vertexError(q, vertex2.position);
  102135. var error3 = this.vertexError(q, p3);
  102136. error = Math.min(error1, error2, error3);
  102137. if (error === error1) {
  102138. if (pointResult) {
  102139. pointResult.copyFrom(vertex1.position);
  102140. }
  102141. }
  102142. else if (error === error2) {
  102143. if (pointResult) {
  102144. pointResult.copyFrom(vertex2.position);
  102145. }
  102146. }
  102147. else {
  102148. if (pointResult) {
  102149. pointResult.copyFrom(p3);
  102150. }
  102151. }
  102152. }
  102153. return error;
  102154. };
  102155. return QuadraticErrorSimplification;
  102156. }());
  102157. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  102158. })(BABYLON || (BABYLON = {}));
  102159. //# sourceMappingURL=babylon.meshSimplification.js.map
  102160. var BABYLON;
  102161. (function (BABYLON) {
  102162. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  102163. get: function () {
  102164. if (!this._simplificationQueue) {
  102165. this._simplificationQueue = new BABYLON.SimplificationQueue();
  102166. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  102167. if (!component) {
  102168. component = new SimplicationQueueSceneComponent(this);
  102169. this._addComponent(component);
  102170. }
  102171. }
  102172. return this._simplificationQueue;
  102173. },
  102174. set: function (value) {
  102175. this._simplificationQueue = value;
  102176. },
  102177. enumerable: true,
  102178. configurable: true
  102179. });
  102180. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  102181. if (parallelProcessing === void 0) { parallelProcessing = true; }
  102182. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  102183. this.getScene().simplificationQueue.addTask({
  102184. settings: settings,
  102185. parallelProcessing: parallelProcessing,
  102186. mesh: this,
  102187. simplificationType: simplificationType,
  102188. successCallback: successCallback
  102189. });
  102190. return this;
  102191. };
  102192. /**
  102193. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  102194. * created in a scene
  102195. */
  102196. var SimplicationQueueSceneComponent = /** @class */ (function () {
  102197. /**
  102198. * Creates a new instance of the component for the given scene
  102199. * @param scene Defines the scene to register the component in
  102200. */
  102201. function SimplicationQueueSceneComponent(scene) {
  102202. /**
  102203. * The component name helpfull to identify the component in the list of scene components.
  102204. */
  102205. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  102206. this.scene = scene;
  102207. }
  102208. /**
  102209. * Registers the component in a given scene
  102210. */
  102211. SimplicationQueueSceneComponent.prototype.register = function () {
  102212. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  102213. };
  102214. /**
  102215. * Rebuilds the elements related to this component in case of
  102216. * context lost for instance.
  102217. */
  102218. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  102219. // Nothing to do for this component
  102220. };
  102221. /**
  102222. * Disposes the component and the associated ressources
  102223. */
  102224. SimplicationQueueSceneComponent.prototype.dispose = function () {
  102225. // Nothing to do for this component
  102226. };
  102227. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  102228. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  102229. this.scene._simplificationQueue.executeNext();
  102230. }
  102231. };
  102232. return SimplicationQueueSceneComponent;
  102233. }());
  102234. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  102235. })(BABYLON || (BABYLON = {}));
  102236. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  102237. var BABYLON;
  102238. (function (BABYLON) {
  102239. /**
  102240. * Class used to represent a specific level of detail of a mesh
  102241. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  102242. */
  102243. var MeshLODLevel = /** @class */ (function () {
  102244. /**
  102245. * Creates a new LOD level
  102246. * @param distance defines the distance where this level should star being displayed
  102247. * @param mesh defines the mesh to use to render this level
  102248. */
  102249. function MeshLODLevel(
  102250. /** Defines the distance where this level should star being displayed */
  102251. distance,
  102252. /** Defines the mesh to use to render this level */
  102253. mesh) {
  102254. this.distance = distance;
  102255. this.mesh = mesh;
  102256. }
  102257. return MeshLODLevel;
  102258. }());
  102259. BABYLON.MeshLODLevel = MeshLODLevel;
  102260. })(BABYLON || (BABYLON = {}));
  102261. //# sourceMappingURL=babylon.meshLODLevel.js.map
  102262. var BABYLON;
  102263. (function (BABYLON) {
  102264. /**
  102265. * Defines the root class used to create scene optimization to use with SceneOptimizer
  102266. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102267. */
  102268. var SceneOptimization = /** @class */ (function () {
  102269. /**
  102270. * Creates the SceneOptimization object
  102271. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102272. * @param desc defines the description associated with the optimization
  102273. */
  102274. function SceneOptimization(
  102275. /**
  102276. * Defines the priority of this optimization (0 by default which means first in the list)
  102277. */
  102278. priority) {
  102279. if (priority === void 0) { priority = 0; }
  102280. this.priority = priority;
  102281. }
  102282. /**
  102283. * Gets a string describing the action executed by the current optimization
  102284. * @returns description string
  102285. */
  102286. SceneOptimization.prototype.getDescription = function () {
  102287. return "";
  102288. };
  102289. /**
  102290. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102291. * @param scene defines the current scene where to apply this optimization
  102292. * @param optimizer defines the current optimizer
  102293. * @returns true if everything that can be done was applied
  102294. */
  102295. SceneOptimization.prototype.apply = function (scene, optimizer) {
  102296. return true;
  102297. };
  102298. ;
  102299. return SceneOptimization;
  102300. }());
  102301. BABYLON.SceneOptimization = SceneOptimization;
  102302. /**
  102303. * Defines an optimization used to reduce the size of render target textures
  102304. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102305. */
  102306. var TextureOptimization = /** @class */ (function (_super) {
  102307. __extends(TextureOptimization, _super);
  102308. /**
  102309. * Creates the TextureOptimization object
  102310. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102311. * @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
  102312. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102313. */
  102314. function TextureOptimization(
  102315. /**
  102316. * Defines the priority of this optimization (0 by default which means first in the list)
  102317. */
  102318. priority,
  102319. /**
  102320. * 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
  102321. */
  102322. maximumSize,
  102323. /**
  102324. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  102325. */
  102326. step) {
  102327. if (priority === void 0) { priority = 0; }
  102328. if (maximumSize === void 0) { maximumSize = 1024; }
  102329. if (step === void 0) { step = 0.5; }
  102330. var _this = _super.call(this, priority) || this;
  102331. _this.priority = priority;
  102332. _this.maximumSize = maximumSize;
  102333. _this.step = step;
  102334. return _this;
  102335. }
  102336. /**
  102337. * Gets a string describing the action executed by the current optimization
  102338. * @returns description string
  102339. */
  102340. TextureOptimization.prototype.getDescription = function () {
  102341. return "Reducing render target texture size to " + this.maximumSize;
  102342. };
  102343. /**
  102344. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102345. * @param scene defines the current scene where to apply this optimization
  102346. * @param optimizer defines the current optimizer
  102347. * @returns true if everything that can be done was applied
  102348. */
  102349. TextureOptimization.prototype.apply = function (scene, optimizer) {
  102350. var allDone = true;
  102351. for (var index = 0; index < scene.textures.length; index++) {
  102352. var texture = scene.textures[index];
  102353. if (!texture.canRescale || texture.getContext) {
  102354. continue;
  102355. }
  102356. var currentSize = texture.getSize();
  102357. var maxDimension = Math.max(currentSize.width, currentSize.height);
  102358. if (maxDimension > this.maximumSize) {
  102359. texture.scale(this.step);
  102360. allDone = false;
  102361. }
  102362. }
  102363. return allDone;
  102364. };
  102365. return TextureOptimization;
  102366. }(SceneOptimization));
  102367. BABYLON.TextureOptimization = TextureOptimization;
  102368. /**
  102369. * Defines an optimization used to increase or decrease the rendering resolution
  102370. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102371. */
  102372. var HardwareScalingOptimization = /** @class */ (function (_super) {
  102373. __extends(HardwareScalingOptimization, _super);
  102374. /**
  102375. * Creates the HardwareScalingOptimization object
  102376. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102377. * @param maximumScale defines the maximum scale to use (2 by default)
  102378. * @param step defines the step to use between two passes (0.5 by default)
  102379. */
  102380. function HardwareScalingOptimization(
  102381. /**
  102382. * Defines the priority of this optimization (0 by default which means first in the list)
  102383. */
  102384. priority,
  102385. /**
  102386. * Defines the maximum scale to use (2 by default)
  102387. */
  102388. maximumScale,
  102389. /**
  102390. * Defines the step to use between two passes (0.5 by default)
  102391. */
  102392. step) {
  102393. if (priority === void 0) { priority = 0; }
  102394. if (maximumScale === void 0) { maximumScale = 2; }
  102395. if (step === void 0) { step = 0.25; }
  102396. var _this = _super.call(this, priority) || this;
  102397. _this.priority = priority;
  102398. _this.maximumScale = maximumScale;
  102399. _this.step = step;
  102400. _this._currentScale = -1;
  102401. _this._directionOffset = 1;
  102402. return _this;
  102403. }
  102404. /**
  102405. * Gets a string describing the action executed by the current optimization
  102406. * @return description string
  102407. */
  102408. HardwareScalingOptimization.prototype.getDescription = function () {
  102409. return "Setting hardware scaling level to " + this._currentScale;
  102410. };
  102411. /**
  102412. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102413. * @param scene defines the current scene where to apply this optimization
  102414. * @param optimizer defines the current optimizer
  102415. * @returns true if everything that can be done was applied
  102416. */
  102417. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  102418. if (this._currentScale === -1) {
  102419. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  102420. if (this._currentScale > this.maximumScale) {
  102421. this._directionOffset = -1;
  102422. }
  102423. }
  102424. this._currentScale += this._directionOffset * this.step;
  102425. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  102426. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  102427. };
  102428. ;
  102429. return HardwareScalingOptimization;
  102430. }(SceneOptimization));
  102431. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  102432. /**
  102433. * Defines an optimization used to remove shadows
  102434. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102435. */
  102436. var ShadowsOptimization = /** @class */ (function (_super) {
  102437. __extends(ShadowsOptimization, _super);
  102438. function ShadowsOptimization() {
  102439. return _super !== null && _super.apply(this, arguments) || this;
  102440. }
  102441. /**
  102442. * Gets a string describing the action executed by the current optimization
  102443. * @return description string
  102444. */
  102445. ShadowsOptimization.prototype.getDescription = function () {
  102446. return "Turning shadows on/off";
  102447. };
  102448. /**
  102449. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102450. * @param scene defines the current scene where to apply this optimization
  102451. * @param optimizer defines the current optimizer
  102452. * @returns true if everything that can be done was applied
  102453. */
  102454. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  102455. scene.shadowsEnabled = optimizer.isInImprovementMode;
  102456. return true;
  102457. };
  102458. ;
  102459. return ShadowsOptimization;
  102460. }(SceneOptimization));
  102461. BABYLON.ShadowsOptimization = ShadowsOptimization;
  102462. /**
  102463. * Defines an optimization used to turn post-processes off
  102464. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102465. */
  102466. var PostProcessesOptimization = /** @class */ (function (_super) {
  102467. __extends(PostProcessesOptimization, _super);
  102468. function PostProcessesOptimization() {
  102469. return _super !== null && _super.apply(this, arguments) || this;
  102470. }
  102471. /**
  102472. * Gets a string describing the action executed by the current optimization
  102473. * @return description string
  102474. */
  102475. PostProcessesOptimization.prototype.getDescription = function () {
  102476. return "Turning post-processes on/off";
  102477. };
  102478. /**
  102479. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102480. * @param scene defines the current scene where to apply this optimization
  102481. * @param optimizer defines the current optimizer
  102482. * @returns true if everything that can be done was applied
  102483. */
  102484. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  102485. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  102486. return true;
  102487. };
  102488. ;
  102489. return PostProcessesOptimization;
  102490. }(SceneOptimization));
  102491. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  102492. /**
  102493. * Defines an optimization used to turn lens flares off
  102494. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102495. */
  102496. var LensFlaresOptimization = /** @class */ (function (_super) {
  102497. __extends(LensFlaresOptimization, _super);
  102498. function LensFlaresOptimization() {
  102499. return _super !== null && _super.apply(this, arguments) || this;
  102500. }
  102501. /**
  102502. * Gets a string describing the action executed by the current optimization
  102503. * @return description string
  102504. */
  102505. LensFlaresOptimization.prototype.getDescription = function () {
  102506. return "Turning lens flares on/off";
  102507. };
  102508. /**
  102509. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102510. * @param scene defines the current scene where to apply this optimization
  102511. * @param optimizer defines the current optimizer
  102512. * @returns true if everything that can be done was applied
  102513. */
  102514. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  102515. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  102516. return true;
  102517. };
  102518. ;
  102519. return LensFlaresOptimization;
  102520. }(SceneOptimization));
  102521. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  102522. /**
  102523. * Defines an optimization based on user defined callback.
  102524. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102525. */
  102526. var CustomOptimization = /** @class */ (function (_super) {
  102527. __extends(CustomOptimization, _super);
  102528. function CustomOptimization() {
  102529. return _super !== null && _super.apply(this, arguments) || this;
  102530. }
  102531. /**
  102532. * Gets a string describing the action executed by the current optimization
  102533. * @returns description string
  102534. */
  102535. CustomOptimization.prototype.getDescription = function () {
  102536. if (this.onGetDescription) {
  102537. return this.onGetDescription();
  102538. }
  102539. return "Running user defined callback";
  102540. };
  102541. /**
  102542. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102543. * @param scene defines the current scene where to apply this optimization
  102544. * @param optimizer defines the current optimizer
  102545. * @returns true if everything that can be done was applied
  102546. */
  102547. CustomOptimization.prototype.apply = function (scene, optimizer) {
  102548. if (this.onApply) {
  102549. return this.onApply(scene, optimizer);
  102550. }
  102551. return true;
  102552. };
  102553. ;
  102554. return CustomOptimization;
  102555. }(SceneOptimization));
  102556. BABYLON.CustomOptimization = CustomOptimization;
  102557. /**
  102558. * Defines an optimization used to turn particles off
  102559. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102560. */
  102561. var ParticlesOptimization = /** @class */ (function (_super) {
  102562. __extends(ParticlesOptimization, _super);
  102563. function ParticlesOptimization() {
  102564. return _super !== null && _super.apply(this, arguments) || this;
  102565. }
  102566. /**
  102567. * Gets a string describing the action executed by the current optimization
  102568. * @return description string
  102569. */
  102570. ParticlesOptimization.prototype.getDescription = function () {
  102571. return "Turning particles on/off";
  102572. };
  102573. /**
  102574. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102575. * @param scene defines the current scene where to apply this optimization
  102576. * @param optimizer defines the current optimizer
  102577. * @returns true if everything that can be done was applied
  102578. */
  102579. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  102580. scene.particlesEnabled = optimizer.isInImprovementMode;
  102581. return true;
  102582. };
  102583. ;
  102584. return ParticlesOptimization;
  102585. }(SceneOptimization));
  102586. BABYLON.ParticlesOptimization = ParticlesOptimization;
  102587. /**
  102588. * Defines an optimization used to turn render targets off
  102589. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102590. */
  102591. var RenderTargetsOptimization = /** @class */ (function (_super) {
  102592. __extends(RenderTargetsOptimization, _super);
  102593. function RenderTargetsOptimization() {
  102594. return _super !== null && _super.apply(this, arguments) || this;
  102595. }
  102596. /**
  102597. * Gets a string describing the action executed by the current optimization
  102598. * @return description string
  102599. */
  102600. RenderTargetsOptimization.prototype.getDescription = function () {
  102601. return "Turning render targets off";
  102602. };
  102603. /**
  102604. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102605. * @param scene defines the current scene where to apply this optimization
  102606. * @param optimizer defines the current optimizer
  102607. * @returns true if everything that can be done was applied
  102608. */
  102609. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  102610. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  102611. return true;
  102612. };
  102613. ;
  102614. return RenderTargetsOptimization;
  102615. }(SceneOptimization));
  102616. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  102617. /**
  102618. * Defines an optimization used to merge meshes with compatible materials
  102619. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102620. */
  102621. var MergeMeshesOptimization = /** @class */ (function (_super) {
  102622. __extends(MergeMeshesOptimization, _super);
  102623. function MergeMeshesOptimization() {
  102624. var _this = _super !== null && _super.apply(this, arguments) || this;
  102625. _this._canBeMerged = function (abstractMesh) {
  102626. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  102627. return false;
  102628. }
  102629. var mesh = abstractMesh;
  102630. if (mesh.isDisposed()) {
  102631. return false;
  102632. }
  102633. if (!mesh.isVisible || !mesh.isEnabled()) {
  102634. return false;
  102635. }
  102636. if (mesh.instances.length > 0) {
  102637. return false;
  102638. }
  102639. if (mesh.skeleton || mesh.hasLODLevels) {
  102640. return false;
  102641. }
  102642. return true;
  102643. };
  102644. return _this;
  102645. }
  102646. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  102647. /**
  102648. * Gets or sets a boolean which defines if optimization octree has to be updated
  102649. */
  102650. get: function () {
  102651. return MergeMeshesOptimization._UpdateSelectionTree;
  102652. },
  102653. /**
  102654. * Gets or sets a boolean which defines if optimization octree has to be updated
  102655. */
  102656. set: function (value) {
  102657. MergeMeshesOptimization._UpdateSelectionTree = value;
  102658. },
  102659. enumerable: true,
  102660. configurable: true
  102661. });
  102662. /**
  102663. * Gets a string describing the action executed by the current optimization
  102664. * @return description string
  102665. */
  102666. MergeMeshesOptimization.prototype.getDescription = function () {
  102667. return "Merging similar meshes together";
  102668. };
  102669. /**
  102670. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  102671. * @param scene defines the current scene where to apply this optimization
  102672. * @param optimizer defines the current optimizer
  102673. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  102674. * @returns true if everything that can be done was applied
  102675. */
  102676. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  102677. var globalPool = scene.meshes.slice(0);
  102678. var globalLength = globalPool.length;
  102679. for (var index = 0; index < globalLength; index++) {
  102680. var currentPool = new Array();
  102681. var current = globalPool[index];
  102682. // Checks
  102683. if (!this._canBeMerged(current)) {
  102684. continue;
  102685. }
  102686. currentPool.push(current);
  102687. // Find compatible meshes
  102688. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  102689. var otherMesh = globalPool[subIndex];
  102690. if (!this._canBeMerged(otherMesh)) {
  102691. continue;
  102692. }
  102693. if (otherMesh.material !== current.material) {
  102694. continue;
  102695. }
  102696. if (otherMesh.checkCollisions !== current.checkCollisions) {
  102697. continue;
  102698. }
  102699. currentPool.push(otherMesh);
  102700. globalLength--;
  102701. globalPool.splice(subIndex, 1);
  102702. subIndex--;
  102703. }
  102704. if (currentPool.length < 2) {
  102705. continue;
  102706. }
  102707. // Merge meshes
  102708. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  102709. }
  102710. // Call the octree system optimization if it is defined.
  102711. var sceneAsAny = scene;
  102712. if (sceneAsAny.createOrUpdateSelectionOctree) {
  102713. if (updateSelectionTree != undefined) {
  102714. if (updateSelectionTree) {
  102715. sceneAsAny.createOrUpdateSelectionOctree();
  102716. }
  102717. }
  102718. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  102719. sceneAsAny.createOrUpdateSelectionOctree();
  102720. }
  102721. }
  102722. return true;
  102723. };
  102724. ;
  102725. MergeMeshesOptimization._UpdateSelectionTree = false;
  102726. return MergeMeshesOptimization;
  102727. }(SceneOptimization));
  102728. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  102729. /**
  102730. * Defines a list of options used by SceneOptimizer
  102731. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102732. */
  102733. var SceneOptimizerOptions = /** @class */ (function () {
  102734. /**
  102735. * Creates a new list of options used by SceneOptimizer
  102736. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  102737. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  102738. */
  102739. function SceneOptimizerOptions(
  102740. /**
  102741. * Defines the target frame rate to reach (60 by default)
  102742. */
  102743. targetFrameRate,
  102744. /**
  102745. * Defines the interval between two checkes (2000ms by default)
  102746. */
  102747. trackerDuration) {
  102748. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  102749. if (trackerDuration === void 0) { trackerDuration = 2000; }
  102750. this.targetFrameRate = targetFrameRate;
  102751. this.trackerDuration = trackerDuration;
  102752. /**
  102753. * Gets the list of optimizations to apply
  102754. */
  102755. this.optimizations = new Array();
  102756. }
  102757. /**
  102758. * Add a new optimization
  102759. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  102760. * @returns the current SceneOptimizerOptions
  102761. */
  102762. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  102763. this.optimizations.push(optimization);
  102764. return this;
  102765. };
  102766. /**
  102767. * Add a new custom optimization
  102768. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  102769. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  102770. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  102771. * @returns the current SceneOptimizerOptions
  102772. */
  102773. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  102774. if (priority === void 0) { priority = 0; }
  102775. var optimization = new CustomOptimization(priority);
  102776. optimization.onApply = onApply;
  102777. optimization.onGetDescription = onGetDescription;
  102778. this.optimizations.push(optimization);
  102779. return this;
  102780. };
  102781. /**
  102782. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  102783. * @param targetFrameRate defines the target frame rate (60 by default)
  102784. * @returns a SceneOptimizerOptions object
  102785. */
  102786. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  102787. var result = new SceneOptimizerOptions(targetFrameRate);
  102788. var priority = 0;
  102789. result.addOptimization(new MergeMeshesOptimization(priority));
  102790. result.addOptimization(new ShadowsOptimization(priority));
  102791. result.addOptimization(new LensFlaresOptimization(priority));
  102792. // Next priority
  102793. priority++;
  102794. result.addOptimization(new PostProcessesOptimization(priority));
  102795. result.addOptimization(new ParticlesOptimization(priority));
  102796. // Next priority
  102797. priority++;
  102798. result.addOptimization(new TextureOptimization(priority, 1024));
  102799. return result;
  102800. };
  102801. /**
  102802. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  102803. * @param targetFrameRate defines the target frame rate (60 by default)
  102804. * @returns a SceneOptimizerOptions object
  102805. */
  102806. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  102807. var result = new SceneOptimizerOptions(targetFrameRate);
  102808. var priority = 0;
  102809. result.addOptimization(new MergeMeshesOptimization(priority));
  102810. result.addOptimization(new ShadowsOptimization(priority));
  102811. result.addOptimization(new LensFlaresOptimization(priority));
  102812. // Next priority
  102813. priority++;
  102814. result.addOptimization(new PostProcessesOptimization(priority));
  102815. result.addOptimization(new ParticlesOptimization(priority));
  102816. // Next priority
  102817. priority++;
  102818. result.addOptimization(new TextureOptimization(priority, 512));
  102819. // Next priority
  102820. priority++;
  102821. result.addOptimization(new RenderTargetsOptimization(priority));
  102822. // Next priority
  102823. priority++;
  102824. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  102825. return result;
  102826. };
  102827. /**
  102828. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  102829. * @param targetFrameRate defines the target frame rate (60 by default)
  102830. * @returns a SceneOptimizerOptions object
  102831. */
  102832. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  102833. var result = new SceneOptimizerOptions(targetFrameRate);
  102834. var priority = 0;
  102835. result.addOptimization(new MergeMeshesOptimization(priority));
  102836. result.addOptimization(new ShadowsOptimization(priority));
  102837. result.addOptimization(new LensFlaresOptimization(priority));
  102838. // Next priority
  102839. priority++;
  102840. result.addOptimization(new PostProcessesOptimization(priority));
  102841. result.addOptimization(new ParticlesOptimization(priority));
  102842. // Next priority
  102843. priority++;
  102844. result.addOptimization(new TextureOptimization(priority, 256));
  102845. // Next priority
  102846. priority++;
  102847. result.addOptimization(new RenderTargetsOptimization(priority));
  102848. // Next priority
  102849. priority++;
  102850. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  102851. return result;
  102852. };
  102853. return SceneOptimizerOptions;
  102854. }());
  102855. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  102856. /**
  102857. * Class used to run optimizations in order to reach a target frame rate
  102858. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  102859. */
  102860. var SceneOptimizer = /** @class */ (function () {
  102861. /**
  102862. * Creates a new SceneOptimizer
  102863. * @param scene defines the scene to work on
  102864. * @param options defines the options to use with the SceneOptimizer
  102865. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  102866. * @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)
  102867. */
  102868. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  102869. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  102870. if (improvementMode === void 0) { improvementMode = false; }
  102871. var _this = this;
  102872. this._isRunning = false;
  102873. this._currentPriorityLevel = 0;
  102874. this._targetFrameRate = 60;
  102875. this._trackerDuration = 2000;
  102876. this._currentFrameRate = 0;
  102877. this._improvementMode = false;
  102878. /**
  102879. * Defines an observable called when the optimizer reaches the target frame rate
  102880. */
  102881. this.onSuccessObservable = new BABYLON.Observable();
  102882. /**
  102883. * Defines an observable called when the optimizer enables an optimization
  102884. */
  102885. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  102886. /**
  102887. * Defines an observable called when the optimizer is not able to reach the target frame rate
  102888. */
  102889. this.onFailureObservable = new BABYLON.Observable();
  102890. if (!options) {
  102891. this._options = new SceneOptimizerOptions();
  102892. }
  102893. else {
  102894. this._options = options;
  102895. }
  102896. if (this._options.targetFrameRate) {
  102897. this._targetFrameRate = this._options.targetFrameRate;
  102898. }
  102899. if (this._options.trackerDuration) {
  102900. this._trackerDuration = this._options.trackerDuration;
  102901. }
  102902. if (autoGeneratePriorities) {
  102903. var priority = 0;
  102904. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  102905. var optim = _a[_i];
  102906. optim.priority = priority++;
  102907. }
  102908. }
  102909. this._improvementMode = improvementMode;
  102910. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  102911. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  102912. _this._sceneDisposeObserver = null;
  102913. _this.dispose();
  102914. });
  102915. }
  102916. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  102917. /**
  102918. * Gets a boolean indicating if the optimizer is in improvement mode
  102919. */
  102920. get: function () {
  102921. return this._improvementMode;
  102922. },
  102923. enumerable: true,
  102924. configurable: true
  102925. });
  102926. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  102927. /**
  102928. * Gets the current priority level (0 at start)
  102929. */
  102930. get: function () {
  102931. return this._currentPriorityLevel;
  102932. },
  102933. enumerable: true,
  102934. configurable: true
  102935. });
  102936. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  102937. /**
  102938. * Gets the current frame rate checked by the SceneOptimizer
  102939. */
  102940. get: function () {
  102941. return this._currentFrameRate;
  102942. },
  102943. enumerable: true,
  102944. configurable: true
  102945. });
  102946. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  102947. /**
  102948. * Gets or sets the current target frame rate (60 by default)
  102949. */
  102950. get: function () {
  102951. return this._targetFrameRate;
  102952. },
  102953. /**
  102954. * Gets or sets the current target frame rate (60 by default)
  102955. */
  102956. set: function (value) {
  102957. this._targetFrameRate = value;
  102958. },
  102959. enumerable: true,
  102960. configurable: true
  102961. });
  102962. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  102963. /**
  102964. * Gets or sets the current interval between two checks (every 2000ms by default)
  102965. */
  102966. get: function () {
  102967. return this._trackerDuration;
  102968. },
  102969. /**
  102970. * Gets or sets the current interval between two checks (every 2000ms by default)
  102971. */
  102972. set: function (value) {
  102973. this._trackerDuration = value;
  102974. },
  102975. enumerable: true,
  102976. configurable: true
  102977. });
  102978. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  102979. /**
  102980. * Gets the list of active optimizations
  102981. */
  102982. get: function () {
  102983. return this._options.optimizations;
  102984. },
  102985. enumerable: true,
  102986. configurable: true
  102987. });
  102988. /**
  102989. * Stops the current optimizer
  102990. */
  102991. SceneOptimizer.prototype.stop = function () {
  102992. this._isRunning = false;
  102993. };
  102994. /**
  102995. * Reset the optimizer to initial step (current priority level = 0)
  102996. */
  102997. SceneOptimizer.prototype.reset = function () {
  102998. this._currentPriorityLevel = 0;
  102999. };
  103000. /**
  103001. * Start the optimizer. By default it will try to reach a specific framerate
  103002. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  103003. */
  103004. SceneOptimizer.prototype.start = function () {
  103005. var _this = this;
  103006. if (this._isRunning) {
  103007. return;
  103008. }
  103009. this._isRunning = true;
  103010. // Let's wait for the scene to be ready before running our check
  103011. this._scene.executeWhenReady(function () {
  103012. setTimeout(function () {
  103013. _this._checkCurrentState();
  103014. }, _this._trackerDuration);
  103015. });
  103016. };
  103017. SceneOptimizer.prototype._checkCurrentState = function () {
  103018. var _this = this;
  103019. if (!this._isRunning) {
  103020. return;
  103021. }
  103022. var scene = this._scene;
  103023. var options = this._options;
  103024. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  103025. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  103026. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  103027. this._isRunning = false;
  103028. this.onSuccessObservable.notifyObservers(this);
  103029. return;
  103030. }
  103031. // Apply current level of optimizations
  103032. var allDone = true;
  103033. var noOptimizationApplied = true;
  103034. for (var index = 0; index < options.optimizations.length; index++) {
  103035. var optimization = options.optimizations[index];
  103036. if (optimization.priority === this._currentPriorityLevel) {
  103037. noOptimizationApplied = false;
  103038. allDone = allDone && optimization.apply(scene, this);
  103039. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  103040. }
  103041. }
  103042. // If no optimization was applied, this is a failure :(
  103043. if (noOptimizationApplied) {
  103044. this._isRunning = false;
  103045. this.onFailureObservable.notifyObservers(this);
  103046. return;
  103047. }
  103048. // If all optimizations were done, move to next level
  103049. if (allDone) {
  103050. this._currentPriorityLevel++;
  103051. }
  103052. // Let's the system running for a specific amount of time before checking FPS
  103053. scene.executeWhenReady(function () {
  103054. setTimeout(function () {
  103055. _this._checkCurrentState();
  103056. }, _this._trackerDuration);
  103057. });
  103058. };
  103059. /**
  103060. * Release all resources
  103061. */
  103062. SceneOptimizer.prototype.dispose = function () {
  103063. this.stop();
  103064. this.onSuccessObservable.clear();
  103065. this.onFailureObservable.clear();
  103066. this.onNewOptimizationAppliedObservable.clear();
  103067. if (this._sceneDisposeObserver) {
  103068. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  103069. }
  103070. };
  103071. /**
  103072. * Helper function to create a SceneOptimizer with one single line of code
  103073. * @param scene defines the scene to work on
  103074. * @param options defines the options to use with the SceneOptimizer
  103075. * @param onSuccess defines a callback to call on success
  103076. * @param onFailure defines a callback to call on failure
  103077. * @returns the new SceneOptimizer object
  103078. */
  103079. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  103080. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  103081. if (onSuccess) {
  103082. optimizer.onSuccessObservable.add(function () {
  103083. onSuccess();
  103084. });
  103085. }
  103086. if (onFailure) {
  103087. optimizer.onFailureObservable.add(function () {
  103088. onFailure();
  103089. });
  103090. }
  103091. optimizer.start();
  103092. return optimizer;
  103093. };
  103094. return SceneOptimizer;
  103095. }());
  103096. BABYLON.SceneOptimizer = SceneOptimizer;
  103097. })(BABYLON || (BABYLON = {}));
  103098. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  103099. var BABYLON;
  103100. (function (BABYLON) {
  103101. /**
  103102. * Gets the outline renderer associated with the scene
  103103. * @returns a OutlineRenderer
  103104. */
  103105. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  103106. if (!this._outlineRenderer) {
  103107. this._outlineRenderer = new OutlineRenderer(this);
  103108. }
  103109. return this._outlineRenderer;
  103110. };
  103111. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  103112. get: function () {
  103113. return this._renderOutline;
  103114. },
  103115. set: function (value) {
  103116. if (value) {
  103117. // Lazy Load the component.
  103118. this.getScene().getOutlineRenderer();
  103119. }
  103120. this._renderOutline = value;
  103121. },
  103122. enumerable: true,
  103123. configurable: true
  103124. });
  103125. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  103126. get: function () {
  103127. return this._renderOverlay;
  103128. },
  103129. set: function (value) {
  103130. if (value) {
  103131. // Lazy Load the component.
  103132. this.getScene().getOutlineRenderer();
  103133. }
  103134. this._renderOverlay = value;
  103135. },
  103136. enumerable: true,
  103137. configurable: true
  103138. });
  103139. /**
  103140. * This class is responsible to draw bothe outline/overlay of meshes.
  103141. * It should not be used directly but through the available method on mesh.
  103142. */
  103143. var OutlineRenderer = /** @class */ (function () {
  103144. /**
  103145. * Instantiates a new outline renderer. (There could be only one per scene).
  103146. * @param scene Defines the scene it belongs to
  103147. */
  103148. function OutlineRenderer(scene) {
  103149. /**
  103150. * The name of the component. Each component must have a unique name.
  103151. */
  103152. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  103153. /**
  103154. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  103155. */
  103156. this.zOffset = 1;
  103157. this.scene = scene;
  103158. this._engine = scene.getEngine();
  103159. this.scene._addComponent(this);
  103160. }
  103161. /**
  103162. * Register the component to one instance of a scene.
  103163. */
  103164. OutlineRenderer.prototype.register = function () {
  103165. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  103166. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  103167. };
  103168. /**
  103169. * Rebuilds the elements related to this component in case of
  103170. * context lost for instance.
  103171. */
  103172. OutlineRenderer.prototype.rebuild = function () {
  103173. // Nothing to do here.
  103174. };
  103175. /**
  103176. * Disposes the component and the associated ressources.
  103177. */
  103178. OutlineRenderer.prototype.dispose = function () {
  103179. // Nothing to do here.
  103180. };
  103181. /**
  103182. * Renders the outline in the canvas.
  103183. * @param subMesh Defines the sumesh to render
  103184. * @param batch Defines the batch of meshes in case of instances
  103185. * @param useOverlay Defines if the rendering is for the overlay or the outline
  103186. */
  103187. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  103188. var _this = this;
  103189. if (useOverlay === void 0) { useOverlay = false; }
  103190. var scene = this.scene;
  103191. var engine = scene.getEngine();
  103192. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  103193. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  103194. return;
  103195. }
  103196. var mesh = subMesh.getRenderingMesh();
  103197. var material = subMesh.getMaterial();
  103198. if (!material || !scene.activeCamera) {
  103199. return;
  103200. }
  103201. engine.enableEffect(this._effect);
  103202. // Logarithmic depth
  103203. if (material.useLogarithmicDepth) {
  103204. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  103205. }
  103206. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  103207. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  103208. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  103209. // Bones
  103210. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  103211. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  103212. }
  103213. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  103214. // Alpha test
  103215. if (material && material.needAlphaTesting()) {
  103216. var alphaTexture = material.getAlphaTestTexture();
  103217. if (alphaTexture) {
  103218. this._effect.setTexture("diffuseSampler", alphaTexture);
  103219. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  103220. }
  103221. }
  103222. engine.setZOffset(-this.zOffset);
  103223. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  103224. engine.setZOffset(0);
  103225. };
  103226. /**
  103227. * Returns whether or not the outline renderer is ready for a given submesh.
  103228. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  103229. * @param subMesh Defines the submesh to check readyness for
  103230. * @param useInstances Defines wheter wee are trying to render instances or not
  103231. * @returns true if ready otherwise false
  103232. */
  103233. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  103234. var defines = [];
  103235. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  103236. var mesh = subMesh.getMesh();
  103237. var material = subMesh.getMaterial();
  103238. if (material) {
  103239. // Alpha test
  103240. if (material.needAlphaTesting()) {
  103241. defines.push("#define ALPHATEST");
  103242. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  103243. attribs.push(BABYLON.VertexBuffer.UVKind);
  103244. defines.push("#define UV1");
  103245. }
  103246. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  103247. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  103248. defines.push("#define UV2");
  103249. }
  103250. }
  103251. //Logarithmic depth
  103252. if (material.useLogarithmicDepth) {
  103253. defines.push("#define LOGARITHMICDEPTH");
  103254. }
  103255. }
  103256. // Bones
  103257. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  103258. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  103259. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  103260. if (mesh.numBoneInfluencers > 4) {
  103261. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  103262. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  103263. }
  103264. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  103265. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  103266. }
  103267. else {
  103268. defines.push("#define NUM_BONE_INFLUENCERS 0");
  103269. }
  103270. // Instances
  103271. if (useInstances) {
  103272. defines.push("#define INSTANCES");
  103273. attribs.push("world0");
  103274. attribs.push("world1");
  103275. attribs.push("world2");
  103276. attribs.push("world3");
  103277. }
  103278. // Get correct effect
  103279. var join = defines.join("\n");
  103280. if (this._cachedDefines !== join) {
  103281. this._cachedDefines = join;
  103282. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  103283. }
  103284. return this._effect.isReady();
  103285. };
  103286. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  103287. // Outline - step 1
  103288. this._savedDepthWrite = this._engine.getDepthWrite();
  103289. if (mesh.renderOutline) {
  103290. this._engine.setDepthWrite(false);
  103291. this.render(subMesh, batch);
  103292. this._engine.setDepthWrite(this._savedDepthWrite);
  103293. }
  103294. };
  103295. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  103296. // Outline - step 2
  103297. if (mesh.renderOutline && this._savedDepthWrite) {
  103298. this._engine.setDepthWrite(true);
  103299. this._engine.setColorWrite(false);
  103300. this.render(subMesh, batch);
  103301. this._engine.setColorWrite(true);
  103302. }
  103303. // Overlay
  103304. if (mesh.renderOverlay) {
  103305. var currentMode = this._engine.getAlphaMode();
  103306. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  103307. this.render(subMesh, batch, true);
  103308. this._engine.setAlphaMode(currentMode);
  103309. }
  103310. };
  103311. return OutlineRenderer;
  103312. }());
  103313. BABYLON.OutlineRenderer = OutlineRenderer;
  103314. })(BABYLON || (BABYLON = {}));
  103315. //# sourceMappingURL=babylon.outlineRenderer.js.map
  103316. var BABYLON;
  103317. (function (BABYLON) {
  103318. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  103319. if (this._edgesRenderer) {
  103320. this._edgesRenderer.dispose();
  103321. this._edgesRenderer = null;
  103322. }
  103323. return this;
  103324. };
  103325. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103326. if (epsilon === void 0) { epsilon = 0.95; }
  103327. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103328. this.disableEdgesRendering();
  103329. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103330. return this;
  103331. };
  103332. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  103333. get: function () {
  103334. return this._edgesRenderer;
  103335. },
  103336. enumerable: true,
  103337. configurable: true
  103338. });
  103339. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  103340. if (epsilon === void 0) { epsilon = 0.95; }
  103341. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103342. this.disableEdgesRendering();
  103343. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  103344. return this;
  103345. };
  103346. /**
  103347. * FaceAdjacencies Helper class to generate edges
  103348. */
  103349. var FaceAdjacencies = /** @class */ (function () {
  103350. function FaceAdjacencies() {
  103351. this.edges = new Array();
  103352. this.edgesConnectedCount = 0;
  103353. }
  103354. return FaceAdjacencies;
  103355. }());
  103356. /**
  103357. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  103358. */
  103359. var EdgesRenderer = /** @class */ (function () {
  103360. /**
  103361. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  103362. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  103363. * @param source Mesh used to create edges
  103364. * @param epsilon sum of angles in adjacency to check for edge
  103365. * @param checkVerticesInsteadOfIndices
  103366. * @param generateEdgesLines - should generate Lines or only prepare resources.
  103367. */
  103368. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  103369. if (epsilon === void 0) { epsilon = 0.95; }
  103370. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103371. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  103372. var _this = this;
  103373. this.edgesWidthScalerForOrthographic = 1000.0;
  103374. this.edgesWidthScalerForPerspective = 50.0;
  103375. this._linesPositions = new Array();
  103376. this._linesNormals = new Array();
  103377. this._linesIndices = new Array();
  103378. this._buffers = {};
  103379. this._checkVerticesInsteadOfIndices = false;
  103380. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  103381. this.isEnabled = true;
  103382. this._source = source;
  103383. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  103384. this._epsilon = epsilon;
  103385. this._prepareRessources();
  103386. if (generateEdgesLines) {
  103387. this._generateEdgesLines();
  103388. }
  103389. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  103390. _this._rebuild();
  103391. });
  103392. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  103393. _this.dispose();
  103394. });
  103395. }
  103396. EdgesRenderer.prototype._prepareRessources = function () {
  103397. if (this._lineShader) {
  103398. return;
  103399. }
  103400. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  103401. attributes: ["position", "normal"],
  103402. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  103403. });
  103404. this._lineShader.disableDepthWrite = true;
  103405. this._lineShader.backFaceCulling = false;
  103406. };
  103407. /** @hidden */
  103408. EdgesRenderer.prototype._rebuild = function () {
  103409. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103410. if (buffer) {
  103411. buffer._rebuild();
  103412. }
  103413. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103414. if (buffer) {
  103415. buffer._rebuild();
  103416. }
  103417. var scene = this._source.getScene();
  103418. var engine = scene.getEngine();
  103419. this._ib = engine.createIndexBuffer(this._linesIndices);
  103420. };
  103421. /**
  103422. * Releases the required resources for the edges renderer
  103423. */
  103424. EdgesRenderer.prototype.dispose = function () {
  103425. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  103426. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  103427. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  103428. if (buffer) {
  103429. buffer.dispose();
  103430. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  103431. }
  103432. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  103433. if (buffer) {
  103434. buffer.dispose();
  103435. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  103436. }
  103437. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  103438. this._lineShader.dispose();
  103439. };
  103440. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  103441. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  103442. return 0;
  103443. }
  103444. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  103445. return 1;
  103446. }
  103447. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  103448. return 2;
  103449. }
  103450. return -1;
  103451. };
  103452. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  103453. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  103454. return 0;
  103455. }
  103456. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  103457. return 1;
  103458. }
  103459. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  103460. return 2;
  103461. }
  103462. return -1;
  103463. };
  103464. /**
  103465. * Checks if the pair of p0 and p1 is en edge
  103466. * @param faceIndex
  103467. * @param edge
  103468. * @param faceNormals
  103469. * @param p0
  103470. * @param p1
  103471. * @private
  103472. */
  103473. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  103474. var needToCreateLine;
  103475. if (edge === undefined) {
  103476. needToCreateLine = true;
  103477. }
  103478. else {
  103479. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  103480. needToCreateLine = dotProduct < this._epsilon;
  103481. }
  103482. if (needToCreateLine) {
  103483. var offset = this._linesPositions.length / 3;
  103484. var normal = p0.subtract(p1);
  103485. normal.normalize();
  103486. // Positions
  103487. this._linesPositions.push(p0.x);
  103488. this._linesPositions.push(p0.y);
  103489. this._linesPositions.push(p0.z);
  103490. this._linesPositions.push(p0.x);
  103491. this._linesPositions.push(p0.y);
  103492. this._linesPositions.push(p0.z);
  103493. this._linesPositions.push(p1.x);
  103494. this._linesPositions.push(p1.y);
  103495. this._linesPositions.push(p1.z);
  103496. this._linesPositions.push(p1.x);
  103497. this._linesPositions.push(p1.y);
  103498. this._linesPositions.push(p1.z);
  103499. // Normals
  103500. this._linesNormals.push(p1.x);
  103501. this._linesNormals.push(p1.y);
  103502. this._linesNormals.push(p1.z);
  103503. this._linesNormals.push(-1);
  103504. this._linesNormals.push(p1.x);
  103505. this._linesNormals.push(p1.y);
  103506. this._linesNormals.push(p1.z);
  103507. this._linesNormals.push(1);
  103508. this._linesNormals.push(p0.x);
  103509. this._linesNormals.push(p0.y);
  103510. this._linesNormals.push(p0.z);
  103511. this._linesNormals.push(-1);
  103512. this._linesNormals.push(p0.x);
  103513. this._linesNormals.push(p0.y);
  103514. this._linesNormals.push(p0.z);
  103515. this._linesNormals.push(1);
  103516. // Indices
  103517. this._linesIndices.push(offset);
  103518. this._linesIndices.push(offset + 1);
  103519. this._linesIndices.push(offset + 2);
  103520. this._linesIndices.push(offset);
  103521. this._linesIndices.push(offset + 2);
  103522. this._linesIndices.push(offset + 3);
  103523. }
  103524. };
  103525. /**
  103526. * Generates lines edges from adjacencjes
  103527. * @private
  103528. */
  103529. EdgesRenderer.prototype._generateEdgesLines = function () {
  103530. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103531. var indices = this._source.getIndices();
  103532. if (!indices || !positions) {
  103533. return;
  103534. }
  103535. // First let's find adjacencies
  103536. var adjacencies = new Array();
  103537. var faceNormals = new Array();
  103538. var index;
  103539. var faceAdjacencies;
  103540. // Prepare faces
  103541. for (index = 0; index < indices.length; index += 3) {
  103542. faceAdjacencies = new FaceAdjacencies();
  103543. var p0Index = indices[index];
  103544. var p1Index = indices[index + 1];
  103545. var p2Index = indices[index + 2];
  103546. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  103547. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  103548. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  103549. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  103550. faceNormal.normalize();
  103551. faceNormals.push(faceNormal);
  103552. adjacencies.push(faceAdjacencies);
  103553. }
  103554. // Scan
  103555. for (index = 0; index < adjacencies.length; index++) {
  103556. faceAdjacencies = adjacencies[index];
  103557. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  103558. var otherFaceAdjacencies = adjacencies[otherIndex];
  103559. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  103560. break;
  103561. }
  103562. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  103563. continue;
  103564. }
  103565. var otherP0 = indices[otherIndex * 3];
  103566. var otherP1 = indices[otherIndex * 3 + 1];
  103567. var otherP2 = indices[otherIndex * 3 + 2];
  103568. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  103569. var otherEdgeIndex = 0;
  103570. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  103571. continue;
  103572. }
  103573. switch (edgeIndex) {
  103574. case 0:
  103575. if (this._checkVerticesInsteadOfIndices) {
  103576. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103577. }
  103578. else {
  103579. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  103580. }
  103581. break;
  103582. case 1:
  103583. if (this._checkVerticesInsteadOfIndices) {
  103584. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103585. }
  103586. else {
  103587. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  103588. }
  103589. break;
  103590. case 2:
  103591. if (this._checkVerticesInsteadOfIndices) {
  103592. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  103593. }
  103594. else {
  103595. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  103596. }
  103597. break;
  103598. }
  103599. if (otherEdgeIndex === -1) {
  103600. continue;
  103601. }
  103602. faceAdjacencies.edges[edgeIndex] = otherIndex;
  103603. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  103604. faceAdjacencies.edgesConnectedCount++;
  103605. otherFaceAdjacencies.edgesConnectedCount++;
  103606. if (faceAdjacencies.edgesConnectedCount === 3) {
  103607. break;
  103608. }
  103609. }
  103610. }
  103611. }
  103612. // Create lines
  103613. for (index = 0; index < adjacencies.length; index++) {
  103614. // 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
  103615. var current = adjacencies[index];
  103616. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  103617. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  103618. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  103619. }
  103620. // Merge into a single mesh
  103621. var engine = this._source.getScene().getEngine();
  103622. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  103623. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  103624. this._ib = engine.createIndexBuffer(this._linesIndices);
  103625. this._indicesCount = this._linesIndices.length;
  103626. };
  103627. /**
  103628. * Checks wether or not the edges renderer is ready to render.
  103629. * @return true if ready, otherwise false.
  103630. */
  103631. EdgesRenderer.prototype.isReady = function () {
  103632. return this._lineShader.isReady();
  103633. };
  103634. /**
  103635. * Renders the edges of the attached mesh,
  103636. */
  103637. EdgesRenderer.prototype.render = function () {
  103638. var scene = this._source.getScene();
  103639. if (!this.isReady() || !scene.activeCamera) {
  103640. return;
  103641. }
  103642. var engine = scene.getEngine();
  103643. this._lineShader._preBind();
  103644. if (this._source.edgesColor.a !== 1) {
  103645. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  103646. }
  103647. else {
  103648. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  103649. }
  103650. // VBOs
  103651. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  103652. scene.resetCachedMaterial();
  103653. this._lineShader.setColor4("color", this._source.edgesColor);
  103654. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  103655. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  103656. }
  103657. else {
  103658. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  103659. }
  103660. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  103661. this._lineShader.bind(this._source.getWorldMatrix());
  103662. // Draw order
  103663. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  103664. this._lineShader.unbind();
  103665. };
  103666. return EdgesRenderer;
  103667. }());
  103668. BABYLON.EdgesRenderer = EdgesRenderer;
  103669. })(BABYLON || (BABYLON = {}));
  103670. //# sourceMappingURL=babylon.edgesRenderer.js.map
  103671. var BABYLON;
  103672. (function (BABYLON) {
  103673. /**
  103674. * FaceAdjacencies Helper class to generate edges
  103675. */
  103676. var FaceAdjacencies = /** @class */ (function () {
  103677. function FaceAdjacencies() {
  103678. this.edges = new Array();
  103679. this.edgesConnectedCount = 0;
  103680. }
  103681. return FaceAdjacencies;
  103682. }());
  103683. /**
  103684. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  103685. */
  103686. var LineEdgesRenderer = /** @class */ (function (_super) {
  103687. __extends(LineEdgesRenderer, _super);
  103688. /**
  103689. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  103690. * @param source LineMesh used to generate edges
  103691. * @param epsilon not important (specified angle for edge detection)
  103692. * @param checkVerticesInsteadOfIndices not important for LineMesh
  103693. */
  103694. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  103695. if (epsilon === void 0) { epsilon = 0.95; }
  103696. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  103697. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  103698. _this._generateEdgesLines();
  103699. return _this;
  103700. }
  103701. /**
  103702. * Always create the edge since its a line so only important things are p0 and p1
  103703. * @param faceIndex not important for LineMesh
  103704. * @param edge not important for LineMesh
  103705. * @param faceNormals not important for LineMesh
  103706. * @param p0 beginnig of line
  103707. * @param p1 end of line
  103708. */
  103709. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  103710. var offset = this._linesPositions.length / 3;
  103711. var normal = p0.subtract(p1);
  103712. normal.normalize();
  103713. // Positions
  103714. this._linesPositions.push(p0.x);
  103715. this._linesPositions.push(p0.y);
  103716. this._linesPositions.push(p0.z);
  103717. this._linesPositions.push(p0.x);
  103718. this._linesPositions.push(p0.y);
  103719. this._linesPositions.push(p0.z);
  103720. this._linesPositions.push(p1.x);
  103721. this._linesPositions.push(p1.y);
  103722. this._linesPositions.push(p1.z);
  103723. this._linesPositions.push(p1.x);
  103724. this._linesPositions.push(p1.y);
  103725. this._linesPositions.push(p1.z);
  103726. // Normals
  103727. this._linesNormals.push(p1.x);
  103728. this._linesNormals.push(p1.y);
  103729. this._linesNormals.push(p1.z);
  103730. this._linesNormals.push(-1);
  103731. this._linesNormals.push(p1.x);
  103732. this._linesNormals.push(p1.y);
  103733. this._linesNormals.push(p1.z);
  103734. this._linesNormals.push(1);
  103735. this._linesNormals.push(p0.x);
  103736. this._linesNormals.push(p0.y);
  103737. this._linesNormals.push(p0.z);
  103738. this._linesNormals.push(-1);
  103739. this._linesNormals.push(p0.x);
  103740. this._linesNormals.push(p0.y);
  103741. this._linesNormals.push(p0.z);
  103742. this._linesNormals.push(1);
  103743. // Indices
  103744. this._linesIndices.push(offset);
  103745. this._linesIndices.push(offset + 1);
  103746. this._linesIndices.push(offset + 2);
  103747. this._linesIndices.push(offset);
  103748. this._linesIndices.push(offset + 2);
  103749. this._linesIndices.push(offset + 3);
  103750. };
  103751. /**
  103752. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  103753. */
  103754. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  103755. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  103756. var indices = this._source.getIndices();
  103757. if (!indices || !positions) {
  103758. return;
  103759. }
  103760. // First let's find adjacencies
  103761. var adjacencies = new Array();
  103762. var faceNormals = new Array();
  103763. var index;
  103764. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  103765. var currentAdjecancy = new FaceAdjacencies();
  103766. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  103767. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  103768. adjacencies.push(currentAdjecancy);
  103769. }
  103770. // Create lines
  103771. for (index = 0; index < adjacencies.length; index++) {
  103772. // 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
  103773. var current = adjacencies[index];
  103774. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  103775. }
  103776. // Merge into a single mesh
  103777. var engine = this._source.getScene().getEngine();
  103778. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  103779. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  103780. this._ib = engine.createIndexBuffer(this._linesIndices);
  103781. this._indicesCount = this._linesIndices.length;
  103782. };
  103783. return LineEdgesRenderer;
  103784. }(BABYLON.EdgesRenderer));
  103785. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  103786. })(BABYLON || (BABYLON = {}));
  103787. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  103788. var BABYLON;
  103789. (function (BABYLON) {
  103790. // Adds the parser to the scene parsers.
  103791. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  103792. if (parsedData.effectLayers) {
  103793. if (!container.effectLayers) {
  103794. container.effectLayers = new Array();
  103795. }
  103796. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  103797. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  103798. container.effectLayers.push(effectLayer);
  103799. }
  103800. }
  103801. });
  103802. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  103803. var index = this.effectLayers.indexOf(toRemove);
  103804. if (index !== -1) {
  103805. this.effectLayers.splice(index, 1);
  103806. }
  103807. return index;
  103808. };
  103809. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  103810. this.effectLayers.push(newEffectLayer);
  103811. };
  103812. /**
  103813. * Defines the layer scene component responsible to manage any effect layers
  103814. * in a given scene.
  103815. */
  103816. var EffectLayerSceneComponent = /** @class */ (function () {
  103817. /**
  103818. * Creates a new instance of the component for the given scene
  103819. * @param scene Defines the scene to register the component in
  103820. */
  103821. function EffectLayerSceneComponent(scene) {
  103822. /**
  103823. * The component name helpfull to identify the component in the list of scene components.
  103824. */
  103825. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  103826. this._renderEffects = false;
  103827. this._needStencil = false;
  103828. this._previousStencilState = false;
  103829. this.scene = scene;
  103830. this._engine = scene.getEngine();
  103831. scene.effectLayers = new Array();
  103832. }
  103833. /**
  103834. * Registers the component in a given scene
  103835. */
  103836. EffectLayerSceneComponent.prototype.register = function () {
  103837. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  103838. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  103839. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  103840. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  103841. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  103842. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  103843. };
  103844. /**
  103845. * Rebuilds the elements related to this component in case of
  103846. * context lost for instance.
  103847. */
  103848. EffectLayerSceneComponent.prototype.rebuild = function () {
  103849. var layers = this.scene.effectLayers;
  103850. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  103851. var effectLayer = layers_1[_i];
  103852. effectLayer._rebuild();
  103853. }
  103854. };
  103855. /**
  103856. * Serializes the component data to the specified json object
  103857. * @param serializationObject The object to serialize to
  103858. */
  103859. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  103860. // Effect layers
  103861. serializationObject.effectLayers = [];
  103862. var layers = this.scene.effectLayers;
  103863. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  103864. var effectLayer = layers_2[_i];
  103865. if (effectLayer.serialize) {
  103866. serializationObject.effectLayers.push(effectLayer.serialize());
  103867. }
  103868. }
  103869. };
  103870. /**
  103871. * Adds all the element from the container to the scene
  103872. * @param container the container holding the elements
  103873. */
  103874. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  103875. var _this = this;
  103876. if (!container.effectLayers) {
  103877. return;
  103878. }
  103879. container.effectLayers.forEach(function (o) {
  103880. _this.scene.addEffectLayer(o);
  103881. });
  103882. };
  103883. /**
  103884. * Removes all the elements in the container from the scene
  103885. * @param container contains the elements to remove
  103886. */
  103887. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  103888. var _this = this;
  103889. if (!container.effectLayers) {
  103890. return;
  103891. }
  103892. container.effectLayers.forEach(function (o) {
  103893. _this.scene.removeEffectLayer(o);
  103894. });
  103895. };
  103896. /**
  103897. * Disposes the component and the associated ressources.
  103898. */
  103899. EffectLayerSceneComponent.prototype.dispose = function () {
  103900. var layers = this.scene.effectLayers;
  103901. while (layers.length) {
  103902. layers[0].dispose();
  103903. }
  103904. };
  103905. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  103906. var layers = this.scene.effectLayers;
  103907. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  103908. var layer = layers_3[_i];
  103909. if (!layer.hasMesh(mesh)) {
  103910. continue;
  103911. }
  103912. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  103913. var subMesh = _b[_a];
  103914. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  103915. return false;
  103916. }
  103917. }
  103918. }
  103919. return true;
  103920. };
  103921. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  103922. this._renderEffects = false;
  103923. this._needStencil = false;
  103924. var layers = this.scene.effectLayers;
  103925. if (layers && layers.length > 0) {
  103926. this._previousStencilState = this._engine.getStencilBuffer();
  103927. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  103928. var effectLayer = layers_4[_i];
  103929. if (effectLayer.shouldRender() &&
  103930. (!effectLayer.camera ||
  103931. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  103932. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  103933. this._renderEffects = true;
  103934. this._needStencil = this._needStencil || effectLayer.needStencil();
  103935. var renderTarget = effectLayer._mainTexture;
  103936. if (renderTarget._shouldRender()) {
  103937. this.scene.incrementRenderId();
  103938. renderTarget.render(false, false);
  103939. }
  103940. }
  103941. }
  103942. this.scene.incrementRenderId();
  103943. }
  103944. };
  103945. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  103946. // Activate effect Layer stencil
  103947. if (this._needStencil) {
  103948. this._engine.setStencilBuffer(true);
  103949. }
  103950. };
  103951. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  103952. // Restore effect Layer stencil
  103953. if (this._needStencil) {
  103954. this._engine.setStencilBuffer(this._previousStencilState);
  103955. }
  103956. };
  103957. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  103958. if (this._renderEffects) {
  103959. this._engine.setDepthBuffer(false);
  103960. var layers = this.scene.effectLayers;
  103961. for (var i = 0; i < layers.length; i++) {
  103962. var effectLayer = layers[i];
  103963. if (effectLayer.renderingGroupId === renderingGroupId) {
  103964. if (effectLayer.shouldRender()) {
  103965. effectLayer.render();
  103966. }
  103967. }
  103968. }
  103969. this._engine.setDepthBuffer(true);
  103970. }
  103971. };
  103972. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  103973. if (this._renderEffects) {
  103974. this._draw(-1);
  103975. }
  103976. };
  103977. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  103978. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  103979. this._draw(index);
  103980. }
  103981. };
  103982. return EffectLayerSceneComponent;
  103983. }());
  103984. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  103985. })(BABYLON || (BABYLON = {}));
  103986. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  103987. var __assign = (this && this.__assign) || function () {
  103988. __assign = Object.assign || function(t) {
  103989. for (var s, i = 1, n = arguments.length; i < n; i++) {
  103990. s = arguments[i];
  103991. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  103992. t[p] = s[p];
  103993. }
  103994. return t;
  103995. };
  103996. return __assign.apply(this, arguments);
  103997. };
  103998. var BABYLON;
  103999. (function (BABYLON) {
  104000. /**
  104001. * The effect layer Helps adding post process effect blended with the main pass.
  104002. *
  104003. * This can be for instance use to generate glow or higlight effects on the scene.
  104004. *
  104005. * The effect layer class can not be used directly and is intented to inherited from to be
  104006. * customized per effects.
  104007. */
  104008. var EffectLayer = /** @class */ (function () {
  104009. /**
  104010. * Instantiates a new effect Layer and references it in the scene.
  104011. * @param name The name of the layer
  104012. * @param scene The scene to use the layer in
  104013. */
  104014. function EffectLayer(
  104015. /** The Friendly of the effect in the scene */
  104016. name, scene) {
  104017. this._vertexBuffers = {};
  104018. this._maxSize = 0;
  104019. this._mainTextureDesiredSize = { width: 0, height: 0 };
  104020. this._shouldRender = true;
  104021. this._postProcesses = [];
  104022. this._textures = [];
  104023. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  104024. /**
  104025. * The clear color of the texture used to generate the glow map.
  104026. */
  104027. this.neutralColor = new BABYLON.Color4();
  104028. /**
  104029. * Specifies wether the highlight layer is enabled or not.
  104030. */
  104031. this.isEnabled = true;
  104032. /**
  104033. * An event triggered when the effect layer has been disposed.
  104034. */
  104035. this.onDisposeObservable = new BABYLON.Observable();
  104036. /**
  104037. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  104038. */
  104039. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  104040. /**
  104041. * An event triggered when the generated texture is being merged in the scene.
  104042. */
  104043. this.onBeforeComposeObservable = new BABYLON.Observable();
  104044. /**
  104045. * An event triggered when the generated texture has been merged in the scene.
  104046. */
  104047. this.onAfterComposeObservable = new BABYLON.Observable();
  104048. /**
  104049. * An event triggered when the efffect layer changes its size.
  104050. */
  104051. this.onSizeChangedObservable = new BABYLON.Observable();
  104052. this.name = name;
  104053. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  104054. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  104055. if (!component) {
  104056. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  104057. this._scene._addComponent(component);
  104058. }
  104059. this._engine = this._scene.getEngine();
  104060. this._maxSize = this._engine.getCaps().maxTextureSize;
  104061. this._scene.effectLayers.push(this);
  104062. // Generate Buffers
  104063. this._generateIndexBuffer();
  104064. this._genrateVertexBuffer();
  104065. }
  104066. Object.defineProperty(EffectLayer.prototype, "camera", {
  104067. /**
  104068. * Gets the camera attached to the layer.
  104069. */
  104070. get: function () {
  104071. return this._effectLayerOptions.camera;
  104072. },
  104073. enumerable: true,
  104074. configurable: true
  104075. });
  104076. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  104077. /**
  104078. * Gets the rendering group id the layer should render in.
  104079. */
  104080. get: function () {
  104081. return this._effectLayerOptions.renderingGroupId;
  104082. },
  104083. enumerable: true,
  104084. configurable: true
  104085. });
  104086. /**
  104087. * Initializes the effect layer with the required options.
  104088. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  104089. */
  104090. EffectLayer.prototype._init = function (options) {
  104091. // Adapt options
  104092. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  104093. this._setMainTextureSize();
  104094. this._createMainTexture();
  104095. this._createTextureAndPostProcesses();
  104096. this._mergeEffect = this._createMergeEffect();
  104097. };
  104098. /**
  104099. * Generates the index buffer of the full screen quad blending to the main canvas.
  104100. */
  104101. EffectLayer.prototype._generateIndexBuffer = function () {
  104102. // Indices
  104103. var indices = [];
  104104. indices.push(0);
  104105. indices.push(1);
  104106. indices.push(2);
  104107. indices.push(0);
  104108. indices.push(2);
  104109. indices.push(3);
  104110. this._indexBuffer = this._engine.createIndexBuffer(indices);
  104111. };
  104112. /**
  104113. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  104114. */
  104115. EffectLayer.prototype._genrateVertexBuffer = function () {
  104116. // VBO
  104117. var vertices = [];
  104118. vertices.push(1, 1);
  104119. vertices.push(-1, 1);
  104120. vertices.push(-1, -1);
  104121. vertices.push(1, -1);
  104122. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  104123. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  104124. };
  104125. /**
  104126. * Sets the main texture desired size which is the closest power of two
  104127. * of the engine canvas size.
  104128. */
  104129. EffectLayer.prototype._setMainTextureSize = function () {
  104130. if (this._effectLayerOptions.mainTextureFixedSize) {
  104131. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  104132. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  104133. }
  104134. else {
  104135. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  104136. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  104137. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  104138. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  104139. }
  104140. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  104141. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  104142. };
  104143. /**
  104144. * Creates the main texture for the effect layer.
  104145. */
  104146. EffectLayer.prototype._createMainTexture = function () {
  104147. var _this = this;
  104148. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  104149. width: this._mainTextureDesiredSize.width,
  104150. height: this._mainTextureDesiredSize.height
  104151. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  104152. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  104153. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104154. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104155. this._mainTexture.anisotropicFilteringLevel = 1;
  104156. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  104157. this._mainTexture.renderParticles = false;
  104158. this._mainTexture.renderList = null;
  104159. this._mainTexture.ignoreCameraViewport = true;
  104160. // Custom render function
  104161. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  104162. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  104163. var index;
  104164. var engine = _this._scene.getEngine();
  104165. if (depthOnlySubMeshes.length) {
  104166. engine.setColorWrite(false);
  104167. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  104168. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  104169. }
  104170. engine.setColorWrite(true);
  104171. }
  104172. for (index = 0; index < opaqueSubMeshes.length; index++) {
  104173. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  104174. }
  104175. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  104176. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  104177. }
  104178. for (index = 0; index < transparentSubMeshes.length; index++) {
  104179. _this._renderSubMesh(transparentSubMeshes.data[index]);
  104180. }
  104181. };
  104182. this._mainTexture.onClearObservable.add(function (engine) {
  104183. engine.clear(_this.neutralColor, true, true, true);
  104184. });
  104185. };
  104186. /**
  104187. * Checks for the readiness of the element composing the layer.
  104188. * @param subMesh the mesh to check for
  104189. * @param useInstances specify wether or not to use instances to render the mesh
  104190. * @param emissiveTexture the associated emissive texture used to generate the glow
  104191. * @return true if ready otherwise, false
  104192. */
  104193. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  104194. var material = subMesh.getMaterial();
  104195. if (!material) {
  104196. return false;
  104197. }
  104198. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  104199. return false;
  104200. }
  104201. var defines = [];
  104202. var attribs = [BABYLON.VertexBuffer.PositionKind];
  104203. var mesh = subMesh.getMesh();
  104204. var uv1 = false;
  104205. var uv2 = false;
  104206. // Alpha test
  104207. if (material && material.needAlphaTesting()) {
  104208. var alphaTexture = material.getAlphaTestTexture();
  104209. if (alphaTexture) {
  104210. defines.push("#define ALPHATEST");
  104211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104212. alphaTexture.coordinatesIndex === 1) {
  104213. defines.push("#define DIFFUSEUV2");
  104214. uv2 = true;
  104215. }
  104216. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104217. defines.push("#define DIFFUSEUV1");
  104218. uv1 = true;
  104219. }
  104220. }
  104221. }
  104222. // Emissive
  104223. if (emissiveTexture) {
  104224. defines.push("#define EMISSIVE");
  104225. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  104226. emissiveTexture.coordinatesIndex === 1) {
  104227. defines.push("#define EMISSIVEUV2");
  104228. uv2 = true;
  104229. }
  104230. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  104231. defines.push("#define EMISSIVEUV1");
  104232. uv1 = true;
  104233. }
  104234. }
  104235. if (uv1) {
  104236. attribs.push(BABYLON.VertexBuffer.UVKind);
  104237. defines.push("#define UV1");
  104238. }
  104239. if (uv2) {
  104240. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104241. defines.push("#define UV2");
  104242. }
  104243. // Bones
  104244. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  104245. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  104246. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  104247. if (mesh.numBoneInfluencers > 4) {
  104248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  104249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  104250. }
  104251. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  104252. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  104253. }
  104254. else {
  104255. defines.push("#define NUM_BONE_INFLUENCERS 0");
  104256. }
  104257. // Morph targets
  104258. var manager = mesh.morphTargetManager;
  104259. var morphInfluencers = 0;
  104260. if (manager) {
  104261. if (manager.numInfluencers > 0) {
  104262. defines.push("#define MORPHTARGETS");
  104263. morphInfluencers = manager.numInfluencers;
  104264. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  104265. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  104266. }
  104267. }
  104268. // Instances
  104269. if (useInstances) {
  104270. defines.push("#define INSTANCES");
  104271. attribs.push("world0");
  104272. attribs.push("world1");
  104273. attribs.push("world2");
  104274. attribs.push("world3");
  104275. }
  104276. // Get correct effect
  104277. var join = defines.join("\n");
  104278. if (this._cachedDefines !== join) {
  104279. this._cachedDefines = join;
  104280. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  104281. }
  104282. return this._effectLayerMapGenerationEffect.isReady();
  104283. };
  104284. /**
  104285. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  104286. */
  104287. EffectLayer.prototype.render = function () {
  104288. var currentEffect = this._mergeEffect;
  104289. // Check
  104290. if (!currentEffect.isReady())
  104291. return;
  104292. for (var i = 0; i < this._postProcesses.length; i++) {
  104293. if (!this._postProcesses[i].isReady()) {
  104294. return;
  104295. }
  104296. }
  104297. var engine = this._scene.getEngine();
  104298. this.onBeforeComposeObservable.notifyObservers(this);
  104299. // Render
  104300. engine.enableEffect(currentEffect);
  104301. engine.setState(false);
  104302. // VBOs
  104303. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  104304. // Cache
  104305. var previousAlphaMode = engine.getAlphaMode();
  104306. // Go Blend.
  104307. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  104308. // Blends the map on the main canvas.
  104309. this._internalRender(currentEffect);
  104310. // Restore Alpha
  104311. engine.setAlphaMode(previousAlphaMode);
  104312. this.onAfterComposeObservable.notifyObservers(this);
  104313. // Handle size changes.
  104314. var size = this._mainTexture.getSize();
  104315. this._setMainTextureSize();
  104316. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  104317. // Recreate RTT and post processes on size change.
  104318. this.onSizeChangedObservable.notifyObservers(this);
  104319. this._disposeTextureAndPostProcesses();
  104320. this._createMainTexture();
  104321. this._createTextureAndPostProcesses();
  104322. }
  104323. };
  104324. /**
  104325. * Determine if a given mesh will be used in the current effect.
  104326. * @param mesh mesh to test
  104327. * @returns true if the mesh will be used
  104328. */
  104329. EffectLayer.prototype.hasMesh = function (mesh) {
  104330. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  104331. return true;
  104332. }
  104333. return false;
  104334. };
  104335. /**
  104336. * Returns true if the layer contains information to display, otherwise false.
  104337. * @returns true if the glow layer should be rendered
  104338. */
  104339. EffectLayer.prototype.shouldRender = function () {
  104340. return this.isEnabled && this._shouldRender;
  104341. };
  104342. /**
  104343. * Returns true if the mesh should render, otherwise false.
  104344. * @param mesh The mesh to render
  104345. * @returns true if it should render otherwise false
  104346. */
  104347. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  104348. return true;
  104349. };
  104350. /**
  104351. * Returns true if the mesh should render, otherwise false.
  104352. * @param mesh The mesh to render
  104353. * @returns true if it should render otherwise false
  104354. */
  104355. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  104356. return true;
  104357. };
  104358. /**
  104359. * Renders the submesh passed in parameter to the generation map.
  104360. */
  104361. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  104362. var _this = this;
  104363. if (!this.shouldRender()) {
  104364. return;
  104365. }
  104366. var material = subMesh.getMaterial();
  104367. var mesh = subMesh.getRenderingMesh();
  104368. var scene = this._scene;
  104369. var engine = scene.getEngine();
  104370. if (!material) {
  104371. return;
  104372. }
  104373. // Do not block in blend mode.
  104374. if (material.needAlphaBlendingForMesh(mesh)) {
  104375. return;
  104376. }
  104377. // Culling
  104378. engine.setState(material.backFaceCulling);
  104379. // Managing instances
  104380. var batch = mesh._getInstancesRenderList(subMesh._id);
  104381. if (batch.mustReturn) {
  104382. return;
  104383. }
  104384. // Early Exit per mesh
  104385. if (!this._shouldRenderMesh(mesh)) {
  104386. return;
  104387. }
  104388. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  104389. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  104390. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  104391. engine.enableEffect(this._effectLayerMapGenerationEffect);
  104392. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  104393. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  104394. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  104395. // Alpha test
  104396. if (material && material.needAlphaTesting()) {
  104397. var alphaTexture = material.getAlphaTestTexture();
  104398. if (alphaTexture) {
  104399. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  104400. var textureMatrix = alphaTexture.getTextureMatrix();
  104401. if (textureMatrix) {
  104402. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  104403. }
  104404. }
  104405. }
  104406. // Glow emissive only
  104407. if (this._emissiveTextureAndColor.texture) {
  104408. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  104409. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  104410. }
  104411. // Bones
  104412. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  104413. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  104414. }
  104415. // Morph targets
  104416. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  104417. // Draw
  104418. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  104419. }
  104420. else {
  104421. // Need to reset refresh rate of the main map
  104422. this._mainTexture.resetRefreshCounter();
  104423. }
  104424. };
  104425. /**
  104426. * Rebuild the required buffers.
  104427. * @hidden Internal use only.
  104428. */
  104429. EffectLayer.prototype._rebuild = function () {
  104430. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104431. if (vb) {
  104432. vb._rebuild();
  104433. }
  104434. this._generateIndexBuffer();
  104435. };
  104436. /**
  104437. * Dispose only the render target textures and post process.
  104438. */
  104439. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  104440. this._mainTexture.dispose();
  104441. for (var i = 0; i < this._postProcesses.length; i++) {
  104442. if (this._postProcesses[i]) {
  104443. this._postProcesses[i].dispose();
  104444. }
  104445. }
  104446. this._postProcesses = [];
  104447. for (var i = 0; i < this._textures.length; i++) {
  104448. if (this._textures[i]) {
  104449. this._textures[i].dispose();
  104450. }
  104451. }
  104452. this._textures = [];
  104453. };
  104454. /**
  104455. * Dispose the highlight layer and free resources.
  104456. */
  104457. EffectLayer.prototype.dispose = function () {
  104458. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  104459. if (vertexBuffer) {
  104460. vertexBuffer.dispose();
  104461. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  104462. }
  104463. if (this._indexBuffer) {
  104464. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  104465. this._indexBuffer = null;
  104466. }
  104467. // Clean textures and post processes
  104468. this._disposeTextureAndPostProcesses();
  104469. // Remove from scene
  104470. var index = this._scene.effectLayers.indexOf(this, 0);
  104471. if (index > -1) {
  104472. this._scene.effectLayers.splice(index, 1);
  104473. }
  104474. // Callback
  104475. this.onDisposeObservable.notifyObservers(this);
  104476. this.onDisposeObservable.clear();
  104477. this.onBeforeRenderMainTextureObservable.clear();
  104478. this.onBeforeComposeObservable.clear();
  104479. this.onAfterComposeObservable.clear();
  104480. this.onSizeChangedObservable.clear();
  104481. };
  104482. /**
  104483. * Gets the class name of the effect layer
  104484. * @returns the string with the class name of the effect layer
  104485. */
  104486. EffectLayer.prototype.getClassName = function () {
  104487. return "EffectLayer";
  104488. };
  104489. /**
  104490. * Creates an effect layer from parsed effect layer data
  104491. * @param parsedEffectLayer defines effect layer data
  104492. * @param scene defines the current scene
  104493. * @param rootUrl defines the root URL containing the effect layer information
  104494. * @returns a parsed effect Layer
  104495. */
  104496. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  104497. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  104498. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  104499. };
  104500. __decorate([
  104501. BABYLON.serialize()
  104502. ], EffectLayer.prototype, "name", void 0);
  104503. __decorate([
  104504. BABYLON.serializeAsColor4()
  104505. ], EffectLayer.prototype, "neutralColor", void 0);
  104506. __decorate([
  104507. BABYLON.serialize()
  104508. ], EffectLayer.prototype, "isEnabled", void 0);
  104509. __decorate([
  104510. BABYLON.serializeAsCameraReference()
  104511. ], EffectLayer.prototype, "camera", null);
  104512. __decorate([
  104513. BABYLON.serialize()
  104514. ], EffectLayer.prototype, "renderingGroupId", null);
  104515. return EffectLayer;
  104516. }());
  104517. BABYLON.EffectLayer = EffectLayer;
  104518. })(BABYLON || (BABYLON = {}));
  104519. //# sourceMappingURL=babylon.effectLayer.js.map
  104520. var BABYLON;
  104521. (function (BABYLON) {
  104522. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  104523. for (var index = 0; index < this.effectLayers.length; index++) {
  104524. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  104525. return this.effectLayers[index];
  104526. }
  104527. }
  104528. return null;
  104529. };
  104530. /**
  104531. * Special Glow Blur post process only blurring the alpha channel
  104532. * It enforces keeping the most luminous color in the color channel.
  104533. */
  104534. var GlowBlurPostProcess = /** @class */ (function (_super) {
  104535. __extends(GlowBlurPostProcess, _super);
  104536. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  104537. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  104538. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  104539. _this.direction = direction;
  104540. _this.kernel = kernel;
  104541. _this.onApplyObservable.add(function (effect) {
  104542. effect.setFloat2("screenSize", _this.width, _this.height);
  104543. effect.setVector2("direction", _this.direction);
  104544. effect.setFloat("blurWidth", _this.kernel);
  104545. });
  104546. return _this;
  104547. }
  104548. return GlowBlurPostProcess;
  104549. }(BABYLON.PostProcess));
  104550. /**
  104551. * The highlight layer Helps adding a glow effect around a mesh.
  104552. *
  104553. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  104554. * glowy meshes to your scene.
  104555. *
  104556. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  104557. */
  104558. var HighlightLayer = /** @class */ (function (_super) {
  104559. __extends(HighlightLayer, _super);
  104560. /**
  104561. * Instantiates a new highlight Layer and references it to the scene..
  104562. * @param name The name of the layer
  104563. * @param scene The scene to use the layer in
  104564. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  104565. */
  104566. function HighlightLayer(name, scene, options) {
  104567. var _this = _super.call(this, name, scene) || this;
  104568. _this.name = name;
  104569. /**
  104570. * Specifies whether or not the inner glow is ACTIVE in the layer.
  104571. */
  104572. _this.innerGlow = true;
  104573. /**
  104574. * Specifies whether or not the outer glow is ACTIVE in the layer.
  104575. */
  104576. _this.outerGlow = true;
  104577. /**
  104578. * An event triggered when the highlight layer is being blurred.
  104579. */
  104580. _this.onBeforeBlurObservable = new BABYLON.Observable();
  104581. /**
  104582. * An event triggered when the highlight layer has been blurred.
  104583. */
  104584. _this.onAfterBlurObservable = new BABYLON.Observable();
  104585. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  104586. _this._meshes = {};
  104587. _this._excludedMeshes = {};
  104588. _this.neutralColor = HighlightLayer.NeutralColor;
  104589. // Warn on stencil
  104590. if (!_this._engine.isStencilEnable) {
  104591. 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 }");
  104592. }
  104593. // Adapt options
  104594. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  104595. // Initialize the layer
  104596. _this._init({
  104597. alphaBlendingMode: _this._options.alphaBlendingMode,
  104598. camera: _this._options.camera,
  104599. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  104600. mainTextureRatio: _this._options.mainTextureRatio,
  104601. renderingGroupId: _this._options.renderingGroupId
  104602. });
  104603. // Do not render as long as no meshes have been added
  104604. _this._shouldRender = false;
  104605. return _this;
  104606. }
  104607. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  104608. /**
  104609. * Gets the horizontal size of the blur.
  104610. */
  104611. get: function () {
  104612. return this._horizontalBlurPostprocess.kernel;
  104613. },
  104614. /**
  104615. * Specifies the horizontal size of the blur.
  104616. */
  104617. set: function (value) {
  104618. this._horizontalBlurPostprocess.kernel = value;
  104619. },
  104620. enumerable: true,
  104621. configurable: true
  104622. });
  104623. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  104624. /**
  104625. * Gets the vertical size of the blur.
  104626. */
  104627. get: function () {
  104628. return this._verticalBlurPostprocess.kernel;
  104629. },
  104630. /**
  104631. * Specifies the vertical size of the blur.
  104632. */
  104633. set: function (value) {
  104634. this._verticalBlurPostprocess.kernel = value;
  104635. },
  104636. enumerable: true,
  104637. configurable: true
  104638. });
  104639. /**
  104640. * Get the effect name of the layer.
  104641. * @return The effect name
  104642. */
  104643. HighlightLayer.prototype.getEffectName = function () {
  104644. return HighlightLayer.EffectName;
  104645. };
  104646. /**
  104647. * Create the merge effect. This is the shader use to blit the information back
  104648. * to the main canvas at the end of the scene rendering.
  104649. */
  104650. HighlightLayer.prototype._createMergeEffect = function () {
  104651. // Effect
  104652. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  104653. };
  104654. /**
  104655. * Creates the render target textures and post processes used in the highlight layer.
  104656. */
  104657. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  104658. var _this = this;
  104659. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  104660. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  104661. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  104662. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  104663. var textureType = 0;
  104664. if (this._engine.getCaps().textureHalfFloatRender) {
  104665. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  104666. }
  104667. else {
  104668. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  104669. }
  104670. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  104671. width: blurTextureWidth,
  104672. height: blurTextureHeight
  104673. }, this._scene, false, true, textureType);
  104674. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104675. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  104676. this._blurTexture.anisotropicFilteringLevel = 16;
  104677. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  104678. this._blurTexture.renderParticles = false;
  104679. this._blurTexture.ignoreCameraViewport = true;
  104680. this._textures = [this._blurTexture];
  104681. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  104682. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104683. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  104684. effect.setTexture("textureSampler", _this._mainTexture);
  104685. });
  104686. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104687. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  104688. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  104689. });
  104690. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  104691. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  104692. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  104693. });
  104694. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  104695. }
  104696. else {
  104697. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  104698. width: blurTextureWidth,
  104699. height: blurTextureHeight
  104700. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  104701. this._horizontalBlurPostprocess.width = blurTextureWidth;
  104702. this._horizontalBlurPostprocess.height = blurTextureHeight;
  104703. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  104704. effect.setTexture("textureSampler", _this._mainTexture);
  104705. });
  104706. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  104707. width: blurTextureWidth,
  104708. height: blurTextureHeight
  104709. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  104710. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  104711. }
  104712. this._mainTexture.onAfterUnbindObservable.add(function () {
  104713. _this.onBeforeBlurObservable.notifyObservers(_this);
  104714. var internalTexture = _this._blurTexture.getInternalTexture();
  104715. if (internalTexture) {
  104716. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  104717. }
  104718. _this.onAfterBlurObservable.notifyObservers(_this);
  104719. });
  104720. // Prevent autoClear.
  104721. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  104722. };
  104723. /**
  104724. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  104725. */
  104726. HighlightLayer.prototype.needStencil = function () {
  104727. return true;
  104728. };
  104729. /**
  104730. * Checks for the readiness of the element composing the layer.
  104731. * @param subMesh the mesh to check for
  104732. * @param useInstances specify wether or not to use instances to render the mesh
  104733. * @param emissiveTexture the associated emissive texture used to generate the glow
  104734. * @return true if ready otherwise, false
  104735. */
  104736. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  104737. var material = subMesh.getMaterial();
  104738. var mesh = subMesh.getRenderingMesh();
  104739. if (!material || !mesh || !this._meshes) {
  104740. return false;
  104741. }
  104742. var emissiveTexture = null;
  104743. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  104744. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  104745. emissiveTexture = material.emissiveTexture;
  104746. }
  104747. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  104748. };
  104749. /**
  104750. * Implementation specific of rendering the generating effect on the main canvas.
  104751. * @param effect The effect used to render through
  104752. */
  104753. HighlightLayer.prototype._internalRender = function (effect) {
  104754. // Texture
  104755. effect.setTexture("textureSampler", this._blurTexture);
  104756. // Cache
  104757. var engine = this._engine;
  104758. var previousStencilBuffer = engine.getStencilBuffer();
  104759. var previousStencilFunction = engine.getStencilFunction();
  104760. var previousStencilMask = engine.getStencilMask();
  104761. var previousStencilOperationPass = engine.getStencilOperationPass();
  104762. var previousStencilOperationFail = engine.getStencilOperationFail();
  104763. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  104764. var previousStencilReference = engine.getStencilFunctionReference();
  104765. // Stencil operations
  104766. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  104767. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  104768. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  104769. // Draw order
  104770. engine.setStencilMask(0x00);
  104771. engine.setStencilBuffer(true);
  104772. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  104773. // 2 passes inner outer
  104774. if (this.outerGlow) {
  104775. effect.setFloat("offset", 0);
  104776. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  104777. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104778. }
  104779. if (this.innerGlow) {
  104780. effect.setFloat("offset", 1);
  104781. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  104782. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  104783. }
  104784. // Restore Cache
  104785. engine.setStencilFunction(previousStencilFunction);
  104786. engine.setStencilMask(previousStencilMask);
  104787. engine.setStencilBuffer(previousStencilBuffer);
  104788. engine.setStencilOperationPass(previousStencilOperationPass);
  104789. engine.setStencilOperationFail(previousStencilOperationFail);
  104790. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  104791. engine.setStencilFunctionReference(previousStencilReference);
  104792. };
  104793. /**
  104794. * Returns true if the layer contains information to display, otherwise false.
  104795. */
  104796. HighlightLayer.prototype.shouldRender = function () {
  104797. if (_super.prototype.shouldRender.call(this)) {
  104798. return this._meshes ? true : false;
  104799. }
  104800. return false;
  104801. };
  104802. /**
  104803. * Returns true if the mesh should render, otherwise false.
  104804. * @param mesh The mesh to render
  104805. * @returns true if it should render otherwise false
  104806. */
  104807. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  104808. // Excluded Mesh
  104809. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  104810. return false;
  104811. }
  104812. ;
  104813. if (!_super.prototype.hasMesh.call(this, mesh)) {
  104814. return false;
  104815. }
  104816. return true;
  104817. };
  104818. /**
  104819. * Sets the required values for both the emissive texture and and the main color.
  104820. */
  104821. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  104822. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  104823. if (highlightLayerMesh) {
  104824. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  104825. }
  104826. else {
  104827. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  104828. }
  104829. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  104830. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  104831. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  104832. }
  104833. else {
  104834. this._emissiveTextureAndColor.texture = null;
  104835. }
  104836. };
  104837. /**
  104838. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  104839. * @param mesh The mesh to exclude from the highlight layer
  104840. */
  104841. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  104842. if (!this._excludedMeshes) {
  104843. return;
  104844. }
  104845. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  104846. if (!meshExcluded) {
  104847. this._excludedMeshes[mesh.uniqueId] = {
  104848. mesh: mesh,
  104849. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  104850. mesh.getEngine().setStencilBuffer(false);
  104851. }),
  104852. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  104853. mesh.getEngine().setStencilBuffer(true);
  104854. }),
  104855. };
  104856. }
  104857. };
  104858. /**
  104859. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  104860. * @param mesh The mesh to highlight
  104861. */
  104862. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  104863. if (!this._excludedMeshes) {
  104864. return;
  104865. }
  104866. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  104867. if (meshExcluded) {
  104868. if (meshExcluded.beforeRender) {
  104869. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  104870. }
  104871. if (meshExcluded.afterRender) {
  104872. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  104873. }
  104874. }
  104875. this._excludedMeshes[mesh.uniqueId] = null;
  104876. };
  104877. /**
  104878. * Determine if a given mesh will be highlighted by the current HighlightLayer
  104879. * @param mesh mesh to test
  104880. * @returns true if the mesh will be highlighted by the current HighlightLayer
  104881. */
  104882. HighlightLayer.prototype.hasMesh = function (mesh) {
  104883. if (!this._meshes) {
  104884. return false;
  104885. }
  104886. if (!_super.prototype.hasMesh.call(this, mesh)) {
  104887. return false;
  104888. }
  104889. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  104890. };
  104891. /**
  104892. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  104893. * @param mesh The mesh to highlight
  104894. * @param color The color of the highlight
  104895. * @param glowEmissiveOnly Extract the glow from the emissive texture
  104896. */
  104897. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  104898. var _this = this;
  104899. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  104900. if (!this._meshes) {
  104901. return;
  104902. }
  104903. var meshHighlight = this._meshes[mesh.uniqueId];
  104904. if (meshHighlight) {
  104905. meshHighlight.color = color;
  104906. }
  104907. else {
  104908. this._meshes[mesh.uniqueId] = {
  104909. mesh: mesh,
  104910. color: color,
  104911. // Lambda required for capture due to Observable this context
  104912. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  104913. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  104914. _this._defaultStencilReference(mesh);
  104915. }
  104916. else {
  104917. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  104918. }
  104919. }),
  104920. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  104921. glowEmissiveOnly: glowEmissiveOnly
  104922. };
  104923. mesh.onDisposeObservable.add(function () {
  104924. _this._disposeMesh(mesh);
  104925. });
  104926. }
  104927. this._shouldRender = true;
  104928. };
  104929. /**
  104930. * Remove a mesh from the highlight layer in order to make it stop glowing.
  104931. * @param mesh The mesh to highlight
  104932. */
  104933. HighlightLayer.prototype.removeMesh = function (mesh) {
  104934. if (!this._meshes) {
  104935. return;
  104936. }
  104937. var meshHighlight = this._meshes[mesh.uniqueId];
  104938. if (meshHighlight) {
  104939. if (meshHighlight.observerHighlight) {
  104940. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  104941. }
  104942. if (meshHighlight.observerDefault) {
  104943. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  104944. }
  104945. delete this._meshes[mesh.uniqueId];
  104946. }
  104947. this._shouldRender = false;
  104948. for (var meshHighlightToCheck in this._meshes) {
  104949. if (this._meshes[meshHighlightToCheck]) {
  104950. this._shouldRender = true;
  104951. break;
  104952. }
  104953. }
  104954. };
  104955. /**
  104956. * Force the stencil to the normal expected value for none glowing parts
  104957. */
  104958. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  104959. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  104960. };
  104961. /**
  104962. * Free any resources and references associated to a mesh.
  104963. * Internal use
  104964. * @param mesh The mesh to free.
  104965. * @hidden
  104966. */
  104967. HighlightLayer.prototype._disposeMesh = function (mesh) {
  104968. this.removeMesh(mesh);
  104969. this.removeExcludedMesh(mesh);
  104970. };
  104971. /**
  104972. * Dispose the highlight layer and free resources.
  104973. */
  104974. HighlightLayer.prototype.dispose = function () {
  104975. if (this._meshes) {
  104976. // Clean mesh references
  104977. for (var id in this._meshes) {
  104978. var meshHighlight = this._meshes[id];
  104979. if (meshHighlight && meshHighlight.mesh) {
  104980. if (meshHighlight.observerHighlight) {
  104981. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  104982. }
  104983. if (meshHighlight.observerDefault) {
  104984. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  104985. }
  104986. }
  104987. }
  104988. this._meshes = null;
  104989. }
  104990. if (this._excludedMeshes) {
  104991. for (var id in this._excludedMeshes) {
  104992. var meshHighlight = this._excludedMeshes[id];
  104993. if (meshHighlight) {
  104994. if (meshHighlight.beforeRender) {
  104995. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  104996. }
  104997. if (meshHighlight.afterRender) {
  104998. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  104999. }
  105000. }
  105001. }
  105002. this._excludedMeshes = null;
  105003. }
  105004. _super.prototype.dispose.call(this);
  105005. };
  105006. /**
  105007. * Gets the class name of the effect layer
  105008. * @returns the string with the class name of the effect layer
  105009. */
  105010. HighlightLayer.prototype.getClassName = function () {
  105011. return "HighlightLayer";
  105012. };
  105013. /**
  105014. * Serializes this Highlight layer
  105015. * @returns a serialized Highlight layer object
  105016. */
  105017. HighlightLayer.prototype.serialize = function () {
  105018. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105019. serializationObject.customType = "BABYLON.HighlightLayer";
  105020. // Highlighted meshes
  105021. serializationObject.meshes = [];
  105022. if (this._meshes) {
  105023. for (var m in this._meshes) {
  105024. var mesh = this._meshes[m];
  105025. if (mesh) {
  105026. serializationObject.meshes.push({
  105027. glowEmissiveOnly: mesh.glowEmissiveOnly,
  105028. color: mesh.color.asArray(),
  105029. meshId: mesh.mesh.id
  105030. });
  105031. }
  105032. }
  105033. }
  105034. // Excluded meshes
  105035. serializationObject.excludedMeshes = [];
  105036. if (this._excludedMeshes) {
  105037. for (var e in this._excludedMeshes) {
  105038. var excludedMesh = this._excludedMeshes[e];
  105039. if (excludedMesh) {
  105040. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  105041. }
  105042. }
  105043. }
  105044. return serializationObject;
  105045. };
  105046. /**
  105047. * Creates a Highlight layer from parsed Highlight layer data
  105048. * @param parsedHightlightLayer defines the Highlight layer data
  105049. * @param scene defines the current scene
  105050. * @param rootUrl defines the root URL containing the Highlight layer information
  105051. * @returns a parsed Highlight layer
  105052. */
  105053. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  105054. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  105055. var index;
  105056. // Excluded meshes
  105057. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  105058. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  105059. if (mesh) {
  105060. hl.addExcludedMesh(mesh);
  105061. }
  105062. }
  105063. // Included meshes
  105064. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  105065. var highlightedMesh = parsedHightlightLayer.meshes[index];
  105066. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  105067. if (mesh) {
  105068. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  105069. }
  105070. }
  105071. return hl;
  105072. };
  105073. /**
  105074. * Effect Name of the highlight layer.
  105075. */
  105076. HighlightLayer.EffectName = "HighlightLayer";
  105077. /**
  105078. * The neutral color used during the preparation of the glow effect.
  105079. * This is black by default as the blend operation is a blend operation.
  105080. */
  105081. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  105082. /**
  105083. * Stencil value used for glowing meshes.
  105084. */
  105085. HighlightLayer.GlowingMeshStencilReference = 0x02;
  105086. /**
  105087. * Stencil value used for the other meshes in the scene.
  105088. */
  105089. HighlightLayer.NormalMeshStencilReference = 0x01;
  105090. __decorate([
  105091. BABYLON.serialize()
  105092. ], HighlightLayer.prototype, "innerGlow", void 0);
  105093. __decorate([
  105094. BABYLON.serialize()
  105095. ], HighlightLayer.prototype, "outerGlow", void 0);
  105096. __decorate([
  105097. BABYLON.serialize()
  105098. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  105099. __decorate([
  105100. BABYLON.serialize()
  105101. ], HighlightLayer.prototype, "blurVerticalSize", null);
  105102. __decorate([
  105103. BABYLON.serialize("options")
  105104. ], HighlightLayer.prototype, "_options", void 0);
  105105. return HighlightLayer;
  105106. }(BABYLON.EffectLayer));
  105107. BABYLON.HighlightLayer = HighlightLayer;
  105108. })(BABYLON || (BABYLON = {}));
  105109. //# sourceMappingURL=babylon.highlightLayer.js.map
  105110. var BABYLON;
  105111. (function (BABYLON) {
  105112. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  105113. for (var index = 0; index < this.effectLayers.length; index++) {
  105114. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  105115. return this.effectLayers[index];
  105116. }
  105117. }
  105118. return null;
  105119. };
  105120. /**
  105121. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  105122. *
  105123. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  105124. * glowy meshes to your scene.
  105125. *
  105126. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  105127. */
  105128. var GlowLayer = /** @class */ (function (_super) {
  105129. __extends(GlowLayer, _super);
  105130. /**
  105131. * Instantiates a new glow Layer and references it to the scene.
  105132. * @param name The name of the layer
  105133. * @param scene The scene to use the layer in
  105134. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  105135. */
  105136. function GlowLayer(name, scene, options) {
  105137. var _this = _super.call(this, name, scene) || this;
  105138. _this._intensity = 1.0;
  105139. _this._includedOnlyMeshes = [];
  105140. _this._excludedMeshes = [];
  105141. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  105142. // Adapt options
  105143. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  105144. // Initialize the layer
  105145. _this._init({
  105146. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  105147. camera: _this._options.camera,
  105148. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  105149. mainTextureRatio: _this._options.mainTextureRatio,
  105150. renderingGroupId: _this._options.renderingGroupId
  105151. });
  105152. return _this;
  105153. }
  105154. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  105155. /**
  105156. * Gets the kernel size of the blur.
  105157. */
  105158. get: function () {
  105159. return this._horizontalBlurPostprocess1.kernel;
  105160. },
  105161. /**
  105162. * Sets the kernel size of the blur.
  105163. */
  105164. set: function (value) {
  105165. this._horizontalBlurPostprocess1.kernel = value;
  105166. this._verticalBlurPostprocess1.kernel = value;
  105167. this._horizontalBlurPostprocess2.kernel = value;
  105168. this._verticalBlurPostprocess2.kernel = value;
  105169. },
  105170. enumerable: true,
  105171. configurable: true
  105172. });
  105173. Object.defineProperty(GlowLayer.prototype, "intensity", {
  105174. /**
  105175. * Gets the glow intensity.
  105176. */
  105177. get: function () {
  105178. return this._intensity;
  105179. },
  105180. /**
  105181. * Sets the glow intensity.
  105182. */
  105183. set: function (value) {
  105184. this._intensity = value;
  105185. },
  105186. enumerable: true,
  105187. configurable: true
  105188. });
  105189. /**
  105190. * Get the effect name of the layer.
  105191. * @return The effect name
  105192. */
  105193. GlowLayer.prototype.getEffectName = function () {
  105194. return GlowLayer.EffectName;
  105195. };
  105196. /**
  105197. * Create the merge effect. This is the shader use to blit the information back
  105198. * to the main canvas at the end of the scene rendering.
  105199. */
  105200. GlowLayer.prototype._createMergeEffect = function () {
  105201. // Effect
  105202. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  105203. };
  105204. /**
  105205. * Creates the render target textures and post processes used in the glow layer.
  105206. */
  105207. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  105208. var _this = this;
  105209. var blurTextureWidth = this._mainTextureDesiredSize.width;
  105210. var blurTextureHeight = this._mainTextureDesiredSize.height;
  105211. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  105212. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  105213. var textureType = 0;
  105214. if (this._engine.getCaps().textureHalfFloatRender) {
  105215. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  105216. }
  105217. else {
  105218. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  105219. }
  105220. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  105221. width: blurTextureWidth,
  105222. height: blurTextureHeight
  105223. }, this._scene, false, true, textureType);
  105224. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105225. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105226. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105227. this._blurTexture1.renderParticles = false;
  105228. this._blurTexture1.ignoreCameraViewport = true;
  105229. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  105230. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  105231. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  105232. width: blurTextureWidth2,
  105233. height: blurTextureHeight2
  105234. }, this._scene, false, true, textureType);
  105235. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105236. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105237. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  105238. this._blurTexture2.renderParticles = false;
  105239. this._blurTexture2.ignoreCameraViewport = true;
  105240. this._textures = [this._blurTexture1, this._blurTexture2];
  105241. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105242. width: blurTextureWidth,
  105243. height: blurTextureHeight
  105244. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105245. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  105246. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  105247. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  105248. effect.setTexture("textureSampler", _this._mainTexture);
  105249. });
  105250. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105251. width: blurTextureWidth,
  105252. height: blurTextureHeight
  105253. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105254. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  105255. width: blurTextureWidth2,
  105256. height: blurTextureHeight2
  105257. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105258. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  105259. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  105260. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  105261. effect.setTexture("textureSampler", _this._blurTexture1);
  105262. });
  105263. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  105264. width: blurTextureWidth2,
  105265. height: blurTextureHeight2
  105266. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  105267. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105268. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  105269. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  105270. this._mainTexture.samples = this._options.mainTextureSamples;
  105271. this._mainTexture.onAfterUnbindObservable.add(function () {
  105272. var internalTexture = _this._blurTexture1.getInternalTexture();
  105273. if (internalTexture) {
  105274. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  105275. internalTexture = _this._blurTexture2.getInternalTexture();
  105276. if (internalTexture) {
  105277. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  105278. }
  105279. }
  105280. });
  105281. // Prevent autoClear.
  105282. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  105283. };
  105284. /**
  105285. * Checks for the readiness of the element composing the layer.
  105286. * @param subMesh the mesh to check for
  105287. * @param useInstances specify wether or not to use instances to render the mesh
  105288. * @param emissiveTexture the associated emissive texture used to generate the glow
  105289. * @return true if ready otherwise, false
  105290. */
  105291. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  105292. var material = subMesh.getMaterial();
  105293. var mesh = subMesh.getRenderingMesh();
  105294. if (!material || !mesh) {
  105295. return false;
  105296. }
  105297. var emissiveTexture = material.emissiveTexture;
  105298. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  105299. };
  105300. /**
  105301. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  105302. */
  105303. GlowLayer.prototype.needStencil = function () {
  105304. return false;
  105305. };
  105306. /**
  105307. * Implementation specific of rendering the generating effect on the main canvas.
  105308. * @param effect The effect used to render through
  105309. */
  105310. GlowLayer.prototype._internalRender = function (effect) {
  105311. // Texture
  105312. effect.setTexture("textureSampler", this._blurTexture1);
  105313. effect.setTexture("textureSampler2", this._blurTexture2);
  105314. effect.setFloat("offset", this._intensity);
  105315. // Cache
  105316. var engine = this._engine;
  105317. var previousStencilBuffer = engine.getStencilBuffer();
  105318. // Draw order
  105319. engine.setStencilBuffer(false);
  105320. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  105321. // Draw order
  105322. engine.setStencilBuffer(previousStencilBuffer);
  105323. };
  105324. /**
  105325. * Sets the required values for both the emissive texture and and the main color.
  105326. */
  105327. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  105328. var textureLevel = 1.0;
  105329. if (this.customEmissiveTextureSelector) {
  105330. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  105331. }
  105332. else {
  105333. if (material) {
  105334. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  105335. if (this._emissiveTextureAndColor.texture) {
  105336. textureLevel = this._emissiveTextureAndColor.texture.level;
  105337. }
  105338. }
  105339. else {
  105340. this._emissiveTextureAndColor.texture = null;
  105341. }
  105342. }
  105343. if (this.customEmissiveColorSelector) {
  105344. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  105345. }
  105346. else {
  105347. if (material.emissiveColor) {
  105348. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  105349. }
  105350. else {
  105351. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  105352. }
  105353. }
  105354. };
  105355. /**
  105356. * Returns true if the mesh should render, otherwise false.
  105357. * @param mesh The mesh to render
  105358. * @returns true if it should render otherwise false
  105359. */
  105360. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  105361. return this.hasMesh(mesh);
  105362. };
  105363. /**
  105364. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  105365. * @param mesh The mesh to exclude from the glow layer
  105366. */
  105367. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  105368. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  105369. this._excludedMeshes.push(mesh.uniqueId);
  105370. }
  105371. };
  105372. /**
  105373. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  105374. * @param mesh The mesh to remove
  105375. */
  105376. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  105377. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  105378. if (index !== -1) {
  105379. this._excludedMeshes.splice(index, 1);
  105380. }
  105381. };
  105382. /**
  105383. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  105384. * @param mesh The mesh to include in the glow layer
  105385. */
  105386. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  105387. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  105388. this._includedOnlyMeshes.push(mesh.uniqueId);
  105389. }
  105390. };
  105391. /**
  105392. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  105393. * @param mesh The mesh to remove
  105394. */
  105395. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  105396. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  105397. if (index !== -1) {
  105398. this._includedOnlyMeshes.splice(index, 1);
  105399. }
  105400. };
  105401. /**
  105402. * Determine if a given mesh will be used in the glow layer
  105403. * @param mesh The mesh to test
  105404. * @returns true if the mesh will be highlighted by the current glow layer
  105405. */
  105406. GlowLayer.prototype.hasMesh = function (mesh) {
  105407. if (!_super.prototype.hasMesh.call(this, mesh)) {
  105408. return false;
  105409. }
  105410. // Included Mesh
  105411. if (this._includedOnlyMeshes.length) {
  105412. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  105413. }
  105414. ;
  105415. // Excluded Mesh
  105416. if (this._excludedMeshes.length) {
  105417. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  105418. }
  105419. ;
  105420. return true;
  105421. };
  105422. /**
  105423. * Free any resources and references associated to a mesh.
  105424. * Internal use
  105425. * @param mesh The mesh to free.
  105426. * @hidden
  105427. */
  105428. GlowLayer.prototype._disposeMesh = function (mesh) {
  105429. this.removeIncludedOnlyMesh(mesh);
  105430. this.removeExcludedMesh(mesh);
  105431. };
  105432. /**
  105433. * Gets the class name of the effect layer
  105434. * @returns the string with the class name of the effect layer
  105435. */
  105436. GlowLayer.prototype.getClassName = function () {
  105437. return "GlowLayer";
  105438. };
  105439. /**
  105440. * Serializes this glow layer
  105441. * @returns a serialized glow layer object
  105442. */
  105443. GlowLayer.prototype.serialize = function () {
  105444. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  105445. serializationObject.customType = "BABYLON.GlowLayer";
  105446. var index;
  105447. // Included meshes
  105448. serializationObject.includedMeshes = [];
  105449. if (this._includedOnlyMeshes.length) {
  105450. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  105451. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  105452. if (mesh) {
  105453. serializationObject.includedMeshes.push(mesh.id);
  105454. }
  105455. }
  105456. }
  105457. // Excluded meshes
  105458. serializationObject.excludedMeshes = [];
  105459. if (this._excludedMeshes.length) {
  105460. for (index = 0; index < this._excludedMeshes.length; index++) {
  105461. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  105462. if (mesh) {
  105463. serializationObject.excludedMeshes.push(mesh.id);
  105464. }
  105465. }
  105466. }
  105467. return serializationObject;
  105468. };
  105469. /**
  105470. * Creates a Glow Layer from parsed glow layer data
  105471. * @param parsedGlowLayer defines glow layer data
  105472. * @param scene defines the current scene
  105473. * @param rootUrl defines the root URL containing the glow layer information
  105474. * @returns a parsed Glow Layer
  105475. */
  105476. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  105477. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  105478. var index;
  105479. // Excluded meshes
  105480. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  105481. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  105482. if (mesh) {
  105483. gl.addExcludedMesh(mesh);
  105484. }
  105485. }
  105486. // Included meshes
  105487. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  105488. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  105489. if (mesh) {
  105490. gl.addIncludedOnlyMesh(mesh);
  105491. }
  105492. }
  105493. return gl;
  105494. };
  105495. /**
  105496. * Effect Name of the layer.
  105497. */
  105498. GlowLayer.EffectName = "GlowLayer";
  105499. /**
  105500. * The default blur kernel size used for the glow.
  105501. */
  105502. GlowLayer.DefaultBlurKernelSize = 32;
  105503. /**
  105504. * The default texture size ratio used for the glow.
  105505. */
  105506. GlowLayer.DefaultTextureRatio = 0.5;
  105507. __decorate([
  105508. BABYLON.serialize()
  105509. ], GlowLayer.prototype, "blurKernelSize", null);
  105510. __decorate([
  105511. BABYLON.serialize()
  105512. ], GlowLayer.prototype, "intensity", null);
  105513. __decorate([
  105514. BABYLON.serialize("options")
  105515. ], GlowLayer.prototype, "_options", void 0);
  105516. return GlowLayer;
  105517. }(BABYLON.EffectLayer));
  105518. BABYLON.GlowLayer = GlowLayer;
  105519. })(BABYLON || (BABYLON = {}));
  105520. //# sourceMappingURL=babylon.glowLayer.js.map
  105521. var BABYLON;
  105522. (function (BABYLON) {
  105523. /**
  105524. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  105525. */
  105526. var AssetTaskState;
  105527. (function (AssetTaskState) {
  105528. /**
  105529. * Initialization
  105530. */
  105531. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  105532. /**
  105533. * Running
  105534. */
  105535. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  105536. /**
  105537. * Done
  105538. */
  105539. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  105540. /**
  105541. * Error
  105542. */
  105543. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  105544. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  105545. /**
  105546. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  105547. */
  105548. var AbstractAssetTask = /** @class */ (function () {
  105549. /**
  105550. * Creates a new {BABYLON.AssetsManager}
  105551. * @param name defines the name of the task
  105552. */
  105553. function AbstractAssetTask(
  105554. /**
  105555. * Task name
  105556. */ name) {
  105557. this.name = name;
  105558. this._isCompleted = false;
  105559. this._taskState = AssetTaskState.INIT;
  105560. }
  105561. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  105562. /**
  105563. * Get if the task is completed
  105564. */
  105565. get: function () {
  105566. return this._isCompleted;
  105567. },
  105568. enumerable: true,
  105569. configurable: true
  105570. });
  105571. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  105572. /**
  105573. * Gets the current state of the task
  105574. */
  105575. get: function () {
  105576. return this._taskState;
  105577. },
  105578. enumerable: true,
  105579. configurable: true
  105580. });
  105581. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  105582. /**
  105583. * Gets the current error object (if task is in error)
  105584. */
  105585. get: function () {
  105586. return this._errorObject;
  105587. },
  105588. enumerable: true,
  105589. configurable: true
  105590. });
  105591. /**
  105592. * Internal only
  105593. * @hidden
  105594. */
  105595. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  105596. if (this._errorObject) {
  105597. return;
  105598. }
  105599. this._errorObject = {
  105600. message: message,
  105601. exception: exception
  105602. };
  105603. };
  105604. /**
  105605. * Execute the current task
  105606. * @param scene defines the scene where you want your assets to be loaded
  105607. * @param onSuccess is a callback called when the task is successfully executed
  105608. * @param onError is a callback called if an error occurs
  105609. */
  105610. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  105611. var _this = this;
  105612. this._taskState = AssetTaskState.RUNNING;
  105613. this.runTask(scene, function () {
  105614. _this.onDoneCallback(onSuccess, onError);
  105615. }, function (msg, exception) {
  105616. _this.onErrorCallback(onError, msg, exception);
  105617. });
  105618. };
  105619. /**
  105620. * Execute the current task
  105621. * @param scene defines the scene where you want your assets to be loaded
  105622. * @param onSuccess is a callback called when the task is successfully executed
  105623. * @param onError is a callback called if an error occurs
  105624. */
  105625. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105626. throw new Error("runTask is not implemented");
  105627. };
  105628. /**
  105629. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  105630. * This can be used with failed tasks that have the reason for failure fixed.
  105631. */
  105632. AbstractAssetTask.prototype.reset = function () {
  105633. this._taskState = AssetTaskState.INIT;
  105634. };
  105635. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  105636. this._taskState = AssetTaskState.ERROR;
  105637. this._errorObject = {
  105638. message: message,
  105639. exception: exception
  105640. };
  105641. if (this.onError) {
  105642. this.onError(this, message, exception);
  105643. }
  105644. onError();
  105645. };
  105646. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  105647. try {
  105648. this._taskState = AssetTaskState.DONE;
  105649. this._isCompleted = true;
  105650. if (this.onSuccess) {
  105651. this.onSuccess(this);
  105652. }
  105653. onSuccess();
  105654. }
  105655. catch (e) {
  105656. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  105657. }
  105658. };
  105659. return AbstractAssetTask;
  105660. }());
  105661. BABYLON.AbstractAssetTask = AbstractAssetTask;
  105662. /**
  105663. * Class used to share progress information about assets loading
  105664. */
  105665. var AssetsProgressEvent = /** @class */ (function () {
  105666. /**
  105667. * Creates a {BABYLON.AssetsProgressEvent}
  105668. * @param remainingCount defines the number of remaining tasks to process
  105669. * @param totalCount defines the total number of tasks
  105670. * @param task defines the task that was just processed
  105671. */
  105672. function AssetsProgressEvent(remainingCount, totalCount, task) {
  105673. this.remainingCount = remainingCount;
  105674. this.totalCount = totalCount;
  105675. this.task = task;
  105676. }
  105677. return AssetsProgressEvent;
  105678. }());
  105679. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  105680. /**
  105681. * Define a task used by {BABYLON.AssetsManager} to load meshes
  105682. */
  105683. var MeshAssetTask = /** @class */ (function (_super) {
  105684. __extends(MeshAssetTask, _super);
  105685. /**
  105686. * Creates a new {BABYLON.MeshAssetTask}
  105687. * @param name defines the name of the task
  105688. * @param meshesNames defines the list of mesh's names you want to load
  105689. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  105690. * @param sceneFilename defines the filename of the scene to load from
  105691. */
  105692. function MeshAssetTask(
  105693. /**
  105694. * Defines the name of the task
  105695. */
  105696. name,
  105697. /**
  105698. * Defines the list of mesh's names you want to load
  105699. */
  105700. meshesNames,
  105701. /**
  105702. * Defines the root url to use as a base to load your meshes and associated resources
  105703. */
  105704. rootUrl,
  105705. /**
  105706. * Defines the filename of the scene to load from
  105707. */
  105708. sceneFilename) {
  105709. var _this = _super.call(this, name) || this;
  105710. _this.name = name;
  105711. _this.meshesNames = meshesNames;
  105712. _this.rootUrl = rootUrl;
  105713. _this.sceneFilename = sceneFilename;
  105714. return _this;
  105715. }
  105716. /**
  105717. * Execute the current task
  105718. * @param scene defines the scene where you want your assets to be loaded
  105719. * @param onSuccess is a callback called when the task is successfully executed
  105720. * @param onError is a callback called if an error occurs
  105721. */
  105722. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105723. var _this = this;
  105724. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  105725. _this.loadedMeshes = meshes;
  105726. _this.loadedParticleSystems = particleSystems;
  105727. _this.loadedSkeletons = skeletons;
  105728. onSuccess();
  105729. }, null, function (scene, message, exception) {
  105730. onError(message, exception);
  105731. });
  105732. };
  105733. return MeshAssetTask;
  105734. }(AbstractAssetTask));
  105735. BABYLON.MeshAssetTask = MeshAssetTask;
  105736. /**
  105737. * Define a task used by {BABYLON.AssetsManager} to load text content
  105738. */
  105739. var TextFileAssetTask = /** @class */ (function (_super) {
  105740. __extends(TextFileAssetTask, _super);
  105741. /**
  105742. * Creates a new TextFileAssetTask object
  105743. * @param name defines the name of the task
  105744. * @param url defines the location of the file to load
  105745. */
  105746. function TextFileAssetTask(
  105747. /**
  105748. * Defines the name of the task
  105749. */
  105750. name,
  105751. /**
  105752. * Defines the location of the file to load
  105753. */
  105754. url) {
  105755. var _this = _super.call(this, name) || this;
  105756. _this.name = name;
  105757. _this.url = url;
  105758. return _this;
  105759. }
  105760. /**
  105761. * Execute the current task
  105762. * @param scene defines the scene where you want your assets to be loaded
  105763. * @param onSuccess is a callback called when the task is successfully executed
  105764. * @param onError is a callback called if an error occurs
  105765. */
  105766. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105767. var _this = this;
  105768. scene._loadFile(this.url, function (data) {
  105769. _this.text = data;
  105770. onSuccess();
  105771. }, undefined, false, false, function (request, exception) {
  105772. if (request) {
  105773. onError(request.status + " " + request.statusText, exception);
  105774. }
  105775. });
  105776. };
  105777. return TextFileAssetTask;
  105778. }(AbstractAssetTask));
  105779. BABYLON.TextFileAssetTask = TextFileAssetTask;
  105780. /**
  105781. * Define a task used by {BABYLON.AssetsManager} to load binary data
  105782. */
  105783. var BinaryFileAssetTask = /** @class */ (function (_super) {
  105784. __extends(BinaryFileAssetTask, _super);
  105785. /**
  105786. * Creates a new BinaryFileAssetTask object
  105787. * @param name defines the name of the new task
  105788. * @param url defines the location of the file to load
  105789. */
  105790. function BinaryFileAssetTask(
  105791. /**
  105792. * Defines the name of the task
  105793. */
  105794. name,
  105795. /**
  105796. * Defines the location of the file to load
  105797. */
  105798. url) {
  105799. var _this = _super.call(this, name) || this;
  105800. _this.name = name;
  105801. _this.url = url;
  105802. return _this;
  105803. }
  105804. /**
  105805. * Execute the current task
  105806. * @param scene defines the scene where you want your assets to be loaded
  105807. * @param onSuccess is a callback called when the task is successfully executed
  105808. * @param onError is a callback called if an error occurs
  105809. */
  105810. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105811. var _this = this;
  105812. scene._loadFile(this.url, function (data) {
  105813. _this.data = data;
  105814. onSuccess();
  105815. }, undefined, true, true, function (request, exception) {
  105816. if (request) {
  105817. onError(request.status + " " + request.statusText, exception);
  105818. }
  105819. });
  105820. };
  105821. return BinaryFileAssetTask;
  105822. }(AbstractAssetTask));
  105823. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  105824. /**
  105825. * Define a task used by {BABYLON.AssetsManager} to load images
  105826. */
  105827. var ImageAssetTask = /** @class */ (function (_super) {
  105828. __extends(ImageAssetTask, _super);
  105829. /**
  105830. * Creates a new ImageAssetTask
  105831. * @param name defines the name of the task
  105832. * @param url defines the location of the image to load
  105833. */
  105834. function ImageAssetTask(
  105835. /**
  105836. * Defines the name of the task
  105837. */
  105838. name,
  105839. /**
  105840. * Defines the location of the image to load
  105841. */
  105842. url) {
  105843. var _this = _super.call(this, name) || this;
  105844. _this.name = name;
  105845. _this.url = url;
  105846. return _this;
  105847. }
  105848. /**
  105849. * Execute the current task
  105850. * @param scene defines the scene where you want your assets to be loaded
  105851. * @param onSuccess is a callback called when the task is successfully executed
  105852. * @param onError is a callback called if an error occurs
  105853. */
  105854. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105855. var _this = this;
  105856. var img = new Image();
  105857. BABYLON.Tools.SetCorsBehavior(this.url, img);
  105858. img.onload = function () {
  105859. _this.image = img;
  105860. onSuccess();
  105861. };
  105862. img.onerror = function (err) {
  105863. onError("Error loading image", err);
  105864. };
  105865. img.src = this.url;
  105866. };
  105867. return ImageAssetTask;
  105868. }(AbstractAssetTask));
  105869. BABYLON.ImageAssetTask = ImageAssetTask;
  105870. /**
  105871. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  105872. */
  105873. var TextureAssetTask = /** @class */ (function (_super) {
  105874. __extends(TextureAssetTask, _super);
  105875. /**
  105876. * Creates a new TextureAssetTask object
  105877. * @param name defines the name of the task
  105878. * @param url defines the location of the file to load
  105879. * @param noMipmap defines if mipmap should not be generated (default is false)
  105880. * @param invertY defines if texture must be inverted on Y axis (default is false)
  105881. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  105882. */
  105883. function TextureAssetTask(
  105884. /**
  105885. * Defines the name of the task
  105886. */
  105887. name,
  105888. /**
  105889. * Defines the location of the file to load
  105890. */
  105891. url,
  105892. /**
  105893. * Defines if mipmap should not be generated (default is false)
  105894. */
  105895. noMipmap,
  105896. /**
  105897. * Defines if texture must be inverted on Y axis (default is false)
  105898. */
  105899. invertY,
  105900. /**
  105901. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  105902. */
  105903. samplingMode) {
  105904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  105905. var _this = _super.call(this, name) || this;
  105906. _this.name = name;
  105907. _this.url = url;
  105908. _this.noMipmap = noMipmap;
  105909. _this.invertY = invertY;
  105910. _this.samplingMode = samplingMode;
  105911. return _this;
  105912. }
  105913. /**
  105914. * Execute the current task
  105915. * @param scene defines the scene where you want your assets to be loaded
  105916. * @param onSuccess is a callback called when the task is successfully executed
  105917. * @param onError is a callback called if an error occurs
  105918. */
  105919. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105920. var onload = function () {
  105921. onSuccess();
  105922. };
  105923. var onerror = function (message, exception) {
  105924. onError(message, exception);
  105925. };
  105926. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  105927. };
  105928. return TextureAssetTask;
  105929. }(AbstractAssetTask));
  105930. BABYLON.TextureAssetTask = TextureAssetTask;
  105931. /**
  105932. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  105933. */
  105934. var CubeTextureAssetTask = /** @class */ (function (_super) {
  105935. __extends(CubeTextureAssetTask, _super);
  105936. /**
  105937. * Creates a new CubeTextureAssetTask
  105938. * @param name defines the name of the task
  105939. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  105940. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  105941. * @param noMipmap defines if mipmaps should not be generated (default is false)
  105942. * @param files defines the explicit list of files (undefined by default)
  105943. */
  105944. function CubeTextureAssetTask(
  105945. /**
  105946. * Defines the name of the task
  105947. */
  105948. name,
  105949. /**
  105950. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  105951. */
  105952. url,
  105953. /**
  105954. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  105955. */
  105956. extensions,
  105957. /**
  105958. * Defines if mipmaps should not be generated (default is false)
  105959. */
  105960. noMipmap,
  105961. /**
  105962. * Defines the explicit list of files (undefined by default)
  105963. */
  105964. files) {
  105965. var _this = _super.call(this, name) || this;
  105966. _this.name = name;
  105967. _this.url = url;
  105968. _this.extensions = extensions;
  105969. _this.noMipmap = noMipmap;
  105970. _this.files = files;
  105971. return _this;
  105972. }
  105973. /**
  105974. * Execute the current task
  105975. * @param scene defines the scene where you want your assets to be loaded
  105976. * @param onSuccess is a callback called when the task is successfully executed
  105977. * @param onError is a callback called if an error occurs
  105978. */
  105979. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  105980. var onload = function () {
  105981. onSuccess();
  105982. };
  105983. var onerror = function (message, exception) {
  105984. onError(message, exception);
  105985. };
  105986. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  105987. };
  105988. return CubeTextureAssetTask;
  105989. }(AbstractAssetTask));
  105990. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  105991. /**
  105992. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  105993. */
  105994. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  105995. __extends(HDRCubeTextureAssetTask, _super);
  105996. /**
  105997. * Creates a new HDRCubeTextureAssetTask object
  105998. * @param name defines the name of the task
  105999. * @param url defines the location of the file to load
  106000. * @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.
  106001. * @param noMipmap defines if mipmaps should not be generated (default is false)
  106002. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106003. * @param gammaSpace 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)
  106004. * @param reserved Internal use only
  106005. */
  106006. function HDRCubeTextureAssetTask(
  106007. /**
  106008. * Defines the name of the task
  106009. */
  106010. name,
  106011. /**
  106012. * Defines the location of the file to load
  106013. */
  106014. url,
  106015. /**
  106016. * Defines the desired size (the more it increases the longer the generation will be)
  106017. */
  106018. size,
  106019. /**
  106020. * Defines if mipmaps should not be generated (default is false)
  106021. */
  106022. noMipmap,
  106023. /**
  106024. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  106025. */
  106026. generateHarmonics,
  106027. /**
  106028. * 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)
  106029. */
  106030. gammaSpace,
  106031. /**
  106032. * Internal Use Only
  106033. */
  106034. reserved) {
  106035. if (noMipmap === void 0) { noMipmap = false; }
  106036. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106037. if (gammaSpace === void 0) { gammaSpace = false; }
  106038. if (reserved === void 0) { reserved = false; }
  106039. var _this = _super.call(this, name) || this;
  106040. _this.name = name;
  106041. _this.url = url;
  106042. _this.size = size;
  106043. _this.noMipmap = noMipmap;
  106044. _this.generateHarmonics = generateHarmonics;
  106045. _this.gammaSpace = gammaSpace;
  106046. _this.reserved = reserved;
  106047. return _this;
  106048. }
  106049. /**
  106050. * Execute the current task
  106051. * @param scene defines the scene where you want your assets to be loaded
  106052. * @param onSuccess is a callback called when the task is successfully executed
  106053. * @param onError is a callback called if an error occurs
  106054. */
  106055. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  106056. var onload = function () {
  106057. onSuccess();
  106058. };
  106059. var onerror = function (message, exception) {
  106060. onError(message, exception);
  106061. };
  106062. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  106063. };
  106064. return HDRCubeTextureAssetTask;
  106065. }(AbstractAssetTask));
  106066. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  106067. /**
  106068. * This class can be used to easily import assets into a scene
  106069. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  106070. */
  106071. var AssetsManager = /** @class */ (function () {
  106072. /**
  106073. * Creates a new AssetsManager
  106074. * @param scene defines the scene to work on
  106075. */
  106076. function AssetsManager(scene) {
  106077. this._isLoading = false;
  106078. this._tasks = new Array();
  106079. this._waitingTasksCount = 0;
  106080. this._totalTasksCount = 0;
  106081. /**
  106082. * Observable called when all tasks are processed
  106083. */
  106084. this.onTaskSuccessObservable = new BABYLON.Observable();
  106085. /**
  106086. * Observable called when a task had an error
  106087. */
  106088. this.onTaskErrorObservable = new BABYLON.Observable();
  106089. /**
  106090. * Observable called when a task is successful
  106091. */
  106092. this.onTasksDoneObservable = new BABYLON.Observable();
  106093. /**
  106094. * Observable called when a task is done (whatever the result is)
  106095. */
  106096. this.onProgressObservable = new BABYLON.Observable();
  106097. /**
  106098. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  106099. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  106100. */
  106101. this.useDefaultLoadingScreen = true;
  106102. this._scene = scene;
  106103. }
  106104. /**
  106105. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  106106. * @param taskName defines the name of the new task
  106107. * @param meshesNames defines the name of meshes to load
  106108. * @param rootUrl defines the root url to use to locate files
  106109. * @param sceneFilename defines the filename of the scene file
  106110. * @returns a new {BABYLON.MeshAssetTask} object
  106111. */
  106112. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  106113. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  106114. this._tasks.push(task);
  106115. return task;
  106116. };
  106117. /**
  106118. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  106119. * @param taskName defines the name of the new task
  106120. * @param url defines the url of the file to load
  106121. * @returns a new {BABYLON.TextFileAssetTask} object
  106122. */
  106123. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  106124. var task = new TextFileAssetTask(taskName, url);
  106125. this._tasks.push(task);
  106126. return task;
  106127. };
  106128. /**
  106129. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  106130. * @param taskName defines the name of the new task
  106131. * @param url defines the url of the file to load
  106132. * @returns a new {BABYLON.BinaryFileAssetTask} object
  106133. */
  106134. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  106135. var task = new BinaryFileAssetTask(taskName, url);
  106136. this._tasks.push(task);
  106137. return task;
  106138. };
  106139. /**
  106140. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  106141. * @param taskName defines the name of the new task
  106142. * @param url defines the url of the file to load
  106143. * @returns a new {BABYLON.ImageAssetTask} object
  106144. */
  106145. AssetsManager.prototype.addImageTask = function (taskName, url) {
  106146. var task = new ImageAssetTask(taskName, url);
  106147. this._tasks.push(task);
  106148. return task;
  106149. };
  106150. /**
  106151. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  106152. * @param taskName defines the name of the new task
  106153. * @param url defines the url of the file to load
  106154. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106155. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  106156. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  106157. * @returns a new {BABYLON.TextureAssetTask} object
  106158. */
  106159. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  106160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  106161. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  106162. this._tasks.push(task);
  106163. return task;
  106164. };
  106165. /**
  106166. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  106167. * @param taskName defines the name of the new task
  106168. * @param url defines the url of the file to load
  106169. * @param extensions defines the extension to use to load the cube map (can be null)
  106170. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106171. * @param files defines the list of files to load (can be null)
  106172. * @returns a new {BABYLON.CubeTextureAssetTask} object
  106173. */
  106174. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  106175. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  106176. this._tasks.push(task);
  106177. return task;
  106178. };
  106179. /**
  106180. *
  106181. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  106182. * @param taskName defines the name of the new task
  106183. * @param url defines the url of the file to load
  106184. * @param size defines the size you want for the cubemap (can be null)
  106185. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  106186. * @param generateHarmonics defines if you want to automatically generate (true by default)
  106187. * @param gammaSpace 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)
  106188. * @param reserved Internal use only
  106189. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  106190. */
  106191. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  106192. if (noMipmap === void 0) { noMipmap = false; }
  106193. if (generateHarmonics === void 0) { generateHarmonics = true; }
  106194. if (gammaSpace === void 0) { gammaSpace = false; }
  106195. if (reserved === void 0) { reserved = false; }
  106196. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  106197. this._tasks.push(task);
  106198. return task;
  106199. };
  106200. /**
  106201. * Remove a task from the assets manager.
  106202. * @param task the task to remove
  106203. */
  106204. AssetsManager.prototype.removeTask = function (task) {
  106205. var index = this._tasks.indexOf(task);
  106206. if (index > -1) {
  106207. this._tasks.splice(index, 1);
  106208. }
  106209. };
  106210. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  106211. this._waitingTasksCount--;
  106212. try {
  106213. if (this.onProgress) {
  106214. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  106215. }
  106216. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  106217. }
  106218. catch (e) {
  106219. BABYLON.Tools.Error("Error running progress callbacks.");
  106220. console.log(e);
  106221. }
  106222. if (this._waitingTasksCount === 0) {
  106223. try {
  106224. if (this.onFinish) {
  106225. this.onFinish(this._tasks);
  106226. }
  106227. // Let's remove successfull tasks
  106228. var currentTasks = this._tasks.slice();
  106229. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  106230. var task = currentTasks_1[_i];
  106231. if (task.taskState === AssetTaskState.DONE) {
  106232. var index = this._tasks.indexOf(task);
  106233. if (index > -1) {
  106234. this._tasks.splice(index, 1);
  106235. }
  106236. }
  106237. }
  106238. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106239. }
  106240. catch (e) {
  106241. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  106242. console.log(e);
  106243. }
  106244. this._isLoading = false;
  106245. this._scene.getEngine().hideLoadingUI();
  106246. }
  106247. };
  106248. AssetsManager.prototype._runTask = function (task) {
  106249. var _this = this;
  106250. var done = function () {
  106251. try {
  106252. if (_this.onTaskSuccess) {
  106253. _this.onTaskSuccess(task);
  106254. }
  106255. _this.onTaskSuccessObservable.notifyObservers(task);
  106256. _this._decreaseWaitingTasksCount(task);
  106257. }
  106258. catch (e) {
  106259. error("Error executing task success callbacks", e);
  106260. }
  106261. };
  106262. var error = function (message, exception) {
  106263. task._setErrorObject(message, exception);
  106264. if (_this.onTaskError) {
  106265. _this.onTaskError(task);
  106266. }
  106267. _this.onTaskErrorObservable.notifyObservers(task);
  106268. _this._decreaseWaitingTasksCount(task);
  106269. };
  106270. task.run(this._scene, done, error);
  106271. };
  106272. /**
  106273. * Reset the {BABYLON.AssetsManager} and remove all tasks
  106274. * @return the current instance of the {BABYLON.AssetsManager}
  106275. */
  106276. AssetsManager.prototype.reset = function () {
  106277. this._isLoading = false;
  106278. this._tasks = new Array();
  106279. return this;
  106280. };
  106281. /**
  106282. * Start the loading process
  106283. * @return the current instance of the {BABYLON.AssetsManager}
  106284. */
  106285. AssetsManager.prototype.load = function () {
  106286. if (this._isLoading) {
  106287. return this;
  106288. }
  106289. this._isLoading = true;
  106290. this._waitingTasksCount = this._tasks.length;
  106291. this._totalTasksCount = this._tasks.length;
  106292. if (this._waitingTasksCount === 0) {
  106293. this._isLoading = false;
  106294. if (this.onFinish) {
  106295. this.onFinish(this._tasks);
  106296. }
  106297. this.onTasksDoneObservable.notifyObservers(this._tasks);
  106298. return this;
  106299. }
  106300. if (this.useDefaultLoadingScreen) {
  106301. this._scene.getEngine().displayLoadingUI();
  106302. }
  106303. for (var index = 0; index < this._tasks.length; index++) {
  106304. var task = this._tasks[index];
  106305. if (task.taskState === AssetTaskState.INIT) {
  106306. this._runTask(task);
  106307. }
  106308. }
  106309. return this;
  106310. };
  106311. return AssetsManager;
  106312. }());
  106313. BABYLON.AssetsManager = AssetsManager;
  106314. })(BABYLON || (BABYLON = {}));
  106315. //# sourceMappingURL=babylon.assetsManager.js.map
  106316. var BABYLON;
  106317. (function (BABYLON) {
  106318. var serializedGeometries = [];
  106319. var serializeGeometry = function (geometry, serializationGeometries) {
  106320. if (serializedGeometries[geometry.id]) {
  106321. return;
  106322. }
  106323. if (geometry.doNotSerialize) {
  106324. return;
  106325. }
  106326. if (geometry instanceof BABYLON.BoxGeometry) {
  106327. serializationGeometries.boxes.push(geometry.serialize());
  106328. }
  106329. else if (geometry instanceof BABYLON.SphereGeometry) {
  106330. serializationGeometries.spheres.push(geometry.serialize());
  106331. }
  106332. else if (geometry instanceof BABYLON.CylinderGeometry) {
  106333. serializationGeometries.cylinders.push(geometry.serialize());
  106334. }
  106335. else if (geometry instanceof BABYLON.TorusGeometry) {
  106336. serializationGeometries.toruses.push(geometry.serialize());
  106337. }
  106338. else if (geometry instanceof BABYLON.GroundGeometry) {
  106339. serializationGeometries.grounds.push(geometry.serialize());
  106340. }
  106341. else if (geometry instanceof BABYLON.Plane) {
  106342. serializationGeometries.planes.push(geometry.serialize());
  106343. }
  106344. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  106345. serializationGeometries.torusKnots.push(geometry.serialize());
  106346. }
  106347. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  106348. throw new Error("Unknown primitive type");
  106349. }
  106350. else {
  106351. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  106352. }
  106353. serializedGeometries[geometry.id] = true;
  106354. };
  106355. var serializeMesh = function (mesh, serializationScene) {
  106356. var serializationObject = {};
  106357. // Geometry
  106358. var geometry = mesh._geometry;
  106359. if (geometry) {
  106360. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  106361. // 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
  106362. serializeGeometry(geometry, serializationScene.geometries);
  106363. }
  106364. }
  106365. // Custom
  106366. if (mesh.serialize) {
  106367. mesh.serialize(serializationObject);
  106368. }
  106369. return serializationObject;
  106370. };
  106371. var finalizeSingleMesh = function (mesh, serializationObject) {
  106372. //only works if the mesh is already loaded
  106373. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  106374. //serialize material
  106375. if (mesh.material) {
  106376. if (mesh.material instanceof BABYLON.MultiMaterial) {
  106377. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  106378. serializationObject.materials = serializationObject.materials || [];
  106379. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106380. serializationObject.multiMaterials.push(mesh.material.serialize());
  106381. var _loop_1 = function (submaterial) {
  106382. if (submaterial) {
  106383. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  106384. serializationObject.materials.push(submaterial.serialize());
  106385. }
  106386. }
  106387. };
  106388. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  106389. var submaterial = _a[_i];
  106390. _loop_1(submaterial);
  106391. }
  106392. }
  106393. }
  106394. else {
  106395. serializationObject.materials = serializationObject.materials || [];
  106396. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  106397. serializationObject.materials.push(mesh.material.serialize());
  106398. }
  106399. }
  106400. }
  106401. //serialize geometry
  106402. var geometry = mesh._geometry;
  106403. if (geometry) {
  106404. if (!serializationObject.geometries) {
  106405. serializationObject.geometries = {};
  106406. serializationObject.geometries.boxes = [];
  106407. serializationObject.geometries.spheres = [];
  106408. serializationObject.geometries.cylinders = [];
  106409. serializationObject.geometries.toruses = [];
  106410. serializationObject.geometries.grounds = [];
  106411. serializationObject.geometries.planes = [];
  106412. serializationObject.geometries.torusKnots = [];
  106413. serializationObject.geometries.vertexData = [];
  106414. }
  106415. serializeGeometry(geometry, serializationObject.geometries);
  106416. }
  106417. // Skeletons
  106418. if (mesh.skeleton) {
  106419. serializationObject.skeletons = serializationObject.skeletons || [];
  106420. serializationObject.skeletons.push(mesh.skeleton.serialize());
  106421. }
  106422. //serialize the actual mesh
  106423. serializationObject.meshes = serializationObject.meshes || [];
  106424. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  106425. }
  106426. };
  106427. var SceneSerializer = /** @class */ (function () {
  106428. function SceneSerializer() {
  106429. }
  106430. SceneSerializer.ClearCache = function () {
  106431. serializedGeometries = [];
  106432. };
  106433. SceneSerializer.Serialize = function (scene) {
  106434. var serializationObject = {};
  106435. SceneSerializer.ClearCache();
  106436. // Scene
  106437. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  106438. serializationObject.autoClear = scene.autoClear;
  106439. serializationObject.clearColor = scene.clearColor.asArray();
  106440. serializationObject.ambientColor = scene.ambientColor.asArray();
  106441. serializationObject.gravity = scene.gravity.asArray();
  106442. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  106443. serializationObject.workerCollisions = scene.workerCollisions;
  106444. // Fog
  106445. if (scene.fogMode && scene.fogMode !== 0) {
  106446. serializationObject.fogMode = scene.fogMode;
  106447. serializationObject.fogColor = scene.fogColor.asArray();
  106448. serializationObject.fogStart = scene.fogStart;
  106449. serializationObject.fogEnd = scene.fogEnd;
  106450. serializationObject.fogDensity = scene.fogDensity;
  106451. }
  106452. //Physics
  106453. if (scene.isPhysicsEnabled()) {
  106454. var physicEngine = scene.getPhysicsEngine();
  106455. if (physicEngine) {
  106456. serializationObject.physicsEnabled = true;
  106457. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  106458. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  106459. }
  106460. }
  106461. // Metadata
  106462. if (scene.metadata) {
  106463. serializationObject.metadata = scene.metadata;
  106464. }
  106465. // Morph targets
  106466. serializationObject.morphTargetManagers = [];
  106467. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  106468. var abstractMesh = _a[_i];
  106469. var manager = abstractMesh.morphTargetManager;
  106470. if (manager) {
  106471. serializationObject.morphTargetManagers.push(manager.serialize());
  106472. }
  106473. }
  106474. // Lights
  106475. serializationObject.lights = [];
  106476. var index;
  106477. var light;
  106478. for (index = 0; index < scene.lights.length; index++) {
  106479. light = scene.lights[index];
  106480. if (!light.doNotSerialize) {
  106481. serializationObject.lights.push(light.serialize());
  106482. }
  106483. }
  106484. // Cameras
  106485. serializationObject.cameras = [];
  106486. for (index = 0; index < scene.cameras.length; index++) {
  106487. var camera = scene.cameras[index];
  106488. if (!camera.doNotSerialize) {
  106489. serializationObject.cameras.push(camera.serialize());
  106490. }
  106491. }
  106492. if (scene.activeCamera) {
  106493. serializationObject.activeCameraID = scene.activeCamera.id;
  106494. }
  106495. // Animations
  106496. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  106497. // Materials
  106498. serializationObject.materials = [];
  106499. serializationObject.multiMaterials = [];
  106500. var material;
  106501. for (index = 0; index < scene.materials.length; index++) {
  106502. material = scene.materials[index];
  106503. if (!material.doNotSerialize) {
  106504. serializationObject.materials.push(material.serialize());
  106505. }
  106506. }
  106507. // MultiMaterials
  106508. serializationObject.multiMaterials = [];
  106509. for (index = 0; index < scene.multiMaterials.length; index++) {
  106510. var multiMaterial = scene.multiMaterials[index];
  106511. serializationObject.multiMaterials.push(multiMaterial.serialize());
  106512. }
  106513. // Environment texture
  106514. if (scene.environmentTexture) {
  106515. serializationObject.environmentTexture = scene.environmentTexture.name;
  106516. }
  106517. // Skeletons
  106518. serializationObject.skeletons = [];
  106519. for (index = 0; index < scene.skeletons.length; index++) {
  106520. var skeleton = scene.skeletons[index];
  106521. if (!skeleton.doNotSerialize) {
  106522. serializationObject.skeletons.push(skeleton.serialize());
  106523. }
  106524. }
  106525. // Transform nodes
  106526. serializationObject.transformNodes = [];
  106527. for (index = 0; index < scene.transformNodes.length; index++) {
  106528. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  106529. }
  106530. // Geometries
  106531. serializationObject.geometries = {};
  106532. serializationObject.geometries.boxes = [];
  106533. serializationObject.geometries.spheres = [];
  106534. serializationObject.geometries.cylinders = [];
  106535. serializationObject.geometries.toruses = [];
  106536. serializationObject.geometries.grounds = [];
  106537. serializationObject.geometries.planes = [];
  106538. serializationObject.geometries.torusKnots = [];
  106539. serializationObject.geometries.vertexData = [];
  106540. serializedGeometries = [];
  106541. var geometries = scene.getGeometries();
  106542. for (index = 0; index < geometries.length; index++) {
  106543. var geometry = geometries[index];
  106544. if (geometry.isReady()) {
  106545. serializeGeometry(geometry, serializationObject.geometries);
  106546. }
  106547. }
  106548. // Meshes
  106549. serializationObject.meshes = [];
  106550. for (index = 0; index < scene.meshes.length; index++) {
  106551. var abstractMesh = scene.meshes[index];
  106552. if (abstractMesh instanceof BABYLON.Mesh) {
  106553. var mesh = abstractMesh;
  106554. if (!mesh.doNotSerialize) {
  106555. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  106556. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  106557. }
  106558. }
  106559. }
  106560. }
  106561. // Particles Systems
  106562. serializationObject.particleSystems = [];
  106563. for (index = 0; index < scene.particleSystems.length; index++) {
  106564. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  106565. }
  106566. // Action Manager
  106567. if (scene.actionManager) {
  106568. serializationObject.actions = scene.actionManager.serialize("scene");
  106569. }
  106570. // Components
  106571. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  106572. var component = _c[_b];
  106573. component.serialize(serializationObject);
  106574. }
  106575. return serializationObject;
  106576. };
  106577. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  106578. if (withParents === void 0) { withParents = false; }
  106579. if (withChildren === void 0) { withChildren = false; }
  106580. var serializationObject = {};
  106581. SceneSerializer.ClearCache();
  106582. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  106583. if (withParents || withChildren) {
  106584. //deliberate for loop! not for each, appended should be processed as well.
  106585. for (var i = 0; i < toSerialize.length; ++i) {
  106586. if (withChildren) {
  106587. toSerialize[i].getDescendants().forEach(function (node) {
  106588. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  106589. toSerialize.push(node);
  106590. }
  106591. });
  106592. }
  106593. //make sure the array doesn't contain the object already
  106594. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  106595. toSerialize.push(toSerialize[i].parent);
  106596. }
  106597. }
  106598. }
  106599. toSerialize.forEach(function (mesh) {
  106600. finalizeSingleMesh(mesh, serializationObject);
  106601. });
  106602. return serializationObject;
  106603. };
  106604. return SceneSerializer;
  106605. }());
  106606. BABYLON.SceneSerializer = SceneSerializer;
  106607. })(BABYLON || (BABYLON = {}));
  106608. //# sourceMappingURL=babylon.sceneSerializer.js.map
  106609. var BABYLON;
  106610. (function (BABYLON) {
  106611. /**
  106612. * Class used to generate realtime reflection / refraction cube textures
  106613. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  106614. */
  106615. var ReflectionProbe = /** @class */ (function () {
  106616. /**
  106617. * Creates a new reflection probe
  106618. * @param name defines the name of the probe
  106619. * @param size defines the texture resolution (for each face)
  106620. * @param scene defines the hosting scene
  106621. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  106622. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  106623. */
  106624. function ReflectionProbe(
  106625. /** defines the name of the probe */
  106626. name, size, scene, generateMipMaps, useFloat) {
  106627. if (generateMipMaps === void 0) { generateMipMaps = true; }
  106628. if (useFloat === void 0) { useFloat = false; }
  106629. var _this = this;
  106630. this.name = name;
  106631. this._viewMatrix = BABYLON.Matrix.Identity();
  106632. this._target = BABYLON.Vector3.Zero();
  106633. this._add = BABYLON.Vector3.Zero();
  106634. this._invertYAxis = false;
  106635. /** Gets or sets probe position (center of the cube map) */
  106636. this.position = BABYLON.Vector3.Zero();
  106637. this._scene = scene;
  106638. // Create the scene field if not exist.
  106639. if (!this._scene.reflectionProbes) {
  106640. this._scene.reflectionProbes = new Array();
  106641. }
  106642. this._scene.reflectionProbes.push(this);
  106643. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  106644. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  106645. switch (faceIndex) {
  106646. case 0:
  106647. _this._add.copyFromFloats(1, 0, 0);
  106648. break;
  106649. case 1:
  106650. _this._add.copyFromFloats(-1, 0, 0);
  106651. break;
  106652. case 2:
  106653. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  106654. break;
  106655. case 3:
  106656. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  106657. break;
  106658. case 4:
  106659. _this._add.copyFromFloats(0, 0, 1);
  106660. break;
  106661. case 5:
  106662. _this._add.copyFromFloats(0, 0, -1);
  106663. break;
  106664. }
  106665. if (_this._attachedMesh) {
  106666. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  106667. }
  106668. _this.position.addToRef(_this._add, _this._target);
  106669. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  106670. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  106671. scene._forcedViewPosition = _this.position;
  106672. });
  106673. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  106674. scene._forcedViewPosition = null;
  106675. scene.updateTransformMatrix(true);
  106676. });
  106677. if (scene.activeCamera) {
  106678. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  106679. }
  106680. }
  106681. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  106682. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  106683. get: function () {
  106684. return this._renderTargetTexture.samples;
  106685. },
  106686. set: function (value) {
  106687. this._renderTargetTexture.samples = value;
  106688. },
  106689. enumerable: true,
  106690. configurable: true
  106691. });
  106692. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  106693. /** Gets or sets the refresh rate to use (on every frame by default) */
  106694. get: function () {
  106695. return this._renderTargetTexture.refreshRate;
  106696. },
  106697. set: function (value) {
  106698. this._renderTargetTexture.refreshRate = value;
  106699. },
  106700. enumerable: true,
  106701. configurable: true
  106702. });
  106703. /**
  106704. * Gets the hosting scene
  106705. * @returns a Scene
  106706. */
  106707. ReflectionProbe.prototype.getScene = function () {
  106708. return this._scene;
  106709. };
  106710. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  106711. /** Gets the internal CubeTexture used to render to */
  106712. get: function () {
  106713. return this._renderTargetTexture;
  106714. },
  106715. enumerable: true,
  106716. configurable: true
  106717. });
  106718. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  106719. /** Gets the list of meshes to render */
  106720. get: function () {
  106721. return this._renderTargetTexture.renderList;
  106722. },
  106723. enumerable: true,
  106724. configurable: true
  106725. });
  106726. /**
  106727. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  106728. * @param mesh defines the mesh to attach to
  106729. */
  106730. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  106731. this._attachedMesh = mesh;
  106732. };
  106733. /**
  106734. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  106735. * @param renderingGroupId The rendering group id corresponding to its index
  106736. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  106737. */
  106738. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  106739. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  106740. };
  106741. /**
  106742. * Clean all associated resources
  106743. */
  106744. ReflectionProbe.prototype.dispose = function () {
  106745. var index = this._scene.reflectionProbes.indexOf(this);
  106746. if (index !== -1) {
  106747. // Remove from the scene if found
  106748. this._scene.reflectionProbes.splice(index, 1);
  106749. }
  106750. if (this._renderTargetTexture) {
  106751. this._renderTargetTexture.dispose();
  106752. this._renderTargetTexture = null;
  106753. }
  106754. };
  106755. return ReflectionProbe;
  106756. }());
  106757. BABYLON.ReflectionProbe = ReflectionProbe;
  106758. })(BABYLON || (BABYLON = {}));
  106759. //# sourceMappingURL=babylon.reflectionProbe.js.map
  106760. var BABYLON;
  106761. (function (BABYLON) {
  106762. /**
  106763. * Defines the layer scene component responsible to manage any layers
  106764. * in a given scene.
  106765. */
  106766. var LayerSceneComponent = /** @class */ (function () {
  106767. /**
  106768. * Creates a new instance of the component for the given scene
  106769. * @param scene Defines the scene to register the component in
  106770. */
  106771. function LayerSceneComponent(scene) {
  106772. /**
  106773. * The component name helpfull to identify the component in the list of scene components.
  106774. */
  106775. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  106776. this.scene = scene;
  106777. this._engine = scene.getEngine();
  106778. scene.layers = new Array();
  106779. }
  106780. /**
  106781. * Registers the component in a given scene
  106782. */
  106783. LayerSceneComponent.prototype.register = function () {
  106784. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  106785. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  106786. };
  106787. /**
  106788. * Rebuilds the elements related to this component in case of
  106789. * context lost for instance.
  106790. */
  106791. LayerSceneComponent.prototype.rebuild = function () {
  106792. var layers = this.scene.layers;
  106793. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  106794. var layer = layers_1[_i];
  106795. layer._rebuild();
  106796. }
  106797. };
  106798. /**
  106799. * Disposes the component and the associated ressources.
  106800. */
  106801. LayerSceneComponent.prototype.dispose = function () {
  106802. var layers = this.scene.layers;
  106803. while (layers.length) {
  106804. layers[0].dispose();
  106805. }
  106806. };
  106807. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  106808. var layers = this.scene.layers;
  106809. if (layers.length) {
  106810. this._engine.setDepthBuffer(false);
  106811. var cameraLayerMask = camera.layerMask;
  106812. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  106813. var layer = layers_2[_i];
  106814. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  106815. layer.render();
  106816. }
  106817. }
  106818. this._engine.setDepthBuffer(true);
  106819. }
  106820. };
  106821. LayerSceneComponent.prototype._drawBackground = function (camera) {
  106822. this._draw(camera, true);
  106823. };
  106824. LayerSceneComponent.prototype._drawForeground = function (camera) {
  106825. this._draw(camera, false);
  106826. };
  106827. return LayerSceneComponent;
  106828. }());
  106829. BABYLON.LayerSceneComponent = LayerSceneComponent;
  106830. })(BABYLON || (BABYLON = {}));
  106831. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  106832. var BABYLON;
  106833. (function (BABYLON) {
  106834. var Layer = /** @class */ (function () {
  106835. function Layer(name, imgUrl, scene, isBackground, color) {
  106836. this.name = name;
  106837. this.scale = new BABYLON.Vector2(1, 1);
  106838. this.offset = new BABYLON.Vector2(0, 0);
  106839. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  106840. this.layerMask = 0x0FFFFFFF;
  106841. this._vertexBuffers = {};
  106842. // Events
  106843. /**
  106844. * An event triggered when the layer is disposed.
  106845. */
  106846. this.onDisposeObservable = new BABYLON.Observable();
  106847. /**
  106848. * An event triggered before rendering the scene
  106849. */
  106850. this.onBeforeRenderObservable = new BABYLON.Observable();
  106851. /**
  106852. * An event triggered after rendering the scene
  106853. */
  106854. this.onAfterRenderObservable = new BABYLON.Observable();
  106855. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  106856. this.isBackground = isBackground === undefined ? true : isBackground;
  106857. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  106858. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  106859. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  106860. if (!layerComponent) {
  106861. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  106862. this._scene._addComponent(layerComponent);
  106863. }
  106864. this._scene.layers.push(this);
  106865. var engine = this._scene.getEngine();
  106866. // VBO
  106867. var vertices = [];
  106868. vertices.push(1, 1);
  106869. vertices.push(-1, 1);
  106870. vertices.push(-1, -1);
  106871. vertices.push(1, -1);
  106872. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  106873. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  106874. this._createIndexBuffer();
  106875. // Effects
  106876. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  106877. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  106878. }
  106879. Object.defineProperty(Layer.prototype, "onDispose", {
  106880. set: function (callback) {
  106881. if (this._onDisposeObserver) {
  106882. this.onDisposeObservable.remove(this._onDisposeObserver);
  106883. }
  106884. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106885. },
  106886. enumerable: true,
  106887. configurable: true
  106888. });
  106889. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  106890. set: function (callback) {
  106891. if (this._onBeforeRenderObserver) {
  106892. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  106893. }
  106894. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  106895. },
  106896. enumerable: true,
  106897. configurable: true
  106898. });
  106899. Object.defineProperty(Layer.prototype, "onAfterRender", {
  106900. set: function (callback) {
  106901. if (this._onAfterRenderObserver) {
  106902. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  106903. }
  106904. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  106905. },
  106906. enumerable: true,
  106907. configurable: true
  106908. });
  106909. Layer.prototype._createIndexBuffer = function () {
  106910. var engine = this._scene.getEngine();
  106911. // Indices
  106912. var indices = [];
  106913. indices.push(0);
  106914. indices.push(1);
  106915. indices.push(2);
  106916. indices.push(0);
  106917. indices.push(2);
  106918. indices.push(3);
  106919. this._indexBuffer = engine.createIndexBuffer(indices);
  106920. };
  106921. /** @hidden */
  106922. Layer.prototype._rebuild = function () {
  106923. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106924. if (vb) {
  106925. vb._rebuild();
  106926. }
  106927. this._createIndexBuffer();
  106928. };
  106929. Layer.prototype.render = function () {
  106930. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  106931. // Check
  106932. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  106933. return;
  106934. var engine = this._scene.getEngine();
  106935. this.onBeforeRenderObservable.notifyObservers(this);
  106936. // Render
  106937. engine.enableEffect(currentEffect);
  106938. engine.setState(false);
  106939. // Texture
  106940. currentEffect.setTexture("textureSampler", this.texture);
  106941. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  106942. // Color
  106943. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  106944. // Scale / offset
  106945. currentEffect.setVector2("offset", this.offset);
  106946. currentEffect.setVector2("scale", this.scale);
  106947. // VBOs
  106948. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  106949. // Draw order
  106950. if (!this.alphaTest) {
  106951. engine.setAlphaMode(this.alphaBlendingMode);
  106952. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106953. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  106954. }
  106955. else {
  106956. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  106957. }
  106958. this.onAfterRenderObservable.notifyObservers(this);
  106959. };
  106960. Layer.prototype.dispose = function () {
  106961. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  106962. if (vertexBuffer) {
  106963. vertexBuffer.dispose();
  106964. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  106965. }
  106966. if (this._indexBuffer) {
  106967. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  106968. this._indexBuffer = null;
  106969. }
  106970. if (this.texture) {
  106971. this.texture.dispose();
  106972. this.texture = null;
  106973. }
  106974. // Remove from scene
  106975. var index = this._scene.layers.indexOf(this);
  106976. this._scene.layers.splice(index, 1);
  106977. // Callback
  106978. this.onDisposeObservable.notifyObservers(this);
  106979. this.onDisposeObservable.clear();
  106980. this.onAfterRenderObservable.clear();
  106981. this.onBeforeRenderObservable.clear();
  106982. };
  106983. return Layer;
  106984. }());
  106985. BABYLON.Layer = Layer;
  106986. })(BABYLON || (BABYLON = {}));
  106987. //# sourceMappingURL=babylon.layer.js.map
  106988. var BABYLON;
  106989. (function (BABYLON) {
  106990. var TextureTools = /** @class */ (function () {
  106991. function TextureTools() {
  106992. }
  106993. /**
  106994. * Uses the GPU to create a copy texture rescaled at a given size
  106995. * @param texture Texture to copy from
  106996. * @param width Desired width
  106997. * @param height Desired height
  106998. * @return Generated texture
  106999. */
  107000. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  107001. if (useBilinearMode === void 0) { useBilinearMode = true; }
  107002. var scene = texture.getScene();
  107003. var engine = scene.getEngine();
  107004. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  107005. rtt.wrapU = texture.wrapU;
  107006. rtt.wrapV = texture.wrapV;
  107007. rtt.uOffset = texture.uOffset;
  107008. rtt.vOffset = texture.vOffset;
  107009. rtt.uScale = texture.uScale;
  107010. rtt.vScale = texture.vScale;
  107011. rtt.uAng = texture.uAng;
  107012. rtt.vAng = texture.vAng;
  107013. rtt.wAng = texture.wAng;
  107014. rtt.coordinatesIndex = texture.coordinatesIndex;
  107015. rtt.level = texture.level;
  107016. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  107017. rtt._texture.isReady = false;
  107018. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107019. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107020. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  107021. passPostProcess.getEffect().executeWhenCompiled(function () {
  107022. passPostProcess.onApply = function (effect) {
  107023. effect.setTexture("textureSampler", texture);
  107024. };
  107025. var internalTexture = rtt.getInternalTexture();
  107026. if (internalTexture) {
  107027. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  107028. engine.unBindFramebuffer(internalTexture);
  107029. rtt.disposeFramebufferObjects();
  107030. passPostProcess.dispose();
  107031. internalTexture.isReady = true;
  107032. }
  107033. });
  107034. return rtt;
  107035. };
  107036. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  107037. if (!scene._environmentBRDFTexture) {
  107038. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  107039. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107040. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  107041. scene._environmentBRDFTexture = texture;
  107042. }
  107043. return scene._environmentBRDFTexture;
  107044. };
  107045. 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=";
  107046. return TextureTools;
  107047. }());
  107048. BABYLON.TextureTools = TextureTools;
  107049. })(BABYLON || (BABYLON = {}));
  107050. //# sourceMappingURL=babylon.textureTools.js.map
  107051. var BABYLON;
  107052. (function (BABYLON) {
  107053. /**
  107054. * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
  107055. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  107056. */
  107057. var FramingBehavior = /** @class */ (function () {
  107058. function FramingBehavior() {
  107059. this._mode = FramingBehavior.FitFrustumSidesMode;
  107060. this._radiusScale = 1.0;
  107061. this._positionScale = 0.5;
  107062. this._defaultElevation = 0.3;
  107063. this._elevationReturnTime = 1500;
  107064. this._elevationReturnWaitTime = 1000;
  107065. this._zoomStopsAnimation = false;
  107066. this._framingTime = 1500;
  107067. this._isPointerDown = false;
  107068. this._lastInteractionTime = -Infinity;
  107069. // Framing control
  107070. this._animatables = new Array();
  107071. this._betaIsAnimating = false;
  107072. }
  107073. Object.defineProperty(FramingBehavior.prototype, "name", {
  107074. /**
  107075. * Gets the name of the behavior.
  107076. */
  107077. get: function () {
  107078. return "Framing";
  107079. },
  107080. enumerable: true,
  107081. configurable: true
  107082. });
  107083. Object.defineProperty(FramingBehavior.prototype, "mode", {
  107084. /**
  107085. * Gets current mode used by the behavior.
  107086. */
  107087. get: function () {
  107088. return this._mode;
  107089. },
  107090. /**
  107091. * Sets the current mode used by the behavior
  107092. */
  107093. set: function (mode) {
  107094. this._mode = mode;
  107095. },
  107096. enumerable: true,
  107097. configurable: true
  107098. });
  107099. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  107100. /**
  107101. * Gets the scale applied to the radius
  107102. */
  107103. get: function () {
  107104. return this._radiusScale;
  107105. },
  107106. /**
  107107. * Sets the scale applied to the radius (1 by default)
  107108. */
  107109. set: function (radius) {
  107110. this._radiusScale = radius;
  107111. },
  107112. enumerable: true,
  107113. configurable: true
  107114. });
  107115. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  107116. /**
  107117. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107118. */
  107119. get: function () {
  107120. return this._positionScale;
  107121. },
  107122. /**
  107123. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  107124. */
  107125. set: function (scale) {
  107126. this._positionScale = scale;
  107127. },
  107128. enumerable: true,
  107129. configurable: true
  107130. });
  107131. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  107132. /**
  107133. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107134. * behaviour is triggered, in radians.
  107135. */
  107136. get: function () {
  107137. return this._defaultElevation;
  107138. },
  107139. /**
  107140. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  107141. * behaviour is triggered, in radians.
  107142. */
  107143. set: function (elevation) {
  107144. this._defaultElevation = elevation;
  107145. },
  107146. enumerable: true,
  107147. configurable: true
  107148. });
  107149. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  107150. /**
  107151. * Gets the time (in milliseconds) taken to return to the default beta position.
  107152. * Negative value indicates camera should not return to default.
  107153. */
  107154. get: function () {
  107155. return this._elevationReturnTime;
  107156. },
  107157. /**
  107158. * Sets the time (in milliseconds) taken to return to the default beta position.
  107159. * Negative value indicates camera should not return to default.
  107160. */
  107161. set: function (speed) {
  107162. this._elevationReturnTime = speed;
  107163. },
  107164. enumerable: true,
  107165. configurable: true
  107166. });
  107167. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  107168. /**
  107169. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107170. */
  107171. get: function () {
  107172. return this._elevationReturnWaitTime;
  107173. },
  107174. /**
  107175. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  107176. */
  107177. set: function (time) {
  107178. this._elevationReturnWaitTime = time;
  107179. },
  107180. enumerable: true,
  107181. configurable: true
  107182. });
  107183. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  107184. /**
  107185. * Gets the flag that indicates if user zooming should stop animation.
  107186. */
  107187. get: function () {
  107188. return this._zoomStopsAnimation;
  107189. },
  107190. /**
  107191. * Sets the flag that indicates if user zooming should stop animation.
  107192. */
  107193. set: function (flag) {
  107194. this._zoomStopsAnimation = flag;
  107195. },
  107196. enumerable: true,
  107197. configurable: true
  107198. });
  107199. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  107200. /**
  107201. * Gets the transition time when framing the mesh, in milliseconds
  107202. */
  107203. get: function () {
  107204. return this._framingTime;
  107205. },
  107206. /**
  107207. * Sets the transition time when framing the mesh, in milliseconds
  107208. */
  107209. set: function (time) {
  107210. this._framingTime = time;
  107211. },
  107212. enumerable: true,
  107213. configurable: true
  107214. });
  107215. /**
  107216. * Initializes the behavior.
  107217. */
  107218. FramingBehavior.prototype.init = function () {
  107219. // Do notihng
  107220. };
  107221. /**
  107222. * Attaches the behavior to its arc rotate camera.
  107223. * @param camera Defines the camera to attach the behavior to
  107224. */
  107225. FramingBehavior.prototype.attach = function (camera) {
  107226. var _this = this;
  107227. this._attachedCamera = camera;
  107228. var scene = this._attachedCamera.getScene();
  107229. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  107230. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  107231. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  107232. _this._isPointerDown = true;
  107233. return;
  107234. }
  107235. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  107236. _this._isPointerDown = false;
  107237. }
  107238. });
  107239. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  107240. if (mesh) {
  107241. _this.zoomOnMesh(mesh);
  107242. }
  107243. });
  107244. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107245. // Stop the animation if there is user interaction and the animation should stop for this interaction
  107246. _this._applyUserInteraction();
  107247. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  107248. // back to the default position after a given timeout
  107249. _this._maintainCameraAboveGround();
  107250. });
  107251. };
  107252. /**
  107253. * Detaches the behavior from its current arc rotate camera.
  107254. */
  107255. FramingBehavior.prototype.detach = function () {
  107256. if (!this._attachedCamera) {
  107257. return;
  107258. }
  107259. var scene = this._attachedCamera.getScene();
  107260. if (this._onPrePointerObservableObserver) {
  107261. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  107262. }
  107263. if (this._onAfterCheckInputsObserver) {
  107264. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107265. }
  107266. if (this._onMeshTargetChangedObserver) {
  107267. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107268. }
  107269. this._attachedCamera = null;
  107270. };
  107271. /**
  107272. * Targets the given mesh and updates zoom level accordingly.
  107273. * @param mesh The mesh to target.
  107274. * @param radius Optional. If a cached radius position already exists, overrides default.
  107275. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107276. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107277. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107278. */
  107279. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107280. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107281. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107282. mesh.computeWorldMatrix(true);
  107283. var boundingBox = mesh.getBoundingInfo().boundingBox;
  107284. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  107285. };
  107286. /**
  107287. * Targets the given mesh with its children and updates zoom level accordingly.
  107288. * @param mesh The mesh to target.
  107289. * @param radius Optional. If a cached radius position already exists, overrides default.
  107290. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107291. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107292. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107293. */
  107294. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  107295. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107296. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107297. mesh.computeWorldMatrix(true);
  107298. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  107299. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  107300. };
  107301. /**
  107302. * Targets the given meshes with their children and updates zoom level accordingly.
  107303. * @param meshes The mesh to target.
  107304. * @param radius Optional. If a cached radius position already exists, overrides default.
  107305. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107306. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107307. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107308. */
  107309. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  107310. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107311. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107312. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  107313. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  107314. for (var i = 0; i < meshes.length; i++) {
  107315. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  107316. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  107317. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  107318. }
  107319. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  107320. };
  107321. /**
  107322. * Targets the given mesh and updates zoom level accordingly.
  107323. * @param mesh The mesh to target.
  107324. * @param radius Optional. If a cached radius position already exists, overrides default.
  107325. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  107326. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  107327. * @param onAnimationEnd Callback triggered at the end of the framing animation
  107328. */
  107329. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  107330. var _this = this;
  107331. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  107332. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  107333. var zoomTarget;
  107334. if (!this._attachedCamera) {
  107335. return;
  107336. }
  107337. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  107338. var bottom = minimumWorld.y;
  107339. var top = maximumWorld.y;
  107340. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  107341. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  107342. if (focusOnOriginXZ) {
  107343. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  107344. }
  107345. else {
  107346. var centerWorld = minimumWorld.add(radiusWorld);
  107347. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  107348. }
  107349. if (!this._vectorTransition) {
  107350. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  107351. }
  107352. this._betaIsAnimating = true;
  107353. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  107354. if (animatable) {
  107355. this._animatables.push(animatable);
  107356. }
  107357. // sets the radius and lower radius bounds
  107358. // Small delta ensures camera is not always at lower zoom limit.
  107359. var radius = 0;
  107360. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  107361. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107362. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  107363. radius = position;
  107364. }
  107365. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107366. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  107367. if (this._attachedCamera.lowerRadiusLimit === null) {
  107368. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  107369. }
  107370. }
  107371. // Set sensibilities
  107372. var extend = maximumWorld.subtract(minimumWorld).length();
  107373. this._attachedCamera.panningSensibility = 5000 / extend;
  107374. this._attachedCamera.wheelPrecision = 100 / radius;
  107375. // transition to new radius
  107376. if (!this._radiusTransition) {
  107377. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107378. }
  107379. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  107380. _this.stopAllAnimations();
  107381. if (onAnimationEnd) {
  107382. onAnimationEnd();
  107383. }
  107384. if (_this._attachedCamera) {
  107385. _this._attachedCamera.storeState();
  107386. }
  107387. });
  107388. if (animatable) {
  107389. this._animatables.push(animatable);
  107390. }
  107391. };
  107392. /**
  107393. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  107394. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  107395. * frustum width.
  107396. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  107397. * to fully enclose the mesh in the viewing frustum.
  107398. */
  107399. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  107400. var size = maximumWorld.subtract(minimumWorld);
  107401. var boxVectorGlobalDiagonal = size.length();
  107402. var frustumSlope = this._getFrustumSlope();
  107403. // Formula for setting distance
  107404. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  107405. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  107406. // Horizon distance
  107407. var radius = radiusWithoutFraming * this._radiusScale;
  107408. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  107409. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  107410. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  107411. var camera = this._attachedCamera;
  107412. if (!camera) {
  107413. return 0;
  107414. }
  107415. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  107416. // Don't exceed the requested limit
  107417. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  107418. }
  107419. // Don't exceed the upper radius limit
  107420. if (camera.upperRadiusLimit) {
  107421. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  107422. }
  107423. return distance;
  107424. };
  107425. /**
  107426. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  107427. * is automatically returned to its default position (expected to be above ground plane).
  107428. */
  107429. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  107430. var _this = this;
  107431. if (this._elevationReturnTime < 0) {
  107432. return;
  107433. }
  107434. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  107435. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  107436. var limitBeta = Math.PI * 0.5;
  107437. // Bring the camera back up if below the ground plane
  107438. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  107439. this._betaIsAnimating = true;
  107440. //Transition to new position
  107441. this.stopAllAnimations();
  107442. if (!this._betaTransition) {
  107443. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  107444. }
  107445. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  107446. _this._clearAnimationLocks();
  107447. _this.stopAllAnimations();
  107448. });
  107449. if (animatabe) {
  107450. this._animatables.push(animatabe);
  107451. }
  107452. }
  107453. };
  107454. /**
  107455. * Returns the frustum slope based on the canvas ratio and camera FOV
  107456. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  107457. */
  107458. FramingBehavior.prototype._getFrustumSlope = function () {
  107459. // Calculate the viewport ratio
  107460. // Aspect Ratio is Height/Width.
  107461. var camera = this._attachedCamera;
  107462. if (!camera) {
  107463. return BABYLON.Vector2.Zero();
  107464. }
  107465. var engine = camera.getScene().getEngine();
  107466. var aspectRatio = engine.getAspectRatio(camera);
  107467. // Camera FOV is the vertical field of view (top-bottom) in radians.
  107468. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  107469. var frustumSlopeY = Math.tan(camera.fov / 2);
  107470. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  107471. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  107472. // along the forward vector.
  107473. var frustumSlopeX = frustumSlopeY * aspectRatio;
  107474. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  107475. };
  107476. /**
  107477. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  107478. */
  107479. FramingBehavior.prototype._clearAnimationLocks = function () {
  107480. this._betaIsAnimating = false;
  107481. };
  107482. /**
  107483. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  107484. */
  107485. FramingBehavior.prototype._applyUserInteraction = function () {
  107486. if (this.isUserIsMoving) {
  107487. this._lastInteractionTime = BABYLON.Tools.Now;
  107488. this.stopAllAnimations();
  107489. this._clearAnimationLocks();
  107490. }
  107491. };
  107492. /**
  107493. * Stops and removes all animations that have been applied to the camera
  107494. */
  107495. FramingBehavior.prototype.stopAllAnimations = function () {
  107496. if (this._attachedCamera) {
  107497. this._attachedCamera.animations = [];
  107498. }
  107499. while (this._animatables.length) {
  107500. if (this._animatables[0]) {
  107501. this._animatables[0].onAnimationEnd = null;
  107502. this._animatables[0].stop();
  107503. }
  107504. this._animatables.shift();
  107505. }
  107506. };
  107507. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  107508. /**
  107509. * Gets a value indicating if the user is moving the camera
  107510. */
  107511. get: function () {
  107512. if (!this._attachedCamera) {
  107513. return false;
  107514. }
  107515. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  107516. this._attachedCamera.inertialBetaOffset !== 0 ||
  107517. this._attachedCamera.inertialRadiusOffset !== 0 ||
  107518. this._attachedCamera.inertialPanningX !== 0 ||
  107519. this._attachedCamera.inertialPanningY !== 0 ||
  107520. this._isPointerDown;
  107521. },
  107522. enumerable: true,
  107523. configurable: true
  107524. });
  107525. /**
  107526. * The easing function used by animations
  107527. */
  107528. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  107529. /**
  107530. * The easing mode used by animations
  107531. */
  107532. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  107533. // Statics
  107534. /**
  107535. * The camera can move all the way towards the mesh.
  107536. */
  107537. FramingBehavior.IgnoreBoundsSizeMode = 0;
  107538. /**
  107539. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  107540. */
  107541. FramingBehavior.FitFrustumSidesMode = 1;
  107542. return FramingBehavior;
  107543. }());
  107544. BABYLON.FramingBehavior = FramingBehavior;
  107545. })(BABYLON || (BABYLON = {}));
  107546. //# sourceMappingURL=babylon.framingBehavior.js.map
  107547. var BABYLON;
  107548. (function (BABYLON) {
  107549. /**
  107550. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  107551. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  107552. */
  107553. var BouncingBehavior = /** @class */ (function () {
  107554. function BouncingBehavior() {
  107555. /**
  107556. * The duration of the animation, in milliseconds
  107557. */
  107558. this.transitionDuration = 450;
  107559. /**
  107560. * Length of the distance animated by the transition when lower radius is reached
  107561. */
  107562. this.lowerRadiusTransitionRange = 2;
  107563. /**
  107564. * Length of the distance animated by the transition when upper radius is reached
  107565. */
  107566. this.upperRadiusTransitionRange = -2;
  107567. this._autoTransitionRange = false;
  107568. // Animations
  107569. this._radiusIsAnimating = false;
  107570. this._radiusBounceTransition = null;
  107571. this._animatables = new Array();
  107572. }
  107573. Object.defineProperty(BouncingBehavior.prototype, "name", {
  107574. /**
  107575. * Gets the name of the behavior.
  107576. */
  107577. get: function () {
  107578. return "Bouncing";
  107579. },
  107580. enumerable: true,
  107581. configurable: true
  107582. });
  107583. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  107584. /**
  107585. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  107586. */
  107587. get: function () {
  107588. return this._autoTransitionRange;
  107589. },
  107590. /**
  107591. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  107592. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  107593. */
  107594. set: function (value) {
  107595. var _this = this;
  107596. if (this._autoTransitionRange === value) {
  107597. return;
  107598. }
  107599. this._autoTransitionRange = value;
  107600. var camera = this._attachedCamera;
  107601. if (!camera) {
  107602. return;
  107603. }
  107604. if (value) {
  107605. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  107606. if (!mesh) {
  107607. return;
  107608. }
  107609. mesh.computeWorldMatrix(true);
  107610. var diagonal = mesh.getBoundingInfo().diagonalLength;
  107611. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  107612. _this.upperRadiusTransitionRange = diagonal * 0.05;
  107613. });
  107614. }
  107615. else if (this._onMeshTargetChangedObserver) {
  107616. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107617. }
  107618. },
  107619. enumerable: true,
  107620. configurable: true
  107621. });
  107622. /**
  107623. * Initializes the behavior.
  107624. */
  107625. BouncingBehavior.prototype.init = function () {
  107626. // Do notihng
  107627. };
  107628. /**
  107629. * Attaches the behavior to its arc rotate camera.
  107630. * @param camera Defines the camera to attach the behavior to
  107631. */
  107632. BouncingBehavior.prototype.attach = function (camera) {
  107633. var _this = this;
  107634. this._attachedCamera = camera;
  107635. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107636. if (!_this._attachedCamera) {
  107637. return;
  107638. }
  107639. // Add the bounce animation to the lower radius limit
  107640. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  107641. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  107642. }
  107643. // Add the bounce animation to the upper radius limit
  107644. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  107645. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  107646. }
  107647. });
  107648. };
  107649. /**
  107650. * Detaches the behavior from its current arc rotate camera.
  107651. */
  107652. BouncingBehavior.prototype.detach = function () {
  107653. if (!this._attachedCamera) {
  107654. return;
  107655. }
  107656. if (this._onAfterCheckInputsObserver) {
  107657. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107658. }
  107659. if (this._onMeshTargetChangedObserver) {
  107660. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  107661. }
  107662. this._attachedCamera = null;
  107663. };
  107664. /**
  107665. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  107666. * @param radiusLimit The limit to check against.
  107667. * @return Bool to indicate if at limit.
  107668. */
  107669. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  107670. if (!this._attachedCamera) {
  107671. return false;
  107672. }
  107673. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  107674. return true;
  107675. }
  107676. return false;
  107677. };
  107678. /**
  107679. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  107680. * @param radiusDelta The delta by which to animate to. Can be negative.
  107681. */
  107682. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  107683. var _this = this;
  107684. if (!this._attachedCamera) {
  107685. return;
  107686. }
  107687. if (!this._radiusBounceTransition) {
  107688. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  107689. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  107690. }
  107691. // Prevent zoom until bounce has completed
  107692. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  107693. this._attachedCamera.wheelPrecision = Infinity;
  107694. this._attachedCamera.inertialRadiusOffset = 0;
  107695. // Animate to the radius limit
  107696. this.stopAllAnimations();
  107697. this._radiusIsAnimating = true;
  107698. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  107699. if (animatable) {
  107700. this._animatables.push(animatable);
  107701. }
  107702. };
  107703. /**
  107704. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  107705. */
  107706. BouncingBehavior.prototype._clearAnimationLocks = function () {
  107707. this._radiusIsAnimating = false;
  107708. if (this._attachedCamera) {
  107709. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  107710. }
  107711. };
  107712. /**
  107713. * Stops and removes all animations that have been applied to the camera
  107714. */
  107715. BouncingBehavior.prototype.stopAllAnimations = function () {
  107716. if (this._attachedCamera) {
  107717. this._attachedCamera.animations = [];
  107718. }
  107719. while (this._animatables.length) {
  107720. this._animatables[0].onAnimationEnd = null;
  107721. this._animatables[0].stop();
  107722. this._animatables.shift();
  107723. }
  107724. };
  107725. /**
  107726. * The easing function used by animations
  107727. */
  107728. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  107729. /**
  107730. * The easing mode used by animations
  107731. */
  107732. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  107733. return BouncingBehavior;
  107734. }());
  107735. BABYLON.BouncingBehavior = BouncingBehavior;
  107736. })(BABYLON || (BABYLON = {}));
  107737. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  107738. var BABYLON;
  107739. (function (BABYLON) {
  107740. /**
  107741. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  107742. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  107743. */
  107744. var AutoRotationBehavior = /** @class */ (function () {
  107745. function AutoRotationBehavior() {
  107746. this._zoomStopsAnimation = false;
  107747. this._idleRotationSpeed = 0.05;
  107748. this._idleRotationWaitTime = 2000;
  107749. this._idleRotationSpinupTime = 2000;
  107750. this._isPointerDown = false;
  107751. this._lastFrameTime = null;
  107752. this._lastInteractionTime = -Infinity;
  107753. this._cameraRotationSpeed = 0;
  107754. this._lastFrameRadius = 0;
  107755. }
  107756. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  107757. /**
  107758. * Gets the name of the behavior.
  107759. */
  107760. get: function () {
  107761. return "AutoRotation";
  107762. },
  107763. enumerable: true,
  107764. configurable: true
  107765. });
  107766. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  107767. /**
  107768. * Gets the flag that indicates if user zooming should stop animation.
  107769. */
  107770. get: function () {
  107771. return this._zoomStopsAnimation;
  107772. },
  107773. /**
  107774. * Sets the flag that indicates if user zooming should stop animation.
  107775. */
  107776. set: function (flag) {
  107777. this._zoomStopsAnimation = flag;
  107778. },
  107779. enumerable: true,
  107780. configurable: true
  107781. });
  107782. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  107783. /**
  107784. * Gets the default speed at which the camera rotates around the model.
  107785. */
  107786. get: function () {
  107787. return this._idleRotationSpeed;
  107788. },
  107789. /**
  107790. * Sets the default speed at which the camera rotates around the model.
  107791. */
  107792. set: function (speed) {
  107793. this._idleRotationSpeed = speed;
  107794. },
  107795. enumerable: true,
  107796. configurable: true
  107797. });
  107798. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  107799. /**
  107800. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  107801. */
  107802. get: function () {
  107803. return this._idleRotationWaitTime;
  107804. },
  107805. /**
  107806. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  107807. */
  107808. set: function (time) {
  107809. this._idleRotationWaitTime = time;
  107810. },
  107811. enumerable: true,
  107812. configurable: true
  107813. });
  107814. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  107815. /**
  107816. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  107817. */
  107818. get: function () {
  107819. return this._idleRotationSpinupTime;
  107820. },
  107821. /**
  107822. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  107823. */
  107824. set: function (time) {
  107825. this._idleRotationSpinupTime = time;
  107826. },
  107827. enumerable: true,
  107828. configurable: true
  107829. });
  107830. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  107831. /**
  107832. * Gets a value indicating if the camera is currently rotating because of this behavior
  107833. */
  107834. get: function () {
  107835. return Math.abs(this._cameraRotationSpeed) > 0;
  107836. },
  107837. enumerable: true,
  107838. configurable: true
  107839. });
  107840. /**
  107841. * Initializes the behavior.
  107842. */
  107843. AutoRotationBehavior.prototype.init = function () {
  107844. // Do notihng
  107845. };
  107846. /**
  107847. * Attaches the behavior to its arc rotate camera.
  107848. * @param camera Defines the camera to attach the behavior to
  107849. */
  107850. AutoRotationBehavior.prototype.attach = function (camera) {
  107851. var _this = this;
  107852. this._attachedCamera = camera;
  107853. var scene = this._attachedCamera.getScene();
  107854. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  107855. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  107856. _this._isPointerDown = true;
  107857. return;
  107858. }
  107859. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  107860. _this._isPointerDown = false;
  107861. }
  107862. });
  107863. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  107864. var now = BABYLON.Tools.Now;
  107865. var dt = 0;
  107866. if (_this._lastFrameTime != null) {
  107867. dt = now - _this._lastFrameTime;
  107868. }
  107869. _this._lastFrameTime = now;
  107870. // Stop the animation if there is user interaction and the animation should stop for this interaction
  107871. _this._applyUserInteraction();
  107872. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  107873. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  107874. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  107875. // Step camera rotation by rotation speed
  107876. if (_this._attachedCamera) {
  107877. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  107878. }
  107879. });
  107880. };
  107881. /**
  107882. * Detaches the behavior from its current arc rotate camera.
  107883. */
  107884. AutoRotationBehavior.prototype.detach = function () {
  107885. if (!this._attachedCamera) {
  107886. return;
  107887. }
  107888. var scene = this._attachedCamera.getScene();
  107889. if (this._onPrePointerObservableObserver) {
  107890. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  107891. }
  107892. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  107893. this._attachedCamera = null;
  107894. };
  107895. /**
  107896. * Returns true if user is scrolling.
  107897. * @return true if user is scrolling.
  107898. */
  107899. AutoRotationBehavior.prototype._userIsZooming = function () {
  107900. if (!this._attachedCamera) {
  107901. return false;
  107902. }
  107903. return this._attachedCamera.inertialRadiusOffset !== 0;
  107904. };
  107905. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  107906. if (!this._attachedCamera) {
  107907. return false;
  107908. }
  107909. var zoomHasHitLimit = false;
  107910. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  107911. zoomHasHitLimit = true;
  107912. }
  107913. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  107914. this._lastFrameRadius = this._attachedCamera.radius;
  107915. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  107916. };
  107917. /**
  107918. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  107919. */
  107920. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  107921. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  107922. this._lastInteractionTime = BABYLON.Tools.Now;
  107923. }
  107924. };
  107925. // Tools
  107926. AutoRotationBehavior.prototype._userIsMoving = function () {
  107927. if (!this._attachedCamera) {
  107928. return false;
  107929. }
  107930. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  107931. this._attachedCamera.inertialBetaOffset !== 0 ||
  107932. this._attachedCamera.inertialRadiusOffset !== 0 ||
  107933. this._attachedCamera.inertialPanningX !== 0 ||
  107934. this._attachedCamera.inertialPanningY !== 0 ||
  107935. this._isPointerDown;
  107936. };
  107937. return AutoRotationBehavior;
  107938. }());
  107939. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  107940. })(BABYLON || (BABYLON = {}));
  107941. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  107942. var BABYLON;
  107943. (function (BABYLON) {
  107944. var NullEngineOptions = /** @class */ (function () {
  107945. function NullEngineOptions() {
  107946. this.renderWidth = 512;
  107947. this.renderHeight = 256;
  107948. this.textureSize = 512;
  107949. this.deterministicLockstep = false;
  107950. this.lockstepMaxSteps = 4;
  107951. }
  107952. return NullEngineOptions;
  107953. }());
  107954. BABYLON.NullEngineOptions = NullEngineOptions;
  107955. /**
  107956. * The null engine class provides support for headless version of babylon.js.
  107957. * This can be used in server side scenario or for testing purposes
  107958. */
  107959. var NullEngine = /** @class */ (function (_super) {
  107960. __extends(NullEngine, _super);
  107961. function NullEngine(options) {
  107962. if (options === void 0) { options = new NullEngineOptions(); }
  107963. var _this = _super.call(this, null) || this;
  107964. if (options.deterministicLockstep === undefined) {
  107965. options.deterministicLockstep = false;
  107966. }
  107967. if (options.lockstepMaxSteps === undefined) {
  107968. options.lockstepMaxSteps = 4;
  107969. }
  107970. _this._options = options;
  107971. // Init caps
  107972. // We consider we are on a webgl1 capable device
  107973. _this._caps = new BABYLON.EngineCapabilities();
  107974. _this._caps.maxTexturesImageUnits = 16;
  107975. _this._caps.maxVertexTextureImageUnits = 16;
  107976. _this._caps.maxTextureSize = 512;
  107977. _this._caps.maxCubemapTextureSize = 512;
  107978. _this._caps.maxRenderTextureSize = 512;
  107979. _this._caps.maxVertexAttribs = 16;
  107980. _this._caps.maxVaryingVectors = 16;
  107981. _this._caps.maxFragmentUniformVectors = 16;
  107982. _this._caps.maxVertexUniformVectors = 16;
  107983. // Extensions
  107984. _this._caps.standardDerivatives = false;
  107985. _this._caps.astc = null;
  107986. _this._caps.s3tc = null;
  107987. _this._caps.pvrtc = null;
  107988. _this._caps.etc1 = null;
  107989. _this._caps.etc2 = null;
  107990. _this._caps.textureAnisotropicFilterExtension = null;
  107991. _this._caps.maxAnisotropy = 0;
  107992. _this._caps.uintIndices = false;
  107993. _this._caps.fragmentDepthSupported = false;
  107994. _this._caps.highPrecisionShaderSupported = true;
  107995. _this._caps.colorBufferFloat = false;
  107996. _this._caps.textureFloat = false;
  107997. _this._caps.textureFloatLinearFiltering = false;
  107998. _this._caps.textureFloatRender = false;
  107999. _this._caps.textureHalfFloat = false;
  108000. _this._caps.textureHalfFloatLinearFiltering = false;
  108001. _this._caps.textureHalfFloatRender = false;
  108002. _this._caps.textureLOD = false;
  108003. _this._caps.drawBuffersExtension = false;
  108004. _this._caps.depthTextureExtension = false;
  108005. _this._caps.vertexArrayObject = false;
  108006. _this._caps.instancedArrays = false;
  108007. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  108008. // Wrappers
  108009. if (typeof URL === "undefined") {
  108010. URL = {
  108011. createObjectURL: function () { },
  108012. revokeObjectURL: function () { }
  108013. };
  108014. }
  108015. if (typeof Blob === "undefined") {
  108016. Blob = function () { };
  108017. }
  108018. return _this;
  108019. }
  108020. NullEngine.prototype.isDeterministicLockStep = function () {
  108021. return this._options.deterministicLockstep;
  108022. };
  108023. NullEngine.prototype.getLockstepMaxSteps = function () {
  108024. return this._options.lockstepMaxSteps;
  108025. };
  108026. NullEngine.prototype.getHardwareScalingLevel = function () {
  108027. return 1.0;
  108028. };
  108029. NullEngine.prototype.createVertexBuffer = function (vertices) {
  108030. return {
  108031. capacity: 0,
  108032. references: 1,
  108033. is32Bits: false
  108034. };
  108035. };
  108036. NullEngine.prototype.createIndexBuffer = function (indices) {
  108037. return {
  108038. capacity: 0,
  108039. references: 1,
  108040. is32Bits: false
  108041. };
  108042. };
  108043. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  108044. if (stencil === void 0) { stencil = false; }
  108045. };
  108046. NullEngine.prototype.getRenderWidth = function (useScreen) {
  108047. if (useScreen === void 0) { useScreen = false; }
  108048. if (!useScreen && this._currentRenderTarget) {
  108049. return this._currentRenderTarget.width;
  108050. }
  108051. return this._options.renderWidth;
  108052. };
  108053. NullEngine.prototype.getRenderHeight = function (useScreen) {
  108054. if (useScreen === void 0) { useScreen = false; }
  108055. if (!useScreen && this._currentRenderTarget) {
  108056. return this._currentRenderTarget.height;
  108057. }
  108058. return this._options.renderHeight;
  108059. };
  108060. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  108061. this._cachedViewport = viewport;
  108062. };
  108063. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  108064. return {
  108065. transformFeedback: null,
  108066. __SPECTOR_rebuildProgram: null
  108067. };
  108068. };
  108069. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  108070. return [];
  108071. };
  108072. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  108073. return [];
  108074. };
  108075. NullEngine.prototype.bindSamplers = function (effect) {
  108076. this._currentEffect = null;
  108077. };
  108078. NullEngine.prototype.enableEffect = function (effect) {
  108079. this._currentEffect = effect;
  108080. if (effect.onBind) {
  108081. effect.onBind(effect);
  108082. }
  108083. if (effect._onBindObservable) {
  108084. effect._onBindObservable.notifyObservers(effect);
  108085. }
  108086. };
  108087. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  108088. if (zOffset === void 0) { zOffset = 0; }
  108089. if (reverseSide === void 0) { reverseSide = false; }
  108090. };
  108091. NullEngine.prototype.setIntArray = function (uniform, array) {
  108092. };
  108093. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  108094. };
  108095. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  108096. };
  108097. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  108098. };
  108099. NullEngine.prototype.setFloatArray = function (uniform, array) {
  108100. };
  108101. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  108102. };
  108103. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  108104. };
  108105. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  108106. };
  108107. NullEngine.prototype.setArray = function (uniform, array) {
  108108. };
  108109. NullEngine.prototype.setArray2 = function (uniform, array) {
  108110. };
  108111. NullEngine.prototype.setArray3 = function (uniform, array) {
  108112. };
  108113. NullEngine.prototype.setArray4 = function (uniform, array) {
  108114. };
  108115. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  108116. };
  108117. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  108118. };
  108119. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  108120. };
  108121. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  108122. };
  108123. NullEngine.prototype.setFloat = function (uniform, value) {
  108124. };
  108125. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  108126. };
  108127. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  108128. };
  108129. NullEngine.prototype.setBool = function (uniform, bool) {
  108130. };
  108131. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  108132. };
  108133. NullEngine.prototype.setColor3 = function (uniform, color3) {
  108134. };
  108135. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  108136. };
  108137. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  108138. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  108139. if (this._alphaMode === mode) {
  108140. return;
  108141. }
  108142. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  108143. if (!noDepthWriteChange) {
  108144. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  108145. }
  108146. this._alphaMode = mode;
  108147. };
  108148. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  108149. };
  108150. NullEngine.prototype.wipeCaches = function (bruteForce) {
  108151. if (this.preventCacheWipeBetweenFrames) {
  108152. return;
  108153. }
  108154. this.resetTextureCache();
  108155. this._currentEffect = null;
  108156. if (bruteForce) {
  108157. this._currentProgram = null;
  108158. this._stencilState.reset();
  108159. this._depthCullingState.reset();
  108160. this._alphaState.reset();
  108161. }
  108162. this._cachedVertexBuffers = null;
  108163. this._cachedIndexBuffer = null;
  108164. this._cachedEffectForVertexBuffers = null;
  108165. };
  108166. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  108167. };
  108168. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  108169. };
  108170. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  108171. };
  108172. /** @hidden */
  108173. NullEngine.prototype._createTexture = function () {
  108174. return {};
  108175. };
  108176. /** @hidden */
  108177. NullEngine.prototype._releaseTexture = function (texture) {
  108178. };
  108179. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  108180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  108181. if (onLoad === void 0) { onLoad = null; }
  108182. if (onError === void 0) { onError = null; }
  108183. if (buffer === void 0) { buffer = null; }
  108184. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  108185. var url = String(urlArg);
  108186. texture.url = url;
  108187. texture.generateMipMaps = !noMipmap;
  108188. texture.samplingMode = samplingMode;
  108189. texture.invertY = invertY;
  108190. texture.baseWidth = this._options.textureSize;
  108191. texture.baseHeight = this._options.textureSize;
  108192. texture.width = this._options.textureSize;
  108193. texture.height = this._options.textureSize;
  108194. if (format) {
  108195. texture.format = format;
  108196. }
  108197. texture.isReady = true;
  108198. if (onLoad) {
  108199. onLoad();
  108200. }
  108201. this._internalTexturesCache.push(texture);
  108202. return texture;
  108203. };
  108204. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  108205. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  108206. if (options !== undefined && typeof options === "object") {
  108207. fullOptions.generateMipMaps = options.generateMipMaps;
  108208. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  108209. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  108210. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  108211. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  108212. }
  108213. else {
  108214. fullOptions.generateMipMaps = options;
  108215. fullOptions.generateDepthBuffer = true;
  108216. fullOptions.generateStencilBuffer = false;
  108217. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  108218. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108219. }
  108220. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  108221. var width = size.width || size;
  108222. var height = size.height || size;
  108223. texture._depthStencilBuffer = {};
  108224. texture._framebuffer = {};
  108225. texture.baseWidth = width;
  108226. texture.baseHeight = height;
  108227. texture.width = width;
  108228. texture.height = height;
  108229. texture.isReady = true;
  108230. texture.samples = 1;
  108231. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  108232. texture.samplingMode = fullOptions.samplingMode;
  108233. texture.type = fullOptions.type;
  108234. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  108235. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  108236. this._internalTexturesCache.push(texture);
  108237. return texture;
  108238. };
  108239. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  108240. texture.samplingMode = samplingMode;
  108241. };
  108242. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  108243. if (this._currentRenderTarget) {
  108244. this.unBindFramebuffer(this._currentRenderTarget);
  108245. }
  108246. this._currentRenderTarget = texture;
  108247. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  108248. if (this._cachedViewport && !forceFullscreenViewport) {
  108249. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  108250. }
  108251. };
  108252. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  108253. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  108254. this._currentRenderTarget = null;
  108255. if (onBeforeUnbind) {
  108256. if (texture._MSAAFramebuffer) {
  108257. this._currentFramebuffer = texture._framebuffer;
  108258. }
  108259. onBeforeUnbind();
  108260. }
  108261. this._currentFramebuffer = null;
  108262. };
  108263. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  108264. var vbo = {
  108265. capacity: 1,
  108266. references: 1,
  108267. is32Bits: false
  108268. };
  108269. return vbo;
  108270. };
  108271. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  108272. if (premulAlpha === void 0) { premulAlpha = false; }
  108273. };
  108274. /**
  108275. * @hidden
  108276. * Get the current error code of the webGL context
  108277. * @returns the error code
  108278. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  108279. */
  108280. NullEngine.prototype.getError = function () {
  108281. return 0;
  108282. };
  108283. /** @hidden */
  108284. NullEngine.prototype._getUnpackAlignement = function () {
  108285. return 1;
  108286. };
  108287. /** @hidden */
  108288. NullEngine.prototype._unpackFlipY = function (value) {
  108289. };
  108290. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  108291. if (offset === void 0) { offset = 0; }
  108292. };
  108293. /**
  108294. * Updates a dynamic vertex buffer.
  108295. * @param vertexBuffer the vertex buffer to update
  108296. * @param data the data used to update the vertex buffer
  108297. * @param byteOffset the byte offset of the data (optional)
  108298. * @param byteLength the byte length of the data (optional)
  108299. */
  108300. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  108301. };
  108302. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  108303. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  108304. this._boundTexturesCache[this._activeChannel] = texture;
  108305. return true;
  108306. }
  108307. return false;
  108308. };
  108309. /** @hidden */
  108310. NullEngine.prototype._bindTexture = function (channel, texture) {
  108311. if (channel < 0) {
  108312. return;
  108313. }
  108314. this._bindTextureDirectly(0, texture);
  108315. };
  108316. /** @hidden */
  108317. NullEngine.prototype._releaseBuffer = function (buffer) {
  108318. buffer.references--;
  108319. if (buffer.references === 0) {
  108320. return true;
  108321. }
  108322. return false;
  108323. };
  108324. NullEngine.prototype.releaseEffects = function () {
  108325. };
  108326. NullEngine.prototype.displayLoadingUI = function () {
  108327. };
  108328. NullEngine.prototype.hideLoadingUI = function () {
  108329. };
  108330. /** @hidden */
  108331. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  108332. if (faceIndex === void 0) { faceIndex = 0; }
  108333. if (lod === void 0) { lod = 0; }
  108334. };
  108335. /** @hidden */
  108336. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  108337. if (faceIndex === void 0) { faceIndex = 0; }
  108338. if (lod === void 0) { lod = 0; }
  108339. };
  108340. /** @hidden */
  108341. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  108342. if (faceIndex === void 0) { faceIndex = 0; }
  108343. if (lod === void 0) { lod = 0; }
  108344. };
  108345. /** @hidden */
  108346. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  108347. if (faceIndex === void 0) { faceIndex = 0; }
  108348. if (lod === void 0) { lod = 0; }
  108349. };
  108350. return NullEngine;
  108351. }(BABYLON.Engine));
  108352. BABYLON.NullEngine = NullEngine;
  108353. })(BABYLON || (BABYLON = {}));
  108354. //# sourceMappingURL=babylon.nullEngine.js.map
  108355. var BABYLON;
  108356. (function (BABYLON) {
  108357. /**
  108358. * This class can be used to get instrumentation data from a Babylon engine
  108359. */
  108360. var EngineInstrumentation = /** @class */ (function () {
  108361. function EngineInstrumentation(engine) {
  108362. this.engine = engine;
  108363. this._captureGPUFrameTime = false;
  108364. this._gpuFrameTime = new BABYLON.PerfCounter();
  108365. this._captureShaderCompilationTime = false;
  108366. this._shaderCompilationTime = new BABYLON.PerfCounter();
  108367. // Observers
  108368. this._onBeginFrameObserver = null;
  108369. this._onEndFrameObserver = null;
  108370. this._onBeforeShaderCompilationObserver = null;
  108371. this._onAfterShaderCompilationObserver = null;
  108372. }
  108373. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  108374. // Properties
  108375. /**
  108376. * Gets the perf counter used for GPU frame time
  108377. */
  108378. get: function () {
  108379. return this._gpuFrameTime;
  108380. },
  108381. enumerable: true,
  108382. configurable: true
  108383. });
  108384. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  108385. /**
  108386. * Gets the GPU frame time capture status
  108387. */
  108388. get: function () {
  108389. return this._captureGPUFrameTime;
  108390. },
  108391. /**
  108392. * Enable or disable the GPU frame time capture
  108393. */
  108394. set: function (value) {
  108395. var _this = this;
  108396. if (value === this._captureGPUFrameTime) {
  108397. return;
  108398. }
  108399. this._captureGPUFrameTime = value;
  108400. if (value) {
  108401. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  108402. if (!_this._gpuFrameTimeToken) {
  108403. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  108404. }
  108405. });
  108406. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  108407. if (!_this._gpuFrameTimeToken) {
  108408. return;
  108409. }
  108410. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  108411. if (time > -1) {
  108412. _this._gpuFrameTimeToken = null;
  108413. _this._gpuFrameTime.fetchNewFrame();
  108414. _this._gpuFrameTime.addCount(time, true);
  108415. }
  108416. });
  108417. }
  108418. else {
  108419. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108420. this._onBeginFrameObserver = null;
  108421. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108422. this._onEndFrameObserver = null;
  108423. }
  108424. },
  108425. enumerable: true,
  108426. configurable: true
  108427. });
  108428. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  108429. /**
  108430. * Gets the perf counter used for shader compilation time
  108431. */
  108432. get: function () {
  108433. return this._shaderCompilationTime;
  108434. },
  108435. enumerable: true,
  108436. configurable: true
  108437. });
  108438. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  108439. /**
  108440. * Gets the shader compilation time capture status
  108441. */
  108442. get: function () {
  108443. return this._captureShaderCompilationTime;
  108444. },
  108445. /**
  108446. * Enable or disable the shader compilation time capture
  108447. */
  108448. set: function (value) {
  108449. var _this = this;
  108450. if (value === this._captureShaderCompilationTime) {
  108451. return;
  108452. }
  108453. this._captureShaderCompilationTime = value;
  108454. if (value) {
  108455. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  108456. _this._shaderCompilationTime.fetchNewFrame();
  108457. _this._shaderCompilationTime.beginMonitoring();
  108458. });
  108459. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  108460. _this._shaderCompilationTime.endMonitoring();
  108461. });
  108462. }
  108463. else {
  108464. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108465. this._onBeforeShaderCompilationObserver = null;
  108466. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108467. this._onAfterShaderCompilationObserver = null;
  108468. }
  108469. },
  108470. enumerable: true,
  108471. configurable: true
  108472. });
  108473. EngineInstrumentation.prototype.dispose = function () {
  108474. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  108475. this._onBeginFrameObserver = null;
  108476. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  108477. this._onEndFrameObserver = null;
  108478. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  108479. this._onBeforeShaderCompilationObserver = null;
  108480. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  108481. this._onAfterShaderCompilationObserver = null;
  108482. this.engine = null;
  108483. };
  108484. return EngineInstrumentation;
  108485. }());
  108486. BABYLON.EngineInstrumentation = EngineInstrumentation;
  108487. })(BABYLON || (BABYLON = {}));
  108488. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  108489. var BABYLON;
  108490. (function (BABYLON) {
  108491. /**
  108492. * This class can be used to get instrumentation data from a Babylon engine
  108493. */
  108494. var SceneInstrumentation = /** @class */ (function () {
  108495. function SceneInstrumentation(scene) {
  108496. var _this = this;
  108497. this.scene = scene;
  108498. this._captureActiveMeshesEvaluationTime = false;
  108499. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  108500. this._captureRenderTargetsRenderTime = false;
  108501. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  108502. this._captureFrameTime = false;
  108503. this._frameTime = new BABYLON.PerfCounter();
  108504. this._captureRenderTime = false;
  108505. this._renderTime = new BABYLON.PerfCounter();
  108506. this._captureInterFrameTime = false;
  108507. this._interFrameTime = new BABYLON.PerfCounter();
  108508. this._captureParticlesRenderTime = false;
  108509. this._particlesRenderTime = new BABYLON.PerfCounter();
  108510. this._captureSpritesRenderTime = false;
  108511. this._spritesRenderTime = new BABYLON.PerfCounter();
  108512. this._capturePhysicsTime = false;
  108513. this._physicsTime = new BABYLON.PerfCounter();
  108514. this._captureAnimationsTime = false;
  108515. this._animationsTime = new BABYLON.PerfCounter();
  108516. this._captureCameraRenderTime = false;
  108517. this._cameraRenderTime = new BABYLON.PerfCounter();
  108518. // Observers
  108519. this._onBeforeActiveMeshesEvaluationObserver = null;
  108520. this._onAfterActiveMeshesEvaluationObserver = null;
  108521. this._onBeforeRenderTargetsRenderObserver = null;
  108522. this._onAfterRenderTargetsRenderObserver = null;
  108523. this._onAfterRenderObserver = null;
  108524. this._onBeforeDrawPhaseObserver = null;
  108525. this._onAfterDrawPhaseObserver = null;
  108526. this._onBeforeAnimationsObserver = null;
  108527. this._onBeforeParticlesRenderingObserver = null;
  108528. this._onAfterParticlesRenderingObserver = null;
  108529. this._onBeforeSpritesRenderingObserver = null;
  108530. this._onAfterSpritesRenderingObserver = null;
  108531. this._onBeforePhysicsObserver = null;
  108532. this._onAfterPhysicsObserver = null;
  108533. this._onAfterAnimationsObserver = null;
  108534. this._onBeforeCameraRenderObserver = null;
  108535. this._onAfterCameraRenderObserver = null;
  108536. // Before render
  108537. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  108538. if (_this._captureActiveMeshesEvaluationTime) {
  108539. _this._activeMeshesEvaluationTime.fetchNewFrame();
  108540. }
  108541. if (_this._captureRenderTargetsRenderTime) {
  108542. _this._renderTargetsRenderTime.fetchNewFrame();
  108543. }
  108544. if (_this._captureFrameTime) {
  108545. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  108546. _this._frameTime.beginMonitoring();
  108547. }
  108548. if (_this._captureInterFrameTime) {
  108549. _this._interFrameTime.endMonitoring();
  108550. }
  108551. if (_this._captureParticlesRenderTime) {
  108552. _this._particlesRenderTime.fetchNewFrame();
  108553. }
  108554. if (_this._captureSpritesRenderTime) {
  108555. _this._spritesRenderTime.fetchNewFrame();
  108556. }
  108557. if (_this._captureAnimationsTime) {
  108558. _this._animationsTime.beginMonitoring();
  108559. }
  108560. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  108561. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  108562. });
  108563. // After render
  108564. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  108565. if (_this._captureFrameTime) {
  108566. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  108567. _this._frameTime.endMonitoring();
  108568. }
  108569. if (_this._captureRenderTime) {
  108570. _this._renderTime.endMonitoring(false);
  108571. }
  108572. if (_this._captureInterFrameTime) {
  108573. _this._interFrameTime.beginMonitoring();
  108574. }
  108575. });
  108576. }
  108577. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  108578. // Properties
  108579. /**
  108580. * Gets the perf counter used for active meshes evaluation time
  108581. */
  108582. get: function () {
  108583. return this._activeMeshesEvaluationTime;
  108584. },
  108585. enumerable: true,
  108586. configurable: true
  108587. });
  108588. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  108589. /**
  108590. * Gets the active meshes evaluation time capture status
  108591. */
  108592. get: function () {
  108593. return this._captureActiveMeshesEvaluationTime;
  108594. },
  108595. /**
  108596. * Enable or disable the active meshes evaluation time capture
  108597. */
  108598. set: function (value) {
  108599. var _this = this;
  108600. if (value === this._captureActiveMeshesEvaluationTime) {
  108601. return;
  108602. }
  108603. this._captureActiveMeshesEvaluationTime = value;
  108604. if (value) {
  108605. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  108606. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  108607. _this._activeMeshesEvaluationTime.beginMonitoring();
  108608. });
  108609. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  108610. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  108611. _this._activeMeshesEvaluationTime.endMonitoring();
  108612. });
  108613. }
  108614. else {
  108615. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  108616. this._onBeforeActiveMeshesEvaluationObserver = null;
  108617. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  108618. this._onAfterActiveMeshesEvaluationObserver = null;
  108619. }
  108620. },
  108621. enumerable: true,
  108622. configurable: true
  108623. });
  108624. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  108625. /**
  108626. * Gets the perf counter used for render targets render time
  108627. */
  108628. get: function () {
  108629. return this._renderTargetsRenderTime;
  108630. },
  108631. enumerable: true,
  108632. configurable: true
  108633. });
  108634. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  108635. /**
  108636. * Gets the render targets render time capture status
  108637. */
  108638. get: function () {
  108639. return this._captureRenderTargetsRenderTime;
  108640. },
  108641. /**
  108642. * Enable or disable the render targets render time capture
  108643. */
  108644. set: function (value) {
  108645. var _this = this;
  108646. if (value === this._captureRenderTargetsRenderTime) {
  108647. return;
  108648. }
  108649. this._captureRenderTargetsRenderTime = value;
  108650. if (value) {
  108651. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  108652. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  108653. _this._renderTargetsRenderTime.beginMonitoring();
  108654. });
  108655. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  108656. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  108657. _this._renderTargetsRenderTime.endMonitoring(false);
  108658. });
  108659. }
  108660. else {
  108661. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  108662. this._onBeforeRenderTargetsRenderObserver = null;
  108663. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  108664. this._onAfterRenderTargetsRenderObserver = null;
  108665. }
  108666. },
  108667. enumerable: true,
  108668. configurable: true
  108669. });
  108670. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  108671. /**
  108672. * Gets the perf counter used for particles render time
  108673. */
  108674. get: function () {
  108675. return this._particlesRenderTime;
  108676. },
  108677. enumerable: true,
  108678. configurable: true
  108679. });
  108680. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  108681. /**
  108682. * Gets the particles render time capture status
  108683. */
  108684. get: function () {
  108685. return this._captureParticlesRenderTime;
  108686. },
  108687. /**
  108688. * Enable or disable the particles render time capture
  108689. */
  108690. set: function (value) {
  108691. var _this = this;
  108692. if (value === this._captureParticlesRenderTime) {
  108693. return;
  108694. }
  108695. this._captureParticlesRenderTime = value;
  108696. if (value) {
  108697. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  108698. BABYLON.Tools.StartPerformanceCounter("Particles");
  108699. _this._particlesRenderTime.beginMonitoring();
  108700. });
  108701. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  108702. BABYLON.Tools.EndPerformanceCounter("Particles");
  108703. _this._particlesRenderTime.endMonitoring(false);
  108704. });
  108705. }
  108706. else {
  108707. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  108708. this._onBeforeParticlesRenderingObserver = null;
  108709. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  108710. this._onAfterParticlesRenderingObserver = null;
  108711. }
  108712. },
  108713. enumerable: true,
  108714. configurable: true
  108715. });
  108716. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  108717. /**
  108718. * Gets the perf counter used for sprites render time
  108719. */
  108720. get: function () {
  108721. return this._spritesRenderTime;
  108722. },
  108723. enumerable: true,
  108724. configurable: true
  108725. });
  108726. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  108727. /**
  108728. * Gets the sprites render time capture status
  108729. */
  108730. get: function () {
  108731. return this._captureSpritesRenderTime;
  108732. },
  108733. /**
  108734. * Enable or disable the sprites render time capture
  108735. */
  108736. set: function (value) {
  108737. var _this = this;
  108738. if (value === this._captureSpritesRenderTime) {
  108739. return;
  108740. }
  108741. this._captureSpritesRenderTime = value;
  108742. if (!this.scene.spriteManagers) {
  108743. return;
  108744. }
  108745. if (value) {
  108746. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  108747. BABYLON.Tools.StartPerformanceCounter("Sprites");
  108748. _this._spritesRenderTime.beginMonitoring();
  108749. });
  108750. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  108751. BABYLON.Tools.EndPerformanceCounter("Sprites");
  108752. _this._spritesRenderTime.endMonitoring(false);
  108753. });
  108754. }
  108755. else {
  108756. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  108757. this._onBeforeSpritesRenderingObserver = null;
  108758. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  108759. this._onAfterSpritesRenderingObserver = null;
  108760. }
  108761. },
  108762. enumerable: true,
  108763. configurable: true
  108764. });
  108765. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  108766. /**
  108767. * Gets the perf counter used for physics time
  108768. */
  108769. get: function () {
  108770. return this._physicsTime;
  108771. },
  108772. enumerable: true,
  108773. configurable: true
  108774. });
  108775. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  108776. /**
  108777. * Gets the physics time capture status
  108778. */
  108779. get: function () {
  108780. return this._capturePhysicsTime;
  108781. },
  108782. /**
  108783. * Enable or disable the physics time capture
  108784. */
  108785. set: function (value) {
  108786. var _this = this;
  108787. if (value === this._capturePhysicsTime) {
  108788. return;
  108789. }
  108790. if (!this.scene.onBeforePhysicsObservable) {
  108791. return;
  108792. }
  108793. this._capturePhysicsTime = value;
  108794. if (value) {
  108795. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  108796. BABYLON.Tools.StartPerformanceCounter("Physics");
  108797. _this._physicsTime.beginMonitoring();
  108798. });
  108799. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  108800. BABYLON.Tools.EndPerformanceCounter("Physics");
  108801. _this._physicsTime.endMonitoring();
  108802. });
  108803. }
  108804. else {
  108805. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  108806. this._onBeforePhysicsObserver = null;
  108807. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  108808. this._onAfterPhysicsObserver = null;
  108809. }
  108810. },
  108811. enumerable: true,
  108812. configurable: true
  108813. });
  108814. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  108815. /**
  108816. * Gets the perf counter used for animations time
  108817. */
  108818. get: function () {
  108819. return this._animationsTime;
  108820. },
  108821. enumerable: true,
  108822. configurable: true
  108823. });
  108824. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  108825. /**
  108826. * Gets the animations time capture status
  108827. */
  108828. get: function () {
  108829. return this._captureAnimationsTime;
  108830. },
  108831. /**
  108832. * Enable or disable the animations time capture
  108833. */
  108834. set: function (value) {
  108835. var _this = this;
  108836. if (value === this._captureAnimationsTime) {
  108837. return;
  108838. }
  108839. this._captureAnimationsTime = value;
  108840. if (value) {
  108841. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  108842. _this._animationsTime.endMonitoring();
  108843. });
  108844. }
  108845. else {
  108846. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  108847. this._onAfterAnimationsObserver = null;
  108848. }
  108849. },
  108850. enumerable: true,
  108851. configurable: true
  108852. });
  108853. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  108854. /**
  108855. * Gets the perf counter used for frame time capture
  108856. */
  108857. get: function () {
  108858. return this._frameTime;
  108859. },
  108860. enumerable: true,
  108861. configurable: true
  108862. });
  108863. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  108864. /**
  108865. * Gets the frame time capture status
  108866. */
  108867. get: function () {
  108868. return this._captureFrameTime;
  108869. },
  108870. /**
  108871. * Enable or disable the frame time capture
  108872. */
  108873. set: function (value) {
  108874. this._captureFrameTime = value;
  108875. },
  108876. enumerable: true,
  108877. configurable: true
  108878. });
  108879. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  108880. /**
  108881. * Gets the perf counter used for inter-frames time capture
  108882. */
  108883. get: function () {
  108884. return this._interFrameTime;
  108885. },
  108886. enumerable: true,
  108887. configurable: true
  108888. });
  108889. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  108890. /**
  108891. * Gets the inter-frames time capture status
  108892. */
  108893. get: function () {
  108894. return this._captureInterFrameTime;
  108895. },
  108896. /**
  108897. * Enable or disable the inter-frames time capture
  108898. */
  108899. set: function (value) {
  108900. this._captureInterFrameTime = value;
  108901. },
  108902. enumerable: true,
  108903. configurable: true
  108904. });
  108905. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  108906. /**
  108907. * Gets the perf counter used for render time capture
  108908. */
  108909. get: function () {
  108910. return this._renderTime;
  108911. },
  108912. enumerable: true,
  108913. configurable: true
  108914. });
  108915. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  108916. /**
  108917. * Gets the render time capture status
  108918. */
  108919. get: function () {
  108920. return this._captureRenderTime;
  108921. },
  108922. /**
  108923. * Enable or disable the render time capture
  108924. */
  108925. set: function (value) {
  108926. var _this = this;
  108927. if (value === this._captureRenderTime) {
  108928. return;
  108929. }
  108930. this._captureRenderTime = value;
  108931. if (value) {
  108932. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  108933. _this._renderTime.beginMonitoring();
  108934. BABYLON.Tools.StartPerformanceCounter("Main render");
  108935. });
  108936. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  108937. _this._renderTime.endMonitoring(false);
  108938. BABYLON.Tools.EndPerformanceCounter("Main render");
  108939. });
  108940. }
  108941. else {
  108942. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  108943. this._onBeforeDrawPhaseObserver = null;
  108944. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  108945. this._onAfterDrawPhaseObserver = null;
  108946. }
  108947. },
  108948. enumerable: true,
  108949. configurable: true
  108950. });
  108951. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  108952. /**
  108953. * Gets the perf counter used for camera render time capture
  108954. */
  108955. get: function () {
  108956. return this._cameraRenderTime;
  108957. },
  108958. enumerable: true,
  108959. configurable: true
  108960. });
  108961. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  108962. /**
  108963. * Gets the camera render time capture status
  108964. */
  108965. get: function () {
  108966. return this._captureCameraRenderTime;
  108967. },
  108968. /**
  108969. * Enable or disable the camera render time capture
  108970. */
  108971. set: function (value) {
  108972. var _this = this;
  108973. if (value === this._captureCameraRenderTime) {
  108974. return;
  108975. }
  108976. this._captureCameraRenderTime = value;
  108977. if (value) {
  108978. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  108979. _this._cameraRenderTime.beginMonitoring();
  108980. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  108981. });
  108982. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  108983. _this._cameraRenderTime.endMonitoring(false);
  108984. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  108985. });
  108986. }
  108987. else {
  108988. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  108989. this._onBeforeCameraRenderObserver = null;
  108990. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  108991. this._onAfterCameraRenderObserver = null;
  108992. }
  108993. },
  108994. enumerable: true,
  108995. configurable: true
  108996. });
  108997. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  108998. /**
  108999. * Gets the perf counter used for draw calls
  109000. */
  109001. get: function () {
  109002. return this.scene.getEngine()._drawCalls;
  109003. },
  109004. enumerable: true,
  109005. configurable: true
  109006. });
  109007. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  109008. /**
  109009. * Gets the perf counter used for texture collisions
  109010. */
  109011. get: function () {
  109012. return this.scene.getEngine()._textureCollisions;
  109013. },
  109014. enumerable: true,
  109015. configurable: true
  109016. });
  109017. SceneInstrumentation.prototype.dispose = function () {
  109018. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  109019. this._onAfterRenderObserver = null;
  109020. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  109021. this._onBeforeActiveMeshesEvaluationObserver = null;
  109022. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  109023. this._onAfterActiveMeshesEvaluationObserver = null;
  109024. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  109025. this._onBeforeRenderTargetsRenderObserver = null;
  109026. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  109027. this._onAfterRenderTargetsRenderObserver = null;
  109028. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  109029. this._onBeforeAnimationsObserver = null;
  109030. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  109031. this._onBeforeParticlesRenderingObserver = null;
  109032. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  109033. this._onAfterParticlesRenderingObserver = null;
  109034. if (this._onBeforeSpritesRenderingObserver) {
  109035. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  109036. this._onBeforeSpritesRenderingObserver = null;
  109037. }
  109038. if (this._onAfterSpritesRenderingObserver) {
  109039. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  109040. this._onAfterSpritesRenderingObserver = null;
  109041. }
  109042. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  109043. this._onBeforeDrawPhaseObserver = null;
  109044. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  109045. this._onAfterDrawPhaseObserver = null;
  109046. if (this._onBeforePhysicsObserver) {
  109047. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  109048. this._onBeforePhysicsObserver = null;
  109049. }
  109050. if (this._onAfterPhysicsObserver) {
  109051. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  109052. this._onAfterPhysicsObserver = null;
  109053. }
  109054. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  109055. this._onAfterAnimationsObserver = null;
  109056. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  109057. this._onBeforeCameraRenderObserver = null;
  109058. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  109059. this._onAfterCameraRenderObserver = null;
  109060. this.scene = null;
  109061. };
  109062. return SceneInstrumentation;
  109063. }());
  109064. BABYLON.SceneInstrumentation = SceneInstrumentation;
  109065. })(BABYLON || (BABYLON = {}));
  109066. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  109067. var BABYLON;
  109068. (function (BABYLON) {
  109069. /**
  109070. * @hidden
  109071. **/
  109072. var _TimeToken = /** @class */ (function () {
  109073. function _TimeToken() {
  109074. this._timeElapsedQueryEnded = false;
  109075. }
  109076. return _TimeToken;
  109077. }());
  109078. BABYLON._TimeToken = _TimeToken;
  109079. })(BABYLON || (BABYLON = {}));
  109080. //# sourceMappingURL=babylon.timeToken.js.map
  109081. var BABYLON;
  109082. (function (BABYLON) {
  109083. /**
  109084. * Background material defines definition.
  109085. * @hidden Mainly internal Use
  109086. */
  109087. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  109088. __extends(BackgroundMaterialDefines, _super);
  109089. /**
  109090. * Constructor of the defines.
  109091. */
  109092. function BackgroundMaterialDefines() {
  109093. var _this = _super.call(this) || this;
  109094. /**
  109095. * True if the diffuse texture is in use.
  109096. */
  109097. _this.DIFFUSE = false;
  109098. /**
  109099. * The direct UV channel to use.
  109100. */
  109101. _this.DIFFUSEDIRECTUV = 0;
  109102. /**
  109103. * True if the diffuse texture is in gamma space.
  109104. */
  109105. _this.GAMMADIFFUSE = false;
  109106. /**
  109107. * True if the diffuse texture has opacity in the alpha channel.
  109108. */
  109109. _this.DIFFUSEHASALPHA = false;
  109110. /**
  109111. * True if you want the material to fade to transparent at grazing angle.
  109112. */
  109113. _this.OPACITYFRESNEL = false;
  109114. /**
  109115. * True if an extra blur needs to be added in the reflection.
  109116. */
  109117. _this.REFLECTIONBLUR = false;
  109118. /**
  109119. * True if you want the material to fade to reflection at grazing angle.
  109120. */
  109121. _this.REFLECTIONFRESNEL = false;
  109122. /**
  109123. * True if you want the material to falloff as far as you move away from the scene center.
  109124. */
  109125. _this.REFLECTIONFALLOFF = false;
  109126. /**
  109127. * False if the current Webgl implementation does not support the texture lod extension.
  109128. */
  109129. _this.TEXTURELODSUPPORT = false;
  109130. /**
  109131. * True to ensure the data are premultiplied.
  109132. */
  109133. _this.PREMULTIPLYALPHA = false;
  109134. /**
  109135. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  109136. */
  109137. _this.USERGBCOLOR = false;
  109138. /**
  109139. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  109140. * stays aligned with the desired configuration.
  109141. */
  109142. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  109143. /**
  109144. * True to add noise in order to reduce the banding effect.
  109145. */
  109146. _this.NOISE = false;
  109147. /**
  109148. * is the reflection texture in BGR color scheme?
  109149. * Mainly used to solve a bug in ios10 video tag
  109150. */
  109151. _this.REFLECTIONBGR = false;
  109152. _this.IMAGEPROCESSING = false;
  109153. _this.VIGNETTE = false;
  109154. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  109155. _this.VIGNETTEBLENDMODEOPAQUE = false;
  109156. _this.TONEMAPPING = false;
  109157. _this.TONEMAPPING_ACES = false;
  109158. _this.CONTRAST = false;
  109159. _this.COLORCURVES = false;
  109160. _this.COLORGRADING = false;
  109161. _this.COLORGRADING3D = false;
  109162. _this.SAMPLER3DGREENDEPTH = false;
  109163. _this.SAMPLER3DBGRMAP = false;
  109164. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  109165. _this.EXPOSURE = false;
  109166. // Reflection.
  109167. _this.REFLECTION = false;
  109168. _this.REFLECTIONMAP_3D = false;
  109169. _this.REFLECTIONMAP_SPHERICAL = false;
  109170. _this.REFLECTIONMAP_PLANAR = false;
  109171. _this.REFLECTIONMAP_CUBIC = false;
  109172. _this.REFLECTIONMAP_PROJECTION = false;
  109173. _this.REFLECTIONMAP_SKYBOX = false;
  109174. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  109175. _this.REFLECTIONMAP_EXPLICIT = false;
  109176. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  109177. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  109178. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  109179. _this.INVERTCUBICMAP = false;
  109180. _this.REFLECTIONMAP_OPPOSITEZ = false;
  109181. _this.LODINREFLECTIONALPHA = false;
  109182. _this.GAMMAREFLECTION = false;
  109183. _this.RGBDREFLECTION = false;
  109184. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  109185. // Default BJS.
  109186. _this.MAINUV1 = false;
  109187. _this.MAINUV2 = false;
  109188. _this.UV1 = false;
  109189. _this.UV2 = false;
  109190. _this.CLIPPLANE = false;
  109191. _this.CLIPPLANE2 = false;
  109192. _this.CLIPPLANE3 = false;
  109193. _this.CLIPPLANE4 = false;
  109194. _this.POINTSIZE = false;
  109195. _this.FOG = false;
  109196. _this.NORMAL = false;
  109197. _this.NUM_BONE_INFLUENCERS = 0;
  109198. _this.BonesPerMesh = 0;
  109199. _this.INSTANCES = false;
  109200. _this.SHADOWFLOAT = false;
  109201. _this.rebuild();
  109202. return _this;
  109203. }
  109204. return BackgroundMaterialDefines;
  109205. }(BABYLON.MaterialDefines));
  109206. /**
  109207. * Background material used to create an efficient environement around your scene.
  109208. */
  109209. var BackgroundMaterial = /** @class */ (function (_super) {
  109210. __extends(BackgroundMaterial, _super);
  109211. /**
  109212. * Instantiates a Background Material in the given scene
  109213. * @param name The friendly name of the material
  109214. * @param scene The scene to add the material to
  109215. */
  109216. function BackgroundMaterial(name, scene) {
  109217. var _this = _super.call(this, name, scene) || this;
  109218. /**
  109219. * Key light Color (multiply against the environement texture)
  109220. */
  109221. _this.primaryColor = BABYLON.Color3.White();
  109222. _this._primaryColorShadowLevel = 0;
  109223. _this._primaryColorHighlightLevel = 0;
  109224. /**
  109225. * Reflection Texture used in the material.
  109226. * Should be author in a specific way for the best result (refer to the documentation).
  109227. */
  109228. _this.reflectionTexture = null;
  109229. /**
  109230. * Reflection Texture level of blur.
  109231. *
  109232. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  109233. * texture twice.
  109234. */
  109235. _this.reflectionBlur = 0;
  109236. /**
  109237. * Diffuse Texture used in the material.
  109238. * Should be author in a specific way for the best result (refer to the documentation).
  109239. */
  109240. _this.diffuseTexture = null;
  109241. _this._shadowLights = null;
  109242. /**
  109243. * Specify the list of lights casting shadow on the material.
  109244. * All scene shadow lights will be included if null.
  109245. */
  109246. _this.shadowLights = null;
  109247. /**
  109248. * Helps adjusting the shadow to a softer level if required.
  109249. * 0 means black shadows and 1 means no shadows.
  109250. */
  109251. _this.shadowLevel = 0;
  109252. /**
  109253. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  109254. * It is usually zero but might be interesting to modify according to your setup.
  109255. */
  109256. _this.sceneCenter = BABYLON.Vector3.Zero();
  109257. /**
  109258. * This helps specifying that the material is falling off to the sky box at grazing angle.
  109259. * This helps ensuring a nice transition when the camera goes under the ground.
  109260. */
  109261. _this.opacityFresnel = true;
  109262. /**
  109263. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  109264. * This helps adding a mirror texture on the ground.
  109265. */
  109266. _this.reflectionFresnel = false;
  109267. /**
  109268. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  109269. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  109270. */
  109271. _this.reflectionFalloffDistance = 0.0;
  109272. /**
  109273. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  109274. */
  109275. _this.reflectionAmount = 1.0;
  109276. /**
  109277. * This specifies the weight of the reflection at grazing angle.
  109278. */
  109279. _this.reflectionReflectance0 = 0.05;
  109280. /**
  109281. * This specifies the weight of the reflection at a perpendicular point of view.
  109282. */
  109283. _this.reflectionReflectance90 = 0.5;
  109284. /**
  109285. * Helps to directly use the maps channels instead of their level.
  109286. */
  109287. _this.useRGBColor = true;
  109288. /**
  109289. * This helps reducing the banding effect that could occur on the background.
  109290. */
  109291. _this.enableNoise = false;
  109292. _this._fovMultiplier = 1.0;
  109293. /**
  109294. * Enable the FOV adjustment feature controlled by fovMultiplier.
  109295. */
  109296. _this.useEquirectangularFOV = false;
  109297. _this._maxSimultaneousLights = 4;
  109298. /**
  109299. * Number of Simultaneous lights allowed on the material.
  109300. */
  109301. _this.maxSimultaneousLights = 4;
  109302. /**
  109303. * Keep track of the image processing observer to allow dispose and replace.
  109304. */
  109305. _this._imageProcessingObserver = null;
  109306. /**
  109307. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  109308. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  109309. */
  109310. _this.switchToBGR = false;
  109311. // Temp values kept as cache in the material.
  109312. _this._renderTargets = new BABYLON.SmartArray(16);
  109313. _this._reflectionControls = BABYLON.Vector4.Zero();
  109314. _this._white = BABYLON.Color3.White();
  109315. _this._primaryShadowColor = BABYLON.Color3.Black();
  109316. _this._primaryHighlightColor = BABYLON.Color3.Black();
  109317. // Setup the default processing configuration to the scene.
  109318. _this._attachImageProcessingConfiguration(null);
  109319. _this.getRenderTargetTextures = function () {
  109320. _this._renderTargets.reset();
  109321. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  109322. _this._renderTargets.push(_this._diffuseTexture);
  109323. }
  109324. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  109325. _this._renderTargets.push(_this._reflectionTexture);
  109326. }
  109327. return _this._renderTargets;
  109328. };
  109329. return _this;
  109330. }
  109331. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  109332. /**
  109333. * Experimental Internal Use Only.
  109334. *
  109335. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  109336. * This acts as a helper to set the primary color to a more "human friendly" value.
  109337. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  109338. * output color as close as possible from the chosen value.
  109339. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  109340. * part of lighting setup.)
  109341. */
  109342. get: function () {
  109343. return this.__perceptualColor;
  109344. },
  109345. set: function (value) {
  109346. this.__perceptualColor = value;
  109347. this._computePrimaryColorFromPerceptualColor();
  109348. this._markAllSubMeshesAsLightsDirty();
  109349. },
  109350. enumerable: true,
  109351. configurable: true
  109352. });
  109353. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  109354. /**
  109355. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  109356. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  109357. */
  109358. get: function () {
  109359. return this._primaryColorShadowLevel;
  109360. },
  109361. set: function (value) {
  109362. this._primaryColorShadowLevel = value;
  109363. this._computePrimaryColors();
  109364. this._markAllSubMeshesAsLightsDirty();
  109365. },
  109366. enumerable: true,
  109367. configurable: true
  109368. });
  109369. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  109370. /**
  109371. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  109372. * The primary color is used at the level chosen to define what the white area would look.
  109373. */
  109374. get: function () {
  109375. return this._primaryColorHighlightLevel;
  109376. },
  109377. set: function (value) {
  109378. this._primaryColorHighlightLevel = value;
  109379. this._computePrimaryColors();
  109380. this._markAllSubMeshesAsLightsDirty();
  109381. },
  109382. enumerable: true,
  109383. configurable: true
  109384. });
  109385. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  109386. /**
  109387. * Sets the reflection reflectance fresnel values according to the default standard
  109388. * empirically know to work well :-)
  109389. */
  109390. set: function (value) {
  109391. var reflectionWeight = value;
  109392. if (reflectionWeight < 0.5) {
  109393. reflectionWeight = reflectionWeight * 2.0;
  109394. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  109395. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  109396. }
  109397. else {
  109398. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  109399. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  109400. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  109401. }
  109402. },
  109403. enumerable: true,
  109404. configurable: true
  109405. });
  109406. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  109407. /**
  109408. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  109409. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  109410. * Recommended to be keep at 1.0 except for special cases.
  109411. */
  109412. get: function () {
  109413. return this._fovMultiplier;
  109414. },
  109415. set: function (value) {
  109416. if (isNaN(value)) {
  109417. value = 1.0;
  109418. }
  109419. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  109420. },
  109421. enumerable: true,
  109422. configurable: true
  109423. });
  109424. /**
  109425. * Attaches a new image processing configuration to the PBR Material.
  109426. * @param configuration (if null the scene configuration will be use)
  109427. */
  109428. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  109429. var _this = this;
  109430. if (configuration === this._imageProcessingConfiguration) {
  109431. return;
  109432. }
  109433. // Detaches observer.
  109434. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  109435. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  109436. }
  109437. // Pick the scene configuration if needed.
  109438. if (!configuration) {
  109439. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  109440. }
  109441. else {
  109442. this._imageProcessingConfiguration = configuration;
  109443. }
  109444. // Attaches observer.
  109445. if (this._imageProcessingConfiguration) {
  109446. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  109447. _this._computePrimaryColorFromPerceptualColor();
  109448. _this._markAllSubMeshesAsImageProcessingDirty();
  109449. });
  109450. }
  109451. };
  109452. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  109453. /**
  109454. * Gets the image processing configuration used either in this material.
  109455. */
  109456. get: function () {
  109457. return this._imageProcessingConfiguration;
  109458. },
  109459. /**
  109460. * Sets the Default image processing configuration used either in the this material.
  109461. *
  109462. * If sets to null, the scene one is in use.
  109463. */
  109464. set: function (value) {
  109465. this._attachImageProcessingConfiguration(value);
  109466. // Ensure the effect will be rebuilt.
  109467. this._markAllSubMeshesAsTexturesDirty();
  109468. },
  109469. enumerable: true,
  109470. configurable: true
  109471. });
  109472. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  109473. /**
  109474. * Gets wether the color curves effect is enabled.
  109475. */
  109476. get: function () {
  109477. return this.imageProcessingConfiguration.colorCurvesEnabled;
  109478. },
  109479. /**
  109480. * Sets wether the color curves effect is enabled.
  109481. */
  109482. set: function (value) {
  109483. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  109484. },
  109485. enumerable: true,
  109486. configurable: true
  109487. });
  109488. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  109489. /**
  109490. * Gets wether the color grading effect is enabled.
  109491. */
  109492. get: function () {
  109493. return this.imageProcessingConfiguration.colorGradingEnabled;
  109494. },
  109495. /**
  109496. * Gets wether the color grading effect is enabled.
  109497. */
  109498. set: function (value) {
  109499. this.imageProcessingConfiguration.colorGradingEnabled = value;
  109500. },
  109501. enumerable: true,
  109502. configurable: true
  109503. });
  109504. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  109505. /**
  109506. * Gets wether tonemapping is enabled or not.
  109507. */
  109508. get: function () {
  109509. return this._imageProcessingConfiguration.toneMappingEnabled;
  109510. },
  109511. /**
  109512. * Sets wether tonemapping is enabled or not
  109513. */
  109514. set: function (value) {
  109515. this._imageProcessingConfiguration.toneMappingEnabled = value;
  109516. },
  109517. enumerable: true,
  109518. configurable: true
  109519. });
  109520. ;
  109521. ;
  109522. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  109523. /**
  109524. * The camera exposure used on this material.
  109525. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  109526. * This corresponds to a photographic exposure.
  109527. */
  109528. get: function () {
  109529. return this._imageProcessingConfiguration.exposure;
  109530. },
  109531. /**
  109532. * The camera exposure used on this material.
  109533. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  109534. * This corresponds to a photographic exposure.
  109535. */
  109536. set: function (value) {
  109537. this._imageProcessingConfiguration.exposure = value;
  109538. },
  109539. enumerable: true,
  109540. configurable: true
  109541. });
  109542. ;
  109543. ;
  109544. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  109545. /**
  109546. * Gets The camera contrast used on this material.
  109547. */
  109548. get: function () {
  109549. return this._imageProcessingConfiguration.contrast;
  109550. },
  109551. /**
  109552. * Sets The camera contrast used on this material.
  109553. */
  109554. set: function (value) {
  109555. this._imageProcessingConfiguration.contrast = value;
  109556. },
  109557. enumerable: true,
  109558. configurable: true
  109559. });
  109560. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  109561. /**
  109562. * Gets the Color Grading 2D Lookup Texture.
  109563. */
  109564. get: function () {
  109565. return this._imageProcessingConfiguration.colorGradingTexture;
  109566. },
  109567. /**
  109568. * Sets the Color Grading 2D Lookup Texture.
  109569. */
  109570. set: function (value) {
  109571. this.imageProcessingConfiguration.colorGradingTexture = value;
  109572. },
  109573. enumerable: true,
  109574. configurable: true
  109575. });
  109576. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  109577. /**
  109578. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  109579. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  109580. * 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;
  109581. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  109582. */
  109583. get: function () {
  109584. return this.imageProcessingConfiguration.colorCurves;
  109585. },
  109586. /**
  109587. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  109588. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  109589. * 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;
  109590. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  109591. */
  109592. set: function (value) {
  109593. this.imageProcessingConfiguration.colorCurves = value;
  109594. },
  109595. enumerable: true,
  109596. configurable: true
  109597. });
  109598. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  109599. /**
  109600. * Gets a boolean indicating that current material needs to register RTT
  109601. */
  109602. get: function () {
  109603. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  109604. return true;
  109605. }
  109606. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  109607. return true;
  109608. }
  109609. return false;
  109610. },
  109611. enumerable: true,
  109612. configurable: true
  109613. });
  109614. /**
  109615. * The entire material has been created in order to prevent overdraw.
  109616. * @returns false
  109617. */
  109618. BackgroundMaterial.prototype.needAlphaTesting = function () {
  109619. return true;
  109620. };
  109621. /**
  109622. * The entire material has been created in order to prevent overdraw.
  109623. * @returns true if blending is enable
  109624. */
  109625. BackgroundMaterial.prototype.needAlphaBlending = function () {
  109626. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  109627. };
  109628. /**
  109629. * Checks wether the material is ready to be rendered for a given mesh.
  109630. * @param mesh The mesh to render
  109631. * @param subMesh The submesh to check against
  109632. * @param useInstances Specify wether or not the material is used with instances
  109633. * @returns true if all the dependencies are ready (Textures, Effects...)
  109634. */
  109635. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  109636. var _this = this;
  109637. if (useInstances === void 0) { useInstances = false; }
  109638. if (subMesh.effect && this.isFrozen) {
  109639. if (this._wasPreviouslyReady) {
  109640. return true;
  109641. }
  109642. }
  109643. if (!subMesh._materialDefines) {
  109644. subMesh._materialDefines = new BackgroundMaterialDefines();
  109645. }
  109646. var scene = this.getScene();
  109647. var defines = subMesh._materialDefines;
  109648. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  109649. if (defines._renderId === scene.getRenderId()) {
  109650. return true;
  109651. }
  109652. }
  109653. var engine = scene.getEngine();
  109654. // Lights
  109655. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  109656. defines._needNormals = true;
  109657. // Textures
  109658. if (defines._areTexturesDirty) {
  109659. defines._needUVs = false;
  109660. if (scene.texturesEnabled) {
  109661. if (scene.getEngine().getCaps().textureLOD) {
  109662. defines.TEXTURELODSUPPORT = true;
  109663. }
  109664. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  109665. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  109666. return false;
  109667. }
  109668. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  109669. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  109670. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  109671. defines.OPACITYFRESNEL = this._opacityFresnel;
  109672. }
  109673. else {
  109674. defines.DIFFUSE = false;
  109675. defines.DIFFUSEHASALPHA = false;
  109676. defines.GAMMADIFFUSE = false;
  109677. defines.OPACITYFRESNEL = false;
  109678. }
  109679. var reflectionTexture = this._reflectionTexture;
  109680. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  109681. if (!reflectionTexture.isReadyOrNotBlocking()) {
  109682. return false;
  109683. }
  109684. defines.REFLECTION = true;
  109685. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  109686. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  109687. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  109688. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  109689. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  109690. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  109691. defines.REFLECTIONBGR = this.switchToBGR;
  109692. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  109693. defines.INVERTCUBICMAP = true;
  109694. }
  109695. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  109696. switch (reflectionTexture.coordinatesMode) {
  109697. case BABYLON.Texture.EXPLICIT_MODE:
  109698. defines.REFLECTIONMAP_EXPLICIT = true;
  109699. break;
  109700. case BABYLON.Texture.PLANAR_MODE:
  109701. defines.REFLECTIONMAP_PLANAR = true;
  109702. break;
  109703. case BABYLON.Texture.PROJECTION_MODE:
  109704. defines.REFLECTIONMAP_PROJECTION = true;
  109705. break;
  109706. case BABYLON.Texture.SKYBOX_MODE:
  109707. defines.REFLECTIONMAP_SKYBOX = true;
  109708. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  109709. break;
  109710. case BABYLON.Texture.SPHERICAL_MODE:
  109711. defines.REFLECTIONMAP_SPHERICAL = true;
  109712. break;
  109713. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  109714. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  109715. break;
  109716. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  109717. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  109718. break;
  109719. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  109720. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  109721. break;
  109722. case BABYLON.Texture.CUBIC_MODE:
  109723. case BABYLON.Texture.INVCUBIC_MODE:
  109724. default:
  109725. defines.REFLECTIONMAP_CUBIC = true;
  109726. break;
  109727. }
  109728. if (this.reflectionFresnel) {
  109729. defines.REFLECTIONFRESNEL = true;
  109730. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  109731. this._reflectionControls.x = this.reflectionAmount;
  109732. this._reflectionControls.y = this.reflectionReflectance0;
  109733. this._reflectionControls.z = this.reflectionReflectance90;
  109734. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  109735. }
  109736. else {
  109737. defines.REFLECTIONFRESNEL = false;
  109738. defines.REFLECTIONFALLOFF = false;
  109739. }
  109740. }
  109741. else {
  109742. defines.REFLECTION = false;
  109743. defines.REFLECTIONFRESNEL = false;
  109744. defines.REFLECTIONFALLOFF = false;
  109745. defines.REFLECTIONBLUR = false;
  109746. defines.REFLECTIONMAP_3D = false;
  109747. defines.REFLECTIONMAP_SPHERICAL = false;
  109748. defines.REFLECTIONMAP_PLANAR = false;
  109749. defines.REFLECTIONMAP_CUBIC = false;
  109750. defines.REFLECTIONMAP_PROJECTION = false;
  109751. defines.REFLECTIONMAP_SKYBOX = false;
  109752. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  109753. defines.REFLECTIONMAP_EXPLICIT = false;
  109754. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  109755. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  109756. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  109757. defines.INVERTCUBICMAP = false;
  109758. defines.REFLECTIONMAP_OPPOSITEZ = false;
  109759. defines.LODINREFLECTIONALPHA = false;
  109760. defines.GAMMAREFLECTION = false;
  109761. defines.RGBDREFLECTION = false;
  109762. }
  109763. }
  109764. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  109765. defines.USERGBCOLOR = this._useRGBColor;
  109766. defines.NOISE = this._enableNoise;
  109767. }
  109768. if (defines._areLightsDirty) {
  109769. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  109770. }
  109771. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  109772. if (!this._imageProcessingConfiguration.isReady()) {
  109773. return false;
  109774. }
  109775. this._imageProcessingConfiguration.prepareDefines(defines);
  109776. }
  109777. // Misc.
  109778. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  109779. // Values that need to be evaluated on every frame
  109780. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  109781. // Attribs
  109782. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  109783. if (mesh) {
  109784. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  109785. mesh.createNormals(true);
  109786. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  109787. }
  109788. }
  109789. }
  109790. // Get correct effect
  109791. if (defines.isDirty) {
  109792. defines.markAsProcessed();
  109793. scene.resetCachedMaterial();
  109794. // Fallbacks
  109795. var fallbacks = new BABYLON.EffectFallbacks();
  109796. if (defines.FOG) {
  109797. fallbacks.addFallback(0, "FOG");
  109798. }
  109799. if (defines.POINTSIZE) {
  109800. fallbacks.addFallback(1, "POINTSIZE");
  109801. }
  109802. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  109803. if (defines.NUM_BONE_INFLUENCERS > 0) {
  109804. fallbacks.addCPUSkinningFallback(0, mesh);
  109805. }
  109806. //Attributes
  109807. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109808. if (defines.NORMAL) {
  109809. attribs.push(BABYLON.VertexBuffer.NormalKind);
  109810. }
  109811. if (defines.UV1) {
  109812. attribs.push(BABYLON.VertexBuffer.UVKind);
  109813. }
  109814. if (defines.UV2) {
  109815. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109816. }
  109817. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  109818. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  109819. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  109820. "vFogInfos", "vFogColor", "pointSize",
  109821. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  109822. "vPrimaryColor", "vPrimaryColorShadow",
  109823. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  109824. "shadowLevel", "alpha",
  109825. "vBackgroundCenter", "vReflectionControl",
  109826. "vDiffuseInfos", "diffuseMatrix",
  109827. ];
  109828. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  109829. var uniformBuffers = ["Material", "Scene"];
  109830. if (BABYLON.ImageProcessingConfiguration) {
  109831. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  109832. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  109833. }
  109834. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  109835. uniformsNames: uniforms,
  109836. uniformBuffersNames: uniformBuffers,
  109837. samplers: samplers,
  109838. defines: defines,
  109839. maxSimultaneousLights: this._maxSimultaneousLights
  109840. });
  109841. var onCompiled = function (effect) {
  109842. if (_this.onCompiled) {
  109843. _this.onCompiled(effect);
  109844. }
  109845. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  109846. };
  109847. var join = defines.toString();
  109848. subMesh.setEffect(scene.getEngine().createEffect("background", {
  109849. attributes: attribs,
  109850. uniformsNames: uniforms,
  109851. uniformBuffersNames: uniformBuffers,
  109852. samplers: samplers,
  109853. defines: join,
  109854. fallbacks: fallbacks,
  109855. onCompiled: onCompiled,
  109856. onError: this.onError,
  109857. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  109858. }, engine), defines);
  109859. this.buildUniformLayout();
  109860. }
  109861. if (!subMesh.effect || !subMesh.effect.isReady()) {
  109862. return false;
  109863. }
  109864. defines._renderId = scene.getRenderId();
  109865. this._wasPreviouslyReady = true;
  109866. return true;
  109867. };
  109868. /**
  109869. * Compute the primary color according to the chosen perceptual color.
  109870. */
  109871. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  109872. if (!this.__perceptualColor) {
  109873. return;
  109874. }
  109875. this._primaryColor.copyFrom(this.__perceptualColor);
  109876. // Revert gamma space.
  109877. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  109878. // Revert image processing configuration.
  109879. if (this._imageProcessingConfiguration) {
  109880. // Revert Exposure.
  109881. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  109882. }
  109883. this._computePrimaryColors();
  109884. };
  109885. /**
  109886. * Compute the highlights and shadow colors according to their chosen levels.
  109887. */
  109888. BackgroundMaterial.prototype._computePrimaryColors = function () {
  109889. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  109890. return;
  109891. }
  109892. // Find the highlight color based on the configuration.
  109893. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  109894. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  109895. // Find the shadow color based on the configuration.
  109896. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  109897. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  109898. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  109899. };
  109900. /**
  109901. * Build the uniform buffer used in the material.
  109902. */
  109903. BackgroundMaterial.prototype.buildUniformLayout = function () {
  109904. // Order is important !
  109905. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  109906. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  109907. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  109908. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  109909. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  109910. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  109911. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  109912. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  109913. this._uniformBuffer.addUniform("pointSize", 1);
  109914. this._uniformBuffer.addUniform("shadowLevel", 1);
  109915. this._uniformBuffer.addUniform("alpha", 1);
  109916. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  109917. this._uniformBuffer.addUniform("vReflectionControl", 4);
  109918. this._uniformBuffer.create();
  109919. };
  109920. /**
  109921. * Unbind the material.
  109922. */
  109923. BackgroundMaterial.prototype.unbind = function () {
  109924. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  109925. this._uniformBuffer.setTexture("diffuseSampler", null);
  109926. }
  109927. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  109928. this._uniformBuffer.setTexture("reflectionSampler", null);
  109929. }
  109930. _super.prototype.unbind.call(this);
  109931. };
  109932. /**
  109933. * Bind only the world matrix to the material.
  109934. * @param world The world matrix to bind.
  109935. */
  109936. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  109937. this._activeEffect.setMatrix("world", world);
  109938. };
  109939. /**
  109940. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  109941. * @param world The world matrix to bind.
  109942. * @param subMesh The submesh to bind for.
  109943. */
  109944. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  109945. var scene = this.getScene();
  109946. var defines = subMesh._materialDefines;
  109947. if (!defines) {
  109948. return;
  109949. }
  109950. var effect = subMesh.effect;
  109951. if (!effect) {
  109952. return;
  109953. }
  109954. this._activeEffect = effect;
  109955. // Matrices
  109956. this.bindOnlyWorldMatrix(world);
  109957. // Bones
  109958. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  109959. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  109960. if (mustRebind) {
  109961. this._uniformBuffer.bindToEffect(effect, "Material");
  109962. this.bindViewProjection(effect);
  109963. var reflectionTexture = this._reflectionTexture;
  109964. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  109965. // Texture uniforms
  109966. if (scene.texturesEnabled) {
  109967. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  109968. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  109969. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  109970. }
  109971. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  109972. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  109973. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  109974. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  109975. }
  109976. }
  109977. if (this.shadowLevel > 0) {
  109978. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  109979. }
  109980. this._uniformBuffer.updateFloat("alpha", this.alpha);
  109981. // Point size
  109982. if (this.pointsCloud) {
  109983. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  109984. }
  109985. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  109986. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  109987. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  109988. }
  109989. else {
  109990. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  109991. }
  109992. }
  109993. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  109994. // Textures
  109995. if (scene.texturesEnabled) {
  109996. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  109997. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  109998. }
  109999. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  110000. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  110001. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110002. }
  110003. else if (!defines.REFLECTIONBLUR) {
  110004. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  110005. }
  110006. else {
  110007. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  110008. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  110009. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  110010. }
  110011. if (defines.REFLECTIONFRESNEL) {
  110012. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  110013. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  110014. }
  110015. }
  110016. }
  110017. // Clip plane
  110018. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  110019. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  110020. }
  110021. if (mustRebind || !this.isFrozen) {
  110022. if (scene.lightsEnabled) {
  110023. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  110024. }
  110025. // View
  110026. this.bindView(effect);
  110027. // Fog
  110028. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  110029. // image processing
  110030. if (this._imageProcessingConfiguration) {
  110031. this._imageProcessingConfiguration.bind(this._activeEffect);
  110032. }
  110033. }
  110034. this._uniformBuffer.update();
  110035. this._afterBind(mesh, this._activeEffect);
  110036. };
  110037. /**
  110038. * Dispose the material.
  110039. * @param forceDisposeEffect Force disposal of the associated effect.
  110040. * @param forceDisposeTextures Force disposal of the associated textures.
  110041. */
  110042. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  110043. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  110044. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  110045. if (forceDisposeTextures) {
  110046. if (this.diffuseTexture) {
  110047. this.diffuseTexture.dispose();
  110048. }
  110049. if (this.reflectionTexture) {
  110050. this.reflectionTexture.dispose();
  110051. }
  110052. }
  110053. this._renderTargets.dispose();
  110054. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  110055. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  110056. }
  110057. _super.prototype.dispose.call(this, forceDisposeEffect);
  110058. };
  110059. /**
  110060. * Clones the material.
  110061. * @param name The cloned name.
  110062. * @returns The cloned material.
  110063. */
  110064. BackgroundMaterial.prototype.clone = function (name) {
  110065. var _this = this;
  110066. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  110067. };
  110068. /**
  110069. * Serializes the current material to its JSON representation.
  110070. * @returns The JSON representation.
  110071. */
  110072. BackgroundMaterial.prototype.serialize = function () {
  110073. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110074. serializationObject.customType = "BABYLON.BackgroundMaterial";
  110075. return serializationObject;
  110076. };
  110077. /**
  110078. * Gets the class name of the material
  110079. * @returns "BackgroundMaterial"
  110080. */
  110081. BackgroundMaterial.prototype.getClassName = function () {
  110082. return "BackgroundMaterial";
  110083. };
  110084. /**
  110085. * Parse a JSON input to create back a background material.
  110086. * @param source The JSON data to parse
  110087. * @param scene The scene to create the parsed material in
  110088. * @param rootUrl The root url of the assets the material depends upon
  110089. * @returns the instantiated BackgroundMaterial.
  110090. */
  110091. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  110092. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  110093. };
  110094. /**
  110095. * Standard reflectance value at parallel view angle.
  110096. */
  110097. BackgroundMaterial.StandardReflectance0 = 0.05;
  110098. /**
  110099. * Standard reflectance value at grazing angle.
  110100. */
  110101. BackgroundMaterial.StandardReflectance90 = 0.5;
  110102. __decorate([
  110103. BABYLON.serializeAsColor3()
  110104. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  110105. __decorate([
  110106. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110107. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  110108. __decorate([
  110109. BABYLON.serializeAsColor3()
  110110. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  110111. __decorate([
  110112. BABYLON.serialize()
  110113. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  110114. __decorate([
  110115. BABYLON.serialize()
  110116. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  110117. __decorate([
  110118. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  110119. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  110120. __decorate([
  110121. BABYLON.serializeAsTexture()
  110122. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  110123. __decorate([
  110124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110125. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  110126. __decorate([
  110127. BABYLON.serialize()
  110128. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  110129. __decorate([
  110130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110131. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  110132. __decorate([
  110133. BABYLON.serializeAsTexture()
  110134. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  110135. __decorate([
  110136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110137. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  110138. __decorate([
  110139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110140. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  110141. __decorate([
  110142. BABYLON.serialize()
  110143. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  110144. __decorate([
  110145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110146. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  110147. __decorate([
  110148. BABYLON.serializeAsVector3()
  110149. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  110150. __decorate([
  110151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110152. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  110153. __decorate([
  110154. BABYLON.serialize()
  110155. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  110156. __decorate([
  110157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110158. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  110159. __decorate([
  110160. BABYLON.serialize()
  110161. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  110162. __decorate([
  110163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110164. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  110165. __decorate([
  110166. BABYLON.serialize()
  110167. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  110168. __decorate([
  110169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110170. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  110171. __decorate([
  110172. BABYLON.serialize()
  110173. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  110174. __decorate([
  110175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110176. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  110177. __decorate([
  110178. BABYLON.serialize()
  110179. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  110180. __decorate([
  110181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110182. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  110183. __decorate([
  110184. BABYLON.serialize()
  110185. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  110186. __decorate([
  110187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110188. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  110189. __decorate([
  110190. BABYLON.serialize()
  110191. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  110192. __decorate([
  110193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110194. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  110195. __decorate([
  110196. BABYLON.serialize()
  110197. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  110198. __decorate([
  110199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110200. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  110201. __decorate([
  110202. BABYLON.serialize()
  110203. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  110204. __decorate([
  110205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  110206. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  110207. __decorate([
  110208. BABYLON.serializeAsImageProcessingConfiguration()
  110209. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  110210. return BackgroundMaterial;
  110211. }(BABYLON.PushMaterial));
  110212. BABYLON.BackgroundMaterial = BackgroundMaterial;
  110213. })(BABYLON || (BABYLON = {}));
  110214. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  110215. var __assign = (this && this.__assign) || function () {
  110216. __assign = Object.assign || function(t) {
  110217. for (var s, i = 1, n = arguments.length; i < n; i++) {
  110218. s = arguments[i];
  110219. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  110220. t[p] = s[p];
  110221. }
  110222. return t;
  110223. };
  110224. return __assign.apply(this, arguments);
  110225. };
  110226. var BABYLON;
  110227. (function (BABYLON) {
  110228. /**
  110229. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  110230. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  110231. * It also helps with the default setup of your imageProcessing configuration.
  110232. */
  110233. var EnvironmentHelper = /** @class */ (function () {
  110234. /**
  110235. * constructor
  110236. * @param options
  110237. * @param scene The scene to add the material to
  110238. */
  110239. function EnvironmentHelper(options, scene) {
  110240. var _this = this;
  110241. this._errorHandler = function (message, exception) {
  110242. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  110243. };
  110244. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  110245. this._scene = scene;
  110246. this.onErrorObservable = new BABYLON.Observable();
  110247. this._setupBackground();
  110248. this._setupImageProcessing();
  110249. }
  110250. /**
  110251. * Creates the default options for the helper.
  110252. */
  110253. EnvironmentHelper._getDefaultOptions = function () {
  110254. return {
  110255. createGround: true,
  110256. groundSize: 15,
  110257. groundTexture: this._groundTextureCDNUrl,
  110258. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110259. groundOpacity: 0.9,
  110260. enableGroundShadow: true,
  110261. groundShadowLevel: 0.5,
  110262. enableGroundMirror: false,
  110263. groundMirrorSizeRatio: 0.3,
  110264. groundMirrorBlurKernel: 64,
  110265. groundMirrorAmount: 1,
  110266. groundMirrorFresnelWeight: 1,
  110267. groundMirrorFallOffDistance: 0,
  110268. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  110269. groundYBias: 0.00001,
  110270. createSkybox: true,
  110271. skyboxSize: 20,
  110272. skyboxTexture: this._skyboxTextureCDNUrl,
  110273. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  110274. backgroundYRotation: 0,
  110275. sizeAuto: true,
  110276. rootPosition: BABYLON.Vector3.Zero(),
  110277. setupImageProcessing: true,
  110278. environmentTexture: this._environmentTextureCDNUrl,
  110279. cameraExposure: 0.8,
  110280. cameraContrast: 1.2,
  110281. toneMappingEnabled: true,
  110282. };
  110283. };
  110284. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  110285. /**
  110286. * Gets the root mesh created by the helper.
  110287. */
  110288. get: function () {
  110289. return this._rootMesh;
  110290. },
  110291. enumerable: true,
  110292. configurable: true
  110293. });
  110294. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  110295. /**
  110296. * Gets the skybox created by the helper.
  110297. */
  110298. get: function () {
  110299. return this._skybox;
  110300. },
  110301. enumerable: true,
  110302. configurable: true
  110303. });
  110304. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  110305. /**
  110306. * Gets the skybox texture created by the helper.
  110307. */
  110308. get: function () {
  110309. return this._skyboxTexture;
  110310. },
  110311. enumerable: true,
  110312. configurable: true
  110313. });
  110314. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  110315. /**
  110316. * Gets the skybox material created by the helper.
  110317. */
  110318. get: function () {
  110319. return this._skyboxMaterial;
  110320. },
  110321. enumerable: true,
  110322. configurable: true
  110323. });
  110324. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  110325. /**
  110326. * Gets the ground mesh created by the helper.
  110327. */
  110328. get: function () {
  110329. return this._ground;
  110330. },
  110331. enumerable: true,
  110332. configurable: true
  110333. });
  110334. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  110335. /**
  110336. * Gets the ground texture created by the helper.
  110337. */
  110338. get: function () {
  110339. return this._groundTexture;
  110340. },
  110341. enumerable: true,
  110342. configurable: true
  110343. });
  110344. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  110345. /**
  110346. * Gets the ground mirror created by the helper.
  110347. */
  110348. get: function () {
  110349. return this._groundMirror;
  110350. },
  110351. enumerable: true,
  110352. configurable: true
  110353. });
  110354. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  110355. /**
  110356. * Gets the ground mirror render list to helps pushing the meshes
  110357. * you wish in the ground reflection.
  110358. */
  110359. get: function () {
  110360. if (this._groundMirror) {
  110361. return this._groundMirror.renderList;
  110362. }
  110363. return null;
  110364. },
  110365. enumerable: true,
  110366. configurable: true
  110367. });
  110368. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  110369. /**
  110370. * Gets the ground material created by the helper.
  110371. */
  110372. get: function () {
  110373. return this._groundMaterial;
  110374. },
  110375. enumerable: true,
  110376. configurable: true
  110377. });
  110378. /**
  110379. * Updates the background according to the new options
  110380. * @param options
  110381. */
  110382. EnvironmentHelper.prototype.updateOptions = function (options) {
  110383. var newOptions = __assign({}, this._options, options);
  110384. if (this._ground && !newOptions.createGround) {
  110385. this._ground.dispose();
  110386. this._ground = null;
  110387. }
  110388. if (this._groundMaterial && !newOptions.createGround) {
  110389. this._groundMaterial.dispose();
  110390. this._groundMaterial = null;
  110391. }
  110392. if (this._groundTexture) {
  110393. if (this._options.groundTexture != newOptions.groundTexture) {
  110394. this._groundTexture.dispose();
  110395. this._groundTexture = null;
  110396. }
  110397. }
  110398. if (this._skybox && !newOptions.createSkybox) {
  110399. this._skybox.dispose();
  110400. this._skybox = null;
  110401. }
  110402. if (this._skyboxMaterial && !newOptions.createSkybox) {
  110403. this._skyboxMaterial.dispose();
  110404. this._skyboxMaterial = null;
  110405. }
  110406. if (this._skyboxTexture) {
  110407. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  110408. this._skyboxTexture.dispose();
  110409. this._skyboxTexture = null;
  110410. }
  110411. }
  110412. if (this._groundMirror && !newOptions.enableGroundMirror) {
  110413. this._groundMirror.dispose();
  110414. this._groundMirror = null;
  110415. }
  110416. if (this._scene.environmentTexture) {
  110417. if (this._options.environmentTexture != newOptions.environmentTexture) {
  110418. this._scene.environmentTexture.dispose();
  110419. }
  110420. }
  110421. this._options = newOptions;
  110422. this._setupBackground();
  110423. this._setupImageProcessing();
  110424. };
  110425. /**
  110426. * Sets the primary color of all the available elements.
  110427. * @param color the main color to affect to the ground and the background
  110428. */
  110429. EnvironmentHelper.prototype.setMainColor = function (color) {
  110430. if (this.groundMaterial) {
  110431. this.groundMaterial.primaryColor = color;
  110432. }
  110433. if (this.skyboxMaterial) {
  110434. this.skyboxMaterial.primaryColor = color;
  110435. }
  110436. if (this.groundMirror) {
  110437. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  110438. }
  110439. };
  110440. /**
  110441. * Setup the image processing according to the specified options.
  110442. */
  110443. EnvironmentHelper.prototype._setupImageProcessing = function () {
  110444. if (this._options.setupImageProcessing) {
  110445. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  110446. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  110447. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  110448. this._setupEnvironmentTexture();
  110449. }
  110450. };
  110451. /**
  110452. * Setup the environment texture according to the specified options.
  110453. */
  110454. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  110455. if (this._scene.environmentTexture) {
  110456. return;
  110457. }
  110458. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  110459. this._scene.environmentTexture = this._options.environmentTexture;
  110460. return;
  110461. }
  110462. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  110463. this._scene.environmentTexture = environmentTexture;
  110464. };
  110465. /**
  110466. * Setup the background according to the specified options.
  110467. */
  110468. EnvironmentHelper.prototype._setupBackground = function () {
  110469. if (!this._rootMesh) {
  110470. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  110471. }
  110472. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  110473. var sceneSize = this._getSceneSize();
  110474. if (this._options.createGround) {
  110475. this._setupGround(sceneSize);
  110476. this._setupGroundMaterial();
  110477. this._setupGroundDiffuseTexture();
  110478. if (this._options.enableGroundMirror) {
  110479. this._setupGroundMirrorTexture(sceneSize);
  110480. }
  110481. this._setupMirrorInGroundMaterial();
  110482. }
  110483. if (this._options.createSkybox) {
  110484. this._setupSkybox(sceneSize);
  110485. this._setupSkyboxMaterial();
  110486. this._setupSkyboxReflectionTexture();
  110487. }
  110488. this._rootMesh.position.x = sceneSize.rootPosition.x;
  110489. this._rootMesh.position.z = sceneSize.rootPosition.z;
  110490. this._rootMesh.position.y = sceneSize.rootPosition.y;
  110491. };
  110492. /**
  110493. * Get the scene sizes according to the setup.
  110494. */
  110495. EnvironmentHelper.prototype._getSceneSize = function () {
  110496. var _this = this;
  110497. var groundSize = this._options.groundSize;
  110498. var skyboxSize = this._options.skyboxSize;
  110499. var rootPosition = this._options.rootPosition;
  110500. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  110501. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  110502. }
  110503. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  110504. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  110505. });
  110506. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  110507. if (this._options.sizeAuto) {
  110508. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  110509. this._scene.activeCamera.upperRadiusLimit) {
  110510. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  110511. skyboxSize = groundSize;
  110512. }
  110513. var sceneDiagonalLenght = sceneDiagonal.length();
  110514. if (sceneDiagonalLenght > groundSize) {
  110515. groundSize = sceneDiagonalLenght * 2;
  110516. skyboxSize = groundSize;
  110517. }
  110518. // 10 % bigger.
  110519. groundSize *= 1.1;
  110520. skyboxSize *= 1.5;
  110521. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  110522. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  110523. }
  110524. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  110525. };
  110526. /**
  110527. * Setup the ground according to the specified options.
  110528. */
  110529. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  110530. var _this = this;
  110531. if (!this._ground || this._ground.isDisposed()) {
  110532. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  110533. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  110534. this._ground.parent = this._rootMesh;
  110535. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  110536. }
  110537. this._ground.receiveShadows = this._options.enableGroundShadow;
  110538. };
  110539. /**
  110540. * Setup the ground material according to the specified options.
  110541. */
  110542. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  110543. if (!this._groundMaterial) {
  110544. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  110545. }
  110546. this._groundMaterial.alpha = this._options.groundOpacity;
  110547. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  110548. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  110549. this._groundMaterial.primaryColor = this._options.groundColor;
  110550. this._groundMaterial.useRGBColor = false;
  110551. this._groundMaterial.enableNoise = true;
  110552. if (this._ground) {
  110553. this._ground.material = this._groundMaterial;
  110554. }
  110555. };
  110556. /**
  110557. * Setup the ground diffuse texture according to the specified options.
  110558. */
  110559. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  110560. if (!this._groundMaterial) {
  110561. return;
  110562. }
  110563. if (this._groundTexture) {
  110564. return;
  110565. }
  110566. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  110567. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  110568. return;
  110569. }
  110570. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  110571. diffuseTexture.gammaSpace = false;
  110572. diffuseTexture.hasAlpha = true;
  110573. this._groundMaterial.diffuseTexture = diffuseTexture;
  110574. };
  110575. /**
  110576. * Setup the ground mirror texture according to the specified options.
  110577. */
  110578. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  110579. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110580. if (!this._groundMirror) {
  110581. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  110582. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  110583. this._groundMirror.anisotropicFilteringLevel = 1;
  110584. this._groundMirror.wrapU = wrapping;
  110585. this._groundMirror.wrapV = wrapping;
  110586. this._groundMirror.gammaSpace = false;
  110587. if (this._groundMirror.renderList) {
  110588. for (var i = 0; i < this._scene.meshes.length; i++) {
  110589. var mesh = this._scene.meshes[i];
  110590. if (mesh !== this._ground &&
  110591. mesh !== this._skybox &&
  110592. mesh !== this._rootMesh) {
  110593. this._groundMirror.renderList.push(mesh);
  110594. }
  110595. }
  110596. }
  110597. }
  110598. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  110599. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  110600. };
  110601. /**
  110602. * Setup the ground to receive the mirror texture.
  110603. */
  110604. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  110605. if (this._groundMaterial) {
  110606. this._groundMaterial.reflectionTexture = this._groundMirror;
  110607. this._groundMaterial.reflectionFresnel = true;
  110608. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  110609. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  110610. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  110611. }
  110612. };
  110613. /**
  110614. * Setup the skybox according to the specified options.
  110615. */
  110616. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  110617. var _this = this;
  110618. if (!this._skybox || this._skybox.isDisposed()) {
  110619. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  110620. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  110621. }
  110622. this._skybox.parent = this._rootMesh;
  110623. };
  110624. /**
  110625. * Setup the skybox material according to the specified options.
  110626. */
  110627. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  110628. if (!this._skybox) {
  110629. return;
  110630. }
  110631. if (!this._skyboxMaterial) {
  110632. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  110633. }
  110634. this._skyboxMaterial.useRGBColor = false;
  110635. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  110636. this._skyboxMaterial.enableNoise = true;
  110637. this._skybox.material = this._skyboxMaterial;
  110638. };
  110639. /**
  110640. * Setup the skybox reflection texture according to the specified options.
  110641. */
  110642. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  110643. if (!this._skyboxMaterial) {
  110644. return;
  110645. }
  110646. if (this._skyboxTexture) {
  110647. return;
  110648. }
  110649. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  110650. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  110651. return;
  110652. }
  110653. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  110654. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  110655. this._skyboxTexture.gammaSpace = false;
  110656. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  110657. };
  110658. /**
  110659. * Dispose all the elements created by the Helper.
  110660. */
  110661. EnvironmentHelper.prototype.dispose = function () {
  110662. if (this._groundMaterial) {
  110663. this._groundMaterial.dispose(true, true);
  110664. }
  110665. if (this._skyboxMaterial) {
  110666. this._skyboxMaterial.dispose(true, true);
  110667. }
  110668. this._rootMesh.dispose(false);
  110669. };
  110670. /**
  110671. * Default ground texture URL.
  110672. */
  110673. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  110674. /**
  110675. * Default skybox texture URL.
  110676. */
  110677. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  110678. /**
  110679. * Default environment texture URL.
  110680. */
  110681. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  110682. return EnvironmentHelper;
  110683. }());
  110684. BABYLON.EnvironmentHelper = EnvironmentHelper;
  110685. })(BABYLON || (BABYLON = {}));
  110686. //# sourceMappingURL=babylon.environmentHelper.js.map
  110687. var BABYLON;
  110688. (function (BABYLON) {
  110689. /** Internal class used to store shapes for emitters */
  110690. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  110691. function ParticleSystemSetEmitterCreationOptions() {
  110692. }
  110693. return ParticleSystemSetEmitterCreationOptions;
  110694. }());
  110695. /**
  110696. * Represents a set of particle systems working together to create a specific effect
  110697. */
  110698. var ParticleSystemSet = /** @class */ (function () {
  110699. function ParticleSystemSet() {
  110700. /**
  110701. * Gets the particle system list
  110702. */
  110703. this.systems = new Array();
  110704. }
  110705. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  110706. /**
  110707. * Gets the emitter node used with this set
  110708. */
  110709. get: function () {
  110710. return this._emitterNode;
  110711. },
  110712. enumerable: true,
  110713. configurable: true
  110714. });
  110715. /**
  110716. * Creates a new emitter mesh as a sphere
  110717. * @param options defines the options used to create the sphere
  110718. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  110719. * @param scene defines the hosting scene
  110720. */
  110721. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  110722. if (this._emitterNode) {
  110723. this._emitterNode.dispose();
  110724. }
  110725. this._emitterCreationOptions = {
  110726. kind: "Sphere",
  110727. options: options,
  110728. renderingGroupId: renderingGroupId
  110729. };
  110730. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  110731. emitterMesh.renderingGroupId = renderingGroupId;
  110732. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  110733. material.emissiveColor = options.color;
  110734. emitterMesh.material = material;
  110735. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110736. var system = _a[_i];
  110737. system.emitter = emitterMesh;
  110738. }
  110739. this._emitterNode = emitterMesh;
  110740. };
  110741. /**
  110742. * Starts all particle systems of the set
  110743. * @param emitter defines an optional mesh to use as emitter for the particle systems
  110744. */
  110745. ParticleSystemSet.prototype.start = function (emitter) {
  110746. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110747. var system = _a[_i];
  110748. if (emitter) {
  110749. system.emitter = emitter;
  110750. }
  110751. system.start();
  110752. }
  110753. };
  110754. /**
  110755. * Release all associated resources
  110756. */
  110757. ParticleSystemSet.prototype.dispose = function () {
  110758. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110759. var system = _a[_i];
  110760. system.dispose();
  110761. }
  110762. this.systems = [];
  110763. if (this._emitterNode) {
  110764. this._emitterNode.dispose();
  110765. this._emitterNode = null;
  110766. }
  110767. };
  110768. /**
  110769. * Serialize the set into a JSON compatible object
  110770. * @returns a JSON compatible representation of the set
  110771. */
  110772. ParticleSystemSet.prototype.serialize = function () {
  110773. var result = {};
  110774. result.systems = [];
  110775. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  110776. var system = _a[_i];
  110777. result.systems.push(system.serialize());
  110778. }
  110779. if (this._emitterNode) {
  110780. result.emitter = this._emitterCreationOptions;
  110781. }
  110782. return result;
  110783. };
  110784. /**
  110785. * Parse a new ParticleSystemSet from a serialized source
  110786. * @param data defines a JSON compatible representation of the set
  110787. * @param scene defines the hosting scene
  110788. * @param gpu defines if we want GPU particles or CPU particles
  110789. * @returns a new ParticleSystemSet
  110790. */
  110791. ParticleSystemSet.Parse = function (data, scene, gpu) {
  110792. if (gpu === void 0) { gpu = false; }
  110793. var result = new ParticleSystemSet();
  110794. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  110795. scene = scene || BABYLON.Engine.LastCreatedScene;
  110796. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  110797. var system = _a[_i];
  110798. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  110799. }
  110800. if (data.emitter) {
  110801. var options = data.emitter.options;
  110802. switch (data.emitter.kind) {
  110803. case "Sphere":
  110804. result.setEmitterAsSphere({
  110805. diameter: options.diameter,
  110806. segments: options.segments,
  110807. color: BABYLON.Color3.FromArray(options.color)
  110808. }, data.emitter.renderingGroupId, scene);
  110809. break;
  110810. }
  110811. }
  110812. return result;
  110813. };
  110814. return ParticleSystemSet;
  110815. }());
  110816. BABYLON.ParticleSystemSet = ParticleSystemSet;
  110817. })(BABYLON || (BABYLON = {}));
  110818. //# sourceMappingURL=babylon.particleSystemSet.js.map
  110819. var BABYLON;
  110820. (function (BABYLON) {
  110821. /**
  110822. * This class is made for on one-liner static method to help creating particle system set.
  110823. */
  110824. var ParticleHelper = /** @class */ (function () {
  110825. function ParticleHelper() {
  110826. }
  110827. /**
  110828. * Create a default particle system that you can tweak
  110829. * @param emitter defines the emitter to use
  110830. * @param capacity defines the system capacity (default is 500 particles)
  110831. * @param scene defines the hosting scene
  110832. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  110833. * @returns the new Particle system
  110834. */
  110835. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  110836. if (capacity === void 0) { capacity = 500; }
  110837. if (useGPU === void 0) { useGPU = false; }
  110838. var system;
  110839. if (useGPU) {
  110840. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  110841. }
  110842. else {
  110843. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  110844. }
  110845. system.emitter = emitter;
  110846. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  110847. system.createConeEmitter(0.1, Math.PI / 4);
  110848. // Particle color
  110849. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  110850. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  110851. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  110852. // Particle Size
  110853. system.minSize = 0.1;
  110854. system.maxSize = 0.1;
  110855. // Emission speed
  110856. system.minEmitPower = 2;
  110857. system.maxEmitPower = 2;
  110858. // Update speed
  110859. system.updateSpeed = 1 / 60;
  110860. system.emitRate = 30;
  110861. return system;
  110862. };
  110863. /**
  110864. * This is the main static method (one-liner) of this helper to create different particle systems
  110865. * @param type This string represents the type to the particle system to create
  110866. * @param scene The scene where the particle system should live
  110867. * @param gpu If the system will use gpu
  110868. * @returns the ParticleSystemSet created
  110869. */
  110870. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  110871. if (gpu === void 0) { gpu = false; }
  110872. if (!scene) {
  110873. scene = BABYLON.Engine.LastCreatedScene;
  110874. ;
  110875. }
  110876. var token = {};
  110877. scene._addPendingData(token);
  110878. return new Promise(function (resolve, reject) {
  110879. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  110880. scene._removePendingData(token);
  110881. return reject("Particle system with GPU is not supported.");
  110882. }
  110883. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  110884. scene._removePendingData(token);
  110885. var newData = JSON.parse(data.toString());
  110886. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  110887. }, undefined, undefined, undefined, function (req, exception) {
  110888. scene._removePendingData(token);
  110889. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  110890. });
  110891. });
  110892. };
  110893. /**
  110894. * Static function used to export a particle system to a ParticleSystemSet variable.
  110895. * Please note that the emitter shape is not exported
  110896. * @param system defines the particle systems to export
  110897. */
  110898. ParticleHelper.ExportSet = function (systems) {
  110899. var set = new BABYLON.ParticleSystemSet();
  110900. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  110901. var system = systems_1[_i];
  110902. set.systems.push(system);
  110903. }
  110904. return set;
  110905. };
  110906. /**
  110907. * Gets or sets base Assets URL
  110908. */
  110909. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  110910. return ParticleHelper;
  110911. }());
  110912. BABYLON.ParticleHelper = ParticleHelper;
  110913. })(BABYLON || (BABYLON = {}));
  110914. //# sourceMappingURL=babylon.particleHelper.js.map
  110915. var BABYLON;
  110916. (function (BABYLON) {
  110917. /**
  110918. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  110919. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  110920. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  110921. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  110922. */
  110923. var VideoDome = /** @class */ (function (_super) {
  110924. __extends(VideoDome, _super);
  110925. /**
  110926. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  110927. * @param name Element's name, child elements will append suffixes for their own names.
  110928. * @param urlsOrVideo defines the url(s) or the video element to use
  110929. * @param options An object containing optional or exposed sub element properties
  110930. */
  110931. function VideoDome(name, urlsOrVideo, options, scene) {
  110932. var _this = _super.call(this, name, scene) || this;
  110933. _this._useDirectMapping = false;
  110934. // set defaults and manage values
  110935. name = name || "videoDome";
  110936. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  110937. options.clickToPlay = Boolean(options.clickToPlay);
  110938. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  110939. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  110940. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  110941. if (options.useDirectMapping === undefined) {
  110942. _this._useDirectMapping = true;
  110943. }
  110944. else {
  110945. _this._useDirectMapping = options.useDirectMapping;
  110946. }
  110947. _this._setReady(false);
  110948. // create
  110949. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  110950. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  110951. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  110952. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  110953. texture.onLoadObservable.addOnce(function () {
  110954. _this._setReady(true);
  110955. });
  110956. // configure material
  110957. material.useEquirectangularFOV = true;
  110958. material.fovMultiplier = 1.0;
  110959. material.opacityFresnel = false;
  110960. if (_this._useDirectMapping) {
  110961. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110962. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110963. material.diffuseTexture = texture;
  110964. }
  110965. else {
  110966. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  110967. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110968. material.reflectionTexture = texture;
  110969. }
  110970. // configure mesh
  110971. _this._mesh.material = material;
  110972. _this._mesh.parent = _this;
  110973. // optional configuration
  110974. if (options.clickToPlay) {
  110975. scene.onPointerUp = function () {
  110976. _this._videoTexture.video.play();
  110977. };
  110978. }
  110979. return _this;
  110980. }
  110981. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  110982. /**
  110983. * Gets the video texture being displayed on the sphere
  110984. */
  110985. get: function () {
  110986. return this._videoTexture;
  110987. },
  110988. enumerable: true,
  110989. configurable: true
  110990. });
  110991. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  110992. /**
  110993. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  110994. * Also see the options.resolution property.
  110995. */
  110996. get: function () {
  110997. return this._material.fovMultiplier;
  110998. },
  110999. set: function (value) {
  111000. this._material.fovMultiplier = value;
  111001. },
  111002. enumerable: true,
  111003. configurable: true
  111004. });
  111005. /**
  111006. * Releases resources associated with this node.
  111007. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111008. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111009. */
  111010. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111011. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111012. this._videoTexture.dispose();
  111013. this._mesh.dispose();
  111014. this._material.dispose();
  111015. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111016. };
  111017. return VideoDome;
  111018. }(BABYLON.TransformNode));
  111019. BABYLON.VideoDome = VideoDome;
  111020. })(BABYLON || (BABYLON = {}));
  111021. //# sourceMappingURL=babylon.videoDome.js.map
  111022. var BABYLON;
  111023. (function (BABYLON) {
  111024. /**
  111025. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  111026. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  111027. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  111028. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  111029. */
  111030. var PhotoDome = /** @class */ (function (_super) {
  111031. __extends(PhotoDome, _super);
  111032. /**
  111033. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  111034. * @param name Element's name, child elements will append suffixes for their own names.
  111035. * @param urlsOfPhoto defines the url of the photo to display
  111036. * @param options defines an object containing optional or exposed sub element properties
  111037. * @param onError defines a callback called when an error occured while loading the texture
  111038. */
  111039. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  111040. if (onError === void 0) { onError = null; }
  111041. var _this = _super.call(this, name, scene) || this;
  111042. _this._useDirectMapping = false;
  111043. /**
  111044. * Observable raised when an error occured while loading the 360 image
  111045. */
  111046. _this.onLoadErrorObservable = new BABYLON.Observable();
  111047. // set defaults and manage values
  111048. name = name || "photoDome";
  111049. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  111050. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  111051. if (options.useDirectMapping === undefined) {
  111052. _this._useDirectMapping = true;
  111053. }
  111054. else {
  111055. _this._useDirectMapping = options.useDirectMapping;
  111056. }
  111057. _this._setReady(false);
  111058. // create
  111059. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  111060. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  111061. // configure material
  111062. material.opacityFresnel = false;
  111063. material.useEquirectangularFOV = true;
  111064. material.fovMultiplier = 1.0;
  111065. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  111066. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  111067. if (onError) {
  111068. onError(message, exception);
  111069. }
  111070. });
  111071. _this.photoTexture.onLoadObservable.addOnce(function () {
  111072. _this._setReady(true);
  111073. });
  111074. // configure mesh
  111075. _this._mesh.material = material;
  111076. _this._mesh.parent = _this;
  111077. return _this;
  111078. }
  111079. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  111080. /**
  111081. * Gets or sets the texture being displayed on the sphere
  111082. */
  111083. get: function () {
  111084. return this._photoTexture;
  111085. },
  111086. set: function (value) {
  111087. if (this._photoTexture === value) {
  111088. return;
  111089. }
  111090. this._photoTexture = value;
  111091. if (this._useDirectMapping) {
  111092. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111093. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111094. this._material.diffuseTexture = this._photoTexture;
  111095. }
  111096. else {
  111097. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  111098. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111099. this._material.reflectionTexture = this._photoTexture;
  111100. }
  111101. },
  111102. enumerable: true,
  111103. configurable: true
  111104. });
  111105. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  111106. /**
  111107. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  111108. * Also see the options.resolution property.
  111109. */
  111110. get: function () {
  111111. return this._material.fovMultiplier;
  111112. },
  111113. set: function (value) {
  111114. this._material.fovMultiplier = value;
  111115. },
  111116. enumerable: true,
  111117. configurable: true
  111118. });
  111119. /**
  111120. * Releases resources associated with this node.
  111121. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  111122. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  111123. */
  111124. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  111125. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  111126. this._photoTexture.dispose();
  111127. this._mesh.dispose();
  111128. this._material.dispose();
  111129. this.onLoadErrorObservable.clear();
  111130. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  111131. };
  111132. return PhotoDome;
  111133. }(BABYLON.TransformNode));
  111134. BABYLON.PhotoDome = PhotoDome;
  111135. })(BABYLON || (BABYLON = {}));
  111136. //# sourceMappingURL=babylon.photoDome.js.map
  111137. var BABYLON;
  111138. (function (BABYLON) {
  111139. BABYLON.Engine.prototype.createQuery = function () {
  111140. return this._gl.createQuery();
  111141. };
  111142. BABYLON.Engine.prototype.deleteQuery = function (query) {
  111143. this._gl.deleteQuery(query);
  111144. return this;
  111145. };
  111146. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  111147. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  111148. };
  111149. BABYLON.Engine.prototype.getQueryResult = function (query) {
  111150. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  111151. };
  111152. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  111153. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111154. this._gl.beginQuery(glAlgorithm, query);
  111155. return this;
  111156. };
  111157. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  111158. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  111159. this._gl.endQuery(glAlgorithm);
  111160. return this;
  111161. };
  111162. BABYLON.Engine.prototype._createTimeQuery = function () {
  111163. var timerQuery = this.getCaps().timerQuery;
  111164. if (timerQuery.createQueryEXT) {
  111165. return timerQuery.createQueryEXT();
  111166. }
  111167. return this.createQuery();
  111168. };
  111169. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  111170. var timerQuery = this.getCaps().timerQuery;
  111171. if (timerQuery.deleteQueryEXT) {
  111172. timerQuery.deleteQueryEXT(query);
  111173. return;
  111174. }
  111175. this.deleteQuery(query);
  111176. };
  111177. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  111178. var timerQuery = this.getCaps().timerQuery;
  111179. if (timerQuery.getQueryObjectEXT) {
  111180. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  111181. }
  111182. return this.getQueryResult(query);
  111183. };
  111184. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  111185. var timerQuery = this.getCaps().timerQuery;
  111186. if (timerQuery.getQueryObjectEXT) {
  111187. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  111188. }
  111189. return this.isQueryResultAvailable(query);
  111190. };
  111191. BABYLON.Engine.prototype.startTimeQuery = function () {
  111192. var caps = this.getCaps();
  111193. var timerQuery = caps.timerQuery;
  111194. if (!timerQuery) {
  111195. return null;
  111196. }
  111197. var token = new BABYLON._TimeToken();
  111198. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111199. if (caps.canUseTimestampForTimerQuery) {
  111200. token._startTimeQuery = this._createTimeQuery();
  111201. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  111202. }
  111203. else {
  111204. if (this._currentNonTimestampToken) {
  111205. return this._currentNonTimestampToken;
  111206. }
  111207. token._timeElapsedQuery = this._createTimeQuery();
  111208. if (timerQuery.beginQueryEXT) {
  111209. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111210. }
  111211. else {
  111212. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  111213. }
  111214. this._currentNonTimestampToken = token;
  111215. }
  111216. return token;
  111217. };
  111218. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  111219. var caps = this.getCaps();
  111220. var timerQuery = caps.timerQuery;
  111221. if (!timerQuery || !token) {
  111222. return -1;
  111223. }
  111224. if (caps.canUseTimestampForTimerQuery) {
  111225. if (!token._startTimeQuery) {
  111226. return -1;
  111227. }
  111228. if (!token._endTimeQuery) {
  111229. token._endTimeQuery = this._createTimeQuery();
  111230. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  111231. }
  111232. }
  111233. else if (!token._timeElapsedQueryEnded) {
  111234. if (!token._timeElapsedQuery) {
  111235. return -1;
  111236. }
  111237. if (timerQuery.endQueryEXT) {
  111238. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  111239. }
  111240. else {
  111241. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  111242. }
  111243. token._timeElapsedQueryEnded = true;
  111244. }
  111245. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  111246. var available = false;
  111247. if (token._endTimeQuery) {
  111248. available = this._getTimeQueryAvailability(token._endTimeQuery);
  111249. }
  111250. else if (token._timeElapsedQuery) {
  111251. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  111252. }
  111253. if (available && !disjoint) {
  111254. var result = 0;
  111255. if (caps.canUseTimestampForTimerQuery) {
  111256. if (!token._startTimeQuery || !token._endTimeQuery) {
  111257. return -1;
  111258. }
  111259. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  111260. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  111261. result = timeEnd - timeStart;
  111262. this._deleteTimeQuery(token._startTimeQuery);
  111263. this._deleteTimeQuery(token._endTimeQuery);
  111264. token._startTimeQuery = null;
  111265. token._endTimeQuery = null;
  111266. }
  111267. else {
  111268. if (!token._timeElapsedQuery) {
  111269. return -1;
  111270. }
  111271. result = this._getTimeQueryResult(token._timeElapsedQuery);
  111272. this._deleteTimeQuery(token._timeElapsedQuery);
  111273. token._timeElapsedQuery = null;
  111274. token._timeElapsedQueryEnded = false;
  111275. this._currentNonTimestampToken = null;
  111276. }
  111277. return result;
  111278. }
  111279. return -1;
  111280. };
  111281. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  111282. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  111283. };
  111284. // We also need to update AbstractMesh as there is a portion of the code there
  111285. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  111286. if (this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  111287. this._isOccluded = false;
  111288. return;
  111289. }
  111290. var engine = this.getEngine();
  111291. if (engine.webGLVersion < 2) {
  111292. this._isOccluded = false;
  111293. return;
  111294. }
  111295. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  111296. this._isOccluded = false;
  111297. return;
  111298. }
  111299. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  111300. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  111301. if (isOcclusionQueryAvailable) {
  111302. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  111303. this._isOcclusionQueryInProgress = false;
  111304. this._occlusionInternalRetryCounter = 0;
  111305. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  111306. }
  111307. else {
  111308. this._occlusionInternalRetryCounter++;
  111309. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  111310. this._isOcclusionQueryInProgress = false;
  111311. this._occlusionInternalRetryCounter = 0;
  111312. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  111313. // if strict continue the last state of the object.
  111314. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  111315. }
  111316. else {
  111317. return;
  111318. }
  111319. }
  111320. }
  111321. var scene = this.getScene();
  111322. if (scene.getBoundingBoxRenderer) {
  111323. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  111324. if (!this._occlusionQuery) {
  111325. this._occlusionQuery = engine.createQuery();
  111326. }
  111327. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  111328. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  111329. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  111330. this._isOcclusionQueryInProgress = true;
  111331. }
  111332. };
  111333. })(BABYLON || (BABYLON = {}));
  111334. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  111335. var BABYLON;
  111336. (function (BABYLON) {
  111337. /**
  111338. * Class used to generate noise procedural textures
  111339. */
  111340. var NoiseProceduralTexture = /** @class */ (function (_super) {
  111341. __extends(NoiseProceduralTexture, _super);
  111342. /**
  111343. * Creates a new NoiseProceduralTexture
  111344. * @param name defines the name fo the texture
  111345. * @param size defines the size of the texture (default is 256)
  111346. * @param scene defines the hosting scene
  111347. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  111348. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  111349. */
  111350. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  111351. if (size === void 0) { size = 256; }
  111352. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  111353. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  111354. _this._time = 0;
  111355. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  111356. _this.brightness = 0.2;
  111357. /** Defines the number of octaves to process */
  111358. _this.octaves = 3;
  111359. /** Defines the level of persistence (0.8 by default) */
  111360. _this.persistence = 0.8;
  111361. /** Gets or sets animation speed factor (default is 1) */
  111362. _this.animationSpeedFactor = 1;
  111363. _this._updateShaderUniforms();
  111364. return _this;
  111365. }
  111366. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  111367. var scene = this.getScene();
  111368. if (!scene) {
  111369. return;
  111370. }
  111371. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  111372. this.setFloat("brightness", this.brightness);
  111373. this.setFloat("persistence", this.persistence);
  111374. this.setFloat("timeScale", this._time);
  111375. };
  111376. NoiseProceduralTexture.prototype._getDefines = function () {
  111377. return "#define OCTAVES " + (this.octaves | 0);
  111378. };
  111379. /** Generate the current state of the procedural texture */
  111380. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  111381. this._updateShaderUniforms();
  111382. _super.prototype.render.call(this, useCameraPostProcess);
  111383. };
  111384. /**
  111385. * Serializes this noise procedural texture
  111386. * @returns a serialized noise procedural texture object
  111387. */
  111388. NoiseProceduralTexture.prototype.serialize = function () {
  111389. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  111390. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  111391. return serializationObject;
  111392. };
  111393. /**
  111394. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  111395. * @param parsedTexture defines parsed texture data
  111396. * @param scene defines the current scene
  111397. * @param rootUrl defines the root URL containing noise procedural texture information
  111398. * @returns a parsed NoiseProceduralTexture
  111399. */
  111400. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  111401. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  111402. return texture;
  111403. };
  111404. return NoiseProceduralTexture;
  111405. }(BABYLON.ProceduralTexture));
  111406. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  111407. })(BABYLON || (BABYLON = {}));
  111408. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  111409. var __assign = (this && this.__assign) || function () {
  111410. __assign = Object.assign || function(t) {
  111411. for (var s, i = 1, n = arguments.length; i < n; i++) {
  111412. s = arguments[i];
  111413. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  111414. t[p] = s[p];
  111415. }
  111416. return t;
  111417. };
  111418. return __assign.apply(this, arguments);
  111419. };
  111420. var BABYLON;
  111421. (function (BABYLON) {
  111422. /**
  111423. * This can helps recording videos from BabylonJS.
  111424. * This is based on the available WebRTC functionalities of the browser.
  111425. *
  111426. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  111427. */
  111428. var VideoRecorder = /** @class */ (function () {
  111429. /**
  111430. * Create a new VideoCapture object which can help converting what you see in Babylon to
  111431. * a video file.
  111432. * @param engine Defines the BabylonJS Engine you wish to record
  111433. * @param options Defines options that can be used to customized the capture
  111434. */
  111435. function VideoRecorder(engine, options) {
  111436. if (options === void 0) { options = null; }
  111437. if (!VideoRecorder.IsSupported(engine)) {
  111438. throw "Your browser does not support recording so far.";
  111439. }
  111440. var canvas = engine.getRenderingCanvas();
  111441. if (!canvas) {
  111442. throw "The babylon engine must have a canvas to be recorded";
  111443. }
  111444. this._canvas = canvas;
  111445. this._canvas.isRecording = false;
  111446. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  111447. var stream = this._canvas.captureStream(this._options.fps);
  111448. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  111449. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  111450. this._mediaRecorder.onerror = this._handleError.bind(this);
  111451. this._mediaRecorder.onstop = this._handleStop.bind(this);
  111452. }
  111453. /**
  111454. * Returns wehther or not the VideoRecorder is available in your browser.
  111455. * @param engine Defines the Babylon Engine to check the support for
  111456. * @returns true if supported otherwise false
  111457. */
  111458. VideoRecorder.IsSupported = function (engine) {
  111459. var canvas = engine.getRenderingCanvas();
  111460. return (!!canvas && typeof canvas.captureStream === "function");
  111461. };
  111462. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  111463. /**
  111464. * True wether a recording is already in progress.
  111465. */
  111466. get: function () {
  111467. return !!this._canvas && this._canvas.isRecording;
  111468. },
  111469. enumerable: true,
  111470. configurable: true
  111471. });
  111472. /**
  111473. * Stops the current recording before the default capture timeout passed in the startRecording
  111474. * functions.
  111475. */
  111476. VideoRecorder.prototype.stopRecording = function () {
  111477. if (!this._canvas || !this._mediaRecorder) {
  111478. return;
  111479. }
  111480. if (!this.isRecording) {
  111481. return;
  111482. }
  111483. this._canvas.isRecording = false;
  111484. this._mediaRecorder.stop();
  111485. };
  111486. /**
  111487. * Starts recording the canvas for a max duration specified in parameters.
  111488. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  111489. * @param maxDuration Defines the maximum recording time in seconds.
  111490. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  111491. * @return a promise callback at the end of the recording with the video data in Blob.
  111492. */
  111493. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  111494. var _this = this;
  111495. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  111496. if (maxDuration === void 0) { maxDuration = 7; }
  111497. if (!this._canvas || !this._mediaRecorder) {
  111498. throw "Recorder has already been disposed";
  111499. }
  111500. if (this.isRecording) {
  111501. throw "Recording already in progress";
  111502. }
  111503. if (maxDuration > 0) {
  111504. setTimeout(function () {
  111505. _this.stopRecording();
  111506. }, maxDuration * 1000);
  111507. }
  111508. this._fileName = fileName;
  111509. this._recordedChunks = [];
  111510. this._resolve = null;
  111511. this._reject = null;
  111512. this._canvas.isRecording = true;
  111513. this._mediaRecorder.start(this._options.recordChunckSize);
  111514. return new Promise(function (resolve, reject) {
  111515. _this._resolve = resolve;
  111516. _this._reject = reject;
  111517. });
  111518. };
  111519. /**
  111520. * Releases internal resources used during the recording.
  111521. */
  111522. VideoRecorder.prototype.dispose = function () {
  111523. this._canvas = null;
  111524. this._mediaRecorder = null;
  111525. this._recordedChunks = [];
  111526. this._fileName = null;
  111527. this._resolve = null;
  111528. this._reject = null;
  111529. };
  111530. VideoRecorder.prototype._handleDataAvailable = function (event) {
  111531. if (event.data.size > 0) {
  111532. this._recordedChunks.push(event.data);
  111533. }
  111534. };
  111535. VideoRecorder.prototype._handleError = function (event) {
  111536. this.stopRecording();
  111537. if (this._reject) {
  111538. this._reject(event.error);
  111539. }
  111540. else {
  111541. throw new event.error;
  111542. }
  111543. };
  111544. VideoRecorder.prototype._handleStop = function () {
  111545. this.stopRecording();
  111546. var superBuffer = new Blob(this._recordedChunks);
  111547. if (this._resolve) {
  111548. this._resolve(superBuffer);
  111549. }
  111550. window.URL.createObjectURL(superBuffer);
  111551. if (this._fileName) {
  111552. BABYLON.Tools.Download(superBuffer, this._fileName);
  111553. }
  111554. };
  111555. VideoRecorder._defaultOptions = {
  111556. mimeType: "video/webm",
  111557. fps: 25,
  111558. recordChunckSize: 3000
  111559. };
  111560. return VideoRecorder;
  111561. }());
  111562. BABYLON.VideoRecorder = VideoRecorder;
  111563. })(BABYLON || (BABYLON = {}));
  111564. //# sourceMappingURL=babylon.videoRecorder.js.map
  111565. var BABYLON;
  111566. (function (BABYLON) {
  111567. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  111568. if (replace === void 0) { replace = false; }
  111569. // Dispose existing light in replace mode.
  111570. if (replace) {
  111571. if (this.lights) {
  111572. for (var i = 0; i < this.lights.length; i++) {
  111573. this.lights[i].dispose();
  111574. }
  111575. }
  111576. }
  111577. // Light
  111578. if (this.lights.length === 0) {
  111579. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  111580. }
  111581. };
  111582. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  111583. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  111584. if (replace === void 0) { replace = false; }
  111585. if (attachCameraControls === void 0) { attachCameraControls = false; }
  111586. // Dispose existing camera in replace mode.
  111587. if (replace) {
  111588. if (this.activeCamera) {
  111589. this.activeCamera.dispose();
  111590. this.activeCamera = null;
  111591. }
  111592. }
  111593. // Camera
  111594. if (!this.activeCamera) {
  111595. var worldExtends = this.getWorldExtends();
  111596. var worldSize = worldExtends.max.subtract(worldExtends.min);
  111597. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  111598. var camera;
  111599. var radius = worldSize.length() * 1.5;
  111600. // empty scene scenario!
  111601. if (!isFinite(radius)) {
  111602. radius = 1;
  111603. worldCenter.copyFromFloats(0, 0, 0);
  111604. }
  111605. if (createArcRotateCamera) {
  111606. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  111607. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  111608. arcRotateCamera.wheelPrecision = 100 / radius;
  111609. camera = arcRotateCamera;
  111610. }
  111611. else {
  111612. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  111613. freeCamera.setTarget(worldCenter);
  111614. camera = freeCamera;
  111615. }
  111616. camera.minZ = radius * 0.01;
  111617. camera.maxZ = radius * 1000;
  111618. camera.speed = radius * 0.2;
  111619. this.activeCamera = camera;
  111620. var canvas = this.getEngine().getRenderingCanvas();
  111621. if (attachCameraControls && canvas) {
  111622. camera.attachControl(canvas);
  111623. }
  111624. }
  111625. };
  111626. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  111627. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  111628. if (replace === void 0) { replace = false; }
  111629. if (attachCameraControls === void 0) { attachCameraControls = false; }
  111630. this.createDefaultLight(replace);
  111631. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  111632. };
  111633. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  111634. if (pbr === void 0) { pbr = false; }
  111635. if (scale === void 0) { scale = 1000; }
  111636. if (blur === void 0) { blur = 0; }
  111637. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  111638. if (!environmentTexture) {
  111639. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  111640. return null;
  111641. }
  111642. if (setGlobalEnvTexture) {
  111643. if (environmentTexture) {
  111644. this.environmentTexture = environmentTexture;
  111645. }
  111646. }
  111647. // Skybox
  111648. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  111649. if (pbr) {
  111650. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  111651. hdrSkyboxMaterial.backFaceCulling = false;
  111652. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  111653. if (hdrSkyboxMaterial.reflectionTexture) {
  111654. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111655. }
  111656. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  111657. hdrSkyboxMaterial.disableLighting = true;
  111658. hdrSkyboxMaterial.twoSidedLighting = true;
  111659. hdrSkybox.infiniteDistance = true;
  111660. hdrSkybox.material = hdrSkyboxMaterial;
  111661. }
  111662. else {
  111663. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  111664. skyboxMaterial.backFaceCulling = false;
  111665. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  111666. if (skyboxMaterial.reflectionTexture) {
  111667. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  111668. }
  111669. skyboxMaterial.disableLighting = true;
  111670. hdrSkybox.infiniteDistance = true;
  111671. hdrSkybox.material = skyboxMaterial;
  111672. }
  111673. return hdrSkybox;
  111674. };
  111675. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  111676. if (BABYLON.EnvironmentHelper) {
  111677. return new BABYLON.EnvironmentHelper(options, this);
  111678. }
  111679. return null;
  111680. };
  111681. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  111682. if (webVROptions === void 0) { webVROptions = {}; }
  111683. return new BABYLON.VRExperienceHelper(this, webVROptions);
  111684. };
  111685. })(BABYLON || (BABYLON = {}));
  111686. //# sourceMappingURL=babylon.sceneHelpers.js.map
  111687. 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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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#ifdef ALPHATEST\nuniform float alphaCutOff;\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<alphaCutOff)\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) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\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;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\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;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\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;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\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(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\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#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 SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,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);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=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.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=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;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\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(-viewDirectionW,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.rgb*=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.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\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#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\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 float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\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}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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}","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;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\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;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\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\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\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);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\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}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\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}","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\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\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\nvec4 reflectionColor=vec4(1.,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);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=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.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\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.rgb,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","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  111688. 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\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\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};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(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;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(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 REFLECTION\nuniform mat4 reflectionMatrix;\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=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\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\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\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\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\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\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>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}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(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#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(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#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif 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 vec4 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 vec4 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 vec4 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#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\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 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\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};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.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*info.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*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,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;\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;\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}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\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};","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;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\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 vPrimaryColorShadow;\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};"};